Re: heap enhancements

2020-01-04 Thread Peter Otten
jezka...@gmail.com wrote:

> ok, so it could be like this?

Easy things to improve:

(1) Avoid iterating over indices.

Wrong: 

for i in range(len(stuff)):
item = stuff[i]
...

Better:

for item in stuff:
...

(1a) If you need the index use enumerate():

for i, value in enumerate(stuff)
if value < 0: stuff[i] = -value

(1b) Instead of modifiying a container it is often more convenient to build 
a new one

stuff = [abs(v) for v in stuff] # common way
stuff = list(map(abs, stuff))   # also possible

(2) Test for "truthiness" rather than object identity

Wrong:

if x is True:
...

Better:

if x:
...

(3) Avoid toplevel code, or at least move it to the end of the script and 
guard it with

if __name__ == "__main__": ...

Wrong:

do stuff
def foo(): ...
do more stuff
class Bar:
   ...
do even more stuff

Better

def foo(): ...
class Bar: ...

def main():
do stuff
do more stuff
do even more stuff

if __name__ == "__main__":
main()


(4) Choose names carefully.

> def checking(chain):

The function name should tell what is checked, e. g.

def is_valid_int(text):

(5) Parameterize your code to simplify tests and refactoring.

Wrong:

> chain = sys.stdin.read().splitlines()
> array_z = list()
> for line in chain:
> row=list(map(str, line.split()))
> array_z.append(row)
> #every line in input changes into 2D array

Better:

def read_2d_array(instream):
"""Read whitespace-separated pairs from `instream`.
Returns a list of 2-tuples. 
pairs = []
for line in instream:
pair = line.split()
if len(pair) != 2: 
raise ValueError
pairs.append(pair)
return pairs

array_z = read_2d_array(sys.stdin)

If you later decide to support files the change is obvious:

filename = ...
if filename == "-":
array_z = read_2d_array(sys.stdin)
else:
with open(filename) as instream
array_z = read_2d_array(instream)

(Somewhat advanced: read_2d_array() could also be a generator yielding 
pairs.)

> def checking(chain):
> "checking if characters are numbers or not"
> for char in chain:
> if char not in "0123456789-":
> return False
> return True

This check is tedious and incomplete as it allows "-" in arbitrary 
positions. Instead of testing the string for correctness before you convert 
it it is often more convenient to try the conversion and cope with the 
exception that may be raised. Instead of

# this is called "look before you leap", or LBYL
if is_valid_int_string(some_string):
   intval = int(some_string)
else:
   handle error

# "it's easier to ask for forgiveness than permission", or EAFP
try:
intval = int(s)
except ValueError:
handle error
-
 
> class MaxHeap:
> def __init__(self):
> """heap __init__ constructor"""
> self.heap =[]
> def bubble_up(self, i):
> bubble the element up if condition is ok """
> while i > 0:
> j = (i - 1) // 2
> if self.heap[i] <= self.heap[j]:
> break
> self.heap[j], self.heap[i] = self.heap[i], self.heap[j]
> i = j
> def insert(self, k):
> """insert element in heap"""
> self.heap += [k]
> self.bubble_up(len(self.heap) - 1)
> def peek(self):
> """return the biggest element"""
> return self.heap[0]

> def size(self):
> """return quantity of elements in heap"""
> return len(self.heap)
> def is_empty(self):
> """is heap empty?"""
> return self.size() == 0

The pythonic replacement for size() and is_empty() is

 def __len__(self):
return len(self.heap)

You can then replace

  myheap = MaxHeap()
  print(myheap.size())
  if myheap.is_empty(): print("myheap is empty")

with
  print(len(myheap))
  if not myheap: print("myheap is empty")

> def bubble_down(self, i):
> """bubble down the element"""
> n = self.size()
> while 2 * i + 1 < n:
> j = 2 * i + 1
> if j + 1 < n and self.heap[j] < self.heap[j + 1]:
> j += 1
> if self.heap[i] < self.heap[j]:
> self.heap[i], self.heap[j] = self.heap[j], self.heap[i]
> i = j
> def pop(self):
> """delete the biggest element and change the heap"""
> element = self.heap[0]
> self.heap[0] = self.heap[-1]
> self.heap.pop()
> self.bubble_down(0)
> return element
> 
> for i in range (len( array_z)):
> for j in range (len( array_z[i])):
> digit_z= array_z[i][j]
> if digit_z.isdigit() is True:
> array_z[i][j]=int( array_z[i][j])
> check =checking(digit_z)
> if check is True:
> array_z[i][j]=int( array_z[i][j])
> 
> Heap=MaxHeap()
> for a in range (len( array_z)):
> if  array_z[a][0]>0:
> Heap.insert( array_z[a])
> if  array_z[a][0] < 0:
> print( array_z[a][1]+": ",

Re: Python, Be Bold!

2020-01-04 Thread Marko Rauhamaa
Greg Ewing :
> You can pass a zip file with a .pyz extension to the python
> interpreter and it will look for a __main__.py file and run
> it.

This discussion has been interesting, and I've now learned about zipapp.
This is really nice and will likely be a favorite distribution format
for Python applications.

My initial instinct would be to use zipapp as follows:

 * The starting point is a directory containing the Python source files,
   possibly with subdirectories. (A simple, two-file example:
   "myapp.py", "auxmod.py".)

   Be sure that "myapp.py" contains the boilerplate footer:

   if __name__ == '__main__':
   main()

 * Test that the program works:

   $ ./myapp.py
   hello

 * Generate the zipapp:

   $ python3 -m zipapp . -o ../myapp.pyz --main myapp:main \
   -p "/usr/bin/env python3"

 * Try it out:

   $ ../myapp.pyz
   hello


Marko
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: A small quiz

2020-01-04 Thread 황병희
Greg Ewing  writes:

> On 4/01/20 5:41 am, Alan Bawden wrote:
>>>So I was looking for a predefined object from the standard
>>>library that already /is/ an iterator (with no need to use
>>>»iter«).
>
> Why are you so intent on introducing either next() or iter() to
> beginning students? I'd have thought they were somewhat advanced
> topics, to be tackled after your students are familiar with the
> basics.

Also i think that topic is somewhat difficult. Anyway thanks for
introducing, Stefan(OP)^^^

Sincerely,

-- 
^고맙습니다 _地平天成_ 감사합니다_^))//
-- 
https://mail.python.org/mailman/listinfo/python-list


[no subject]

2020-01-04 Thread William Johnsson
Hello! My name is William and im 14 years old and live in sweden.  Im pretty 
new to programing in python and i need some help with code, (That’s why i’m 
here). But i couldn’t really find what i was searching for on the internet. I’m 
trying to write code that can check only the first line in a .txt file and 
check if it’s the same as the int 1000.   I preferably want it to be an if 
satement but anything works, i just don’t know how i should write it. I’ve been 
browsing the internet for a solution but sadly can’t seem to find a solution to 
it.

I don’t really know if this is the right way to get help or even if this email 
is for something else. Hopefully i will get some kind of response.

Best regards, William
-- 
https://mail.python.org/mailman/listinfo/python-list


Re:

2020-01-04 Thread Michael Torrie
On 1/4/20 3:29 PM, William Johnsson wrote:
> Hello! My name is William and im 14 years old and live in sweden.  Im
> pretty new to programing in python and i need some help with code,
> (That’s why i’m here). But i couldn’t really find what i was
> searching for on the internet. I’m trying to write code that can
> check only the first line in a .txt file and check if it’s the same
> as the int 1000.   I preferably want it to be an if satement but
> anything works, i just don’t know how i should write it. I’ve been
> browsing the internet for a solution but sadly can’t seem to find a
> solution to it.
> 
> I don’t really know if this is the right way to get help or even if
> this email is for something else. Hopefully i will get some kind of
> response.
> 
> Best regards, William

Welcome, William.  Another mailing list you might want to post to is the
Python Tutor list (https://mail.python.org/mailman/listinfo/tutor) which
is focused on people learning Python.

Seems like your problem can be broken down into a few steps:
1. Open a file
2. Read the first line
3. look for "1000" in that line.

Learning how to read from a text file would probably be the first thing
to look into.  See in particular chapter 7.2 in this section of official
tutorial.  https://docs.python.org/3/tutorial/inputoutput.html

You may also google for other examples of opening and reading lines from
a text file in Python.

Once you've been able to read in a line, you can do a simple search in
that line using the "in" keyword (mentioned part way down the page
https://docs.python.org/3/library/stdtypes.html in the section called
"Common Sequence Operations").

Hopefully you'll find this useful rather than just giving you a complete
little program (where's the fun in that!).


-- 
https://mail.python.org/mailman/listinfo/python-list