vlady 0 Junior Poster in Training

Hello!

I try to get py output to html table tag. I have a problem to create table in a table...
Here is a pattern how it should look like (in yellow color)
file name: format_DOC.doc

here is the code I use to get a result. Pls can you help me how to make it?

Code blocks are created by indenting at least 4 spaces
... and can span multiple lines

            import webbrowser
            firefox = webbrowser.get()

            premene=['x','y','z']
            marks=['1','2','3']
            text='xxxxxx'
            space=' '

            def skuska1():
                p=''
                for i in premene:
                    p+=i+'<td>'
                return p

            def skuska2():
                m=''
                for i in marks:
                    m+=i+'<td>'
                return m

            def skuska3():
                return text

            def writing():
                vytvor=open('test.html','w')

                for record in ['<table border="1" cellpadding="15" cellspacing="0" width="80%" height="25%">'
                '<tr>'
                    '<th colspan="2">HEADER</th>'
                        '</tr>'
                '<tr>'
                    '<td width="50%">text2:<p style="text-align:center;">',skuska3(),'</p></td>\<td>text 3</td>'
                        '</tr>'
                '<tr>'
                    '<td width="25%"colspan="2">text4:</td>'
                         '</tr>'
                '<tr>'
                    '<th>header</th><th>header</th>'
                          '</tr>'
                '<td>'
                '<table border="1" cellpadding="0" cellspacing="0"width="80%" height="25%">'
                '<tr>'
                    '<td>',skuska1(),'</td></tr><td>',skuska2(),'</td></tr>'
                         '</tr>'
                            '</table>'
                 '</td>'
                  '<tr>'
                    '<td width="50%"colspan="2">text7:</td>'
                        '</tr>'
                '<tr>'
                    '<td width="50%"colspan="2">text 8</td>'
                        '</tr>'
                            '</table>']:
                    vytvor.write("%s\n" % (record))




            def main():
                writing()
                firefox.open('test.html')

            if __name__ == '__main__':
                main()
vlady 0 Junior Poster in Training

Hello
I try to get py output (s_subject) to a web bage table using html code. Thing is that result is in one line. I'd like to have it for each subject one line. Pls can you show me how to make it?
Example:

Predmet: 
         maths
         fyzics
         history

here is a code:

Code blocks are created by indenting at least 4 spaces
... and can span multiple lines



    import webbrowser
    firefox = webbrowser.get()

    subjects=['maths','fyzics','history']
    space=' '

    def stud_subject():
        s=''
        for i in subjects:
            s+=i+'\n'
        s_subject=s
        return s_subject




    def writing():
        vytvor=open('vysvedcenie_test.html','w')

        line1='<table border="1" cellpadding="15" cellspacing="5" width="100%">'
        line2='<tr>'
        line3='<th colspan="2">Vysvedcenie</th>'
        line4='</tr>'
        line5='<tr>'
        line6='<td width="50%">Meno, Priezvisko:</td>\<td>Skolsky rok:</td>'
        line7='</tr>'
        line8='<tr>'
        line9='<td width="25%">Kruzok:</td>'
        line10='</tr>'
        line11='<tr>'
        line12='<td width="50%">Predmety:'+space+stud_subject()+'</td>\ <td>Hodnotenie:</td>'
        line13='</tr>'
        line14='<tr>'
        line15='<td width="50%">Celkovy prospech:</td>'
        line16='</tr>'
        line17='<tr>'
        line18='<td width="50%">Menovany student presiel do dalsieho rocnika (ano/nie):</td>'
        line19='</tr>'
        line20='</table>'


        vytvor.write(line1)
        vytvor.write(line2)
        vytvor.write(line3)
        vytvor.write(line4)
        vytvor.write(line5)
        vytvor.write(line6)
        vytvor.write(line7)
        vytvor.write(line8)
        vytvor.write(line9)
        vytvor.write(line10)
        vytvor.write(line11)
        vytvor.write(line12)
        vytvor.write(line13)
        vytvor.write(line14)
        vytvor.write(line15)
        vytvor.write(line16)
        vytvor.write(line17)
        vytvor.write(line18)
        vytvor.write(line19)
        vytvor.write(line20)
        vytvor.close()


    def main():
        stud_subject()
        writing()
        firefox.open('vysvedcenie_test.html')

    if __name__ == '__main__':
        main()
vlady 0 Junior Poster in Training

Hello,

I need help to get all together. Pls see 2 different codes below .

1 code:
Represents format for final result paper called "vysvedcenie" (evaluation) for a particular student.

code:

def do_once(f):
    f()

def do_twice(f):
    f()
    f()

def do_four(f):
    do_twice(f)
    do_twice(f)

def hlavicka():
    print 'x',' '*40+'VYSVEDCENIE'+' '*46+'x'

def vertikal():
    print 'x'+' '*98+'x'


def horizontal():
    print 'xxxxx'*20

def udaje_student():
    print 'x  Meno, Priezvisko:',' '*40,'Skolsky rok:',' '*24+'x'
    print 'x  Kruzok:',' '*87,'x'

def hodnotenie():
    print 'x  Predmety:', ' '*30,'Hodnotenie:',' '*43+'x'

def zaver():
    print 'x  Celkovy prospech:',' '*77,'x'
    print 'x  Menovany student presiel do dalsieho rocnika (ano/nie):',' '*39,'x'

def format_vysvedcenie():
    horizontal()
    hlavicka()
    horizontal()
    do_once(vertikal)
    udaje_student()
    horizontal()
    do_once(vertikal)
    hodnotenie()
    do_four(vertikal)
    do_four(vertikal)
    horizontal()
    do_once(vertikal)
    zaver()
    do_once(vertikal)
    horizontal()

def main():
    print format_vysvedcenie()

if __name__ == '__main__':
    main()

output of this code is (attachement): output_vysvedcenie.doc

2 code:
Represents all information about students (who are defined inside Class). This code gives you all info about the particular student.

Here is a code:

class Cstudent():
    def __init__(self, name):
        self.name = name
        self.predmety = []
        self.priemer = []

    def add_subject(self, predmet):
        'pridanie predmentu danemu studentovi'
        self.predmety.append(predmet)

    def add_mark(self,predmet,mark):
        'pridanie znamky danemu studentovi'
        for i in self.predmety:
            if i.nazov == predmet:
                i.add_znamka(mark)

    def priemer_student(self):
        'vytvorenie priemernej znamky zo vsetkyvh predmetov pre daneho studenta'
        lstz=[]
        for predmet in self.predmety:
            for znamka in predmet.znamky:
                lstz.append(znamka)
        self.priemer= float(sum(lstz)) / float(len(lstz))

    def get_predmet(self,predmet):
        'nastroj, ktory vrati objekt predmetov'
        for i in self.predmety:
            if i.nazov==predmet:
                return i

    def __str__(self):
        return 'Meno studenta: %s \nCelkovy priemer: %s' % …
vlady 0 Junior Poster in Training

uuups! ok,thanks! - but it seems to be complicated....
my level in classes is not such high.

vlady 0 Junior Poster in Training

Well, apparently, this approach of classes may cause some inconvenients due to the fact that it's not the brightest approach.

Try to define some functions which will print that things for you, from inside the class, use some functions to add elements to the class, then, in the main function, to call accordingly to class calls the actual class and the print functions inside that class.
One final thought: Use a run() function inside the class to gather all the functions needed in this process, so that you would have to call only 1 function from the class in the main function.
Here's some information about classes:
http://docs.python.org/tutorial/classes.html#classes
If you need further information, or if there're any misunderstandings regarding this topic feel free to post them here...

ok, I don´t know if this my example is good approach or not. I am learning it by using exercices... In a book, I foud out that there is not a lot of examples. For me exmples works!
Pls give me an example to what is a good approach. If I see it I will learn it much easy way.

vlady 0 Junior Poster in Training

hi!

I have another struggle. I'd like to have this kind of output:
som object studenta: Janko Mrkvicka
som object predmetu: fyzika, mam znamky: [4, 1] a priemer: 2,5

How can I make it?

my output is a bit different (it is in last line):

som object studenta: Janko Mrkvicka
som object predmetu: fyzika, mam znamky: [4, 1] a priemer: 0
som object predmetu: english, mam znamky: [1] a priemer: 0
som object predmetu: matematika, mam znamky: [] a priemer: 0
2
None
-----------------------------------------------------
som object studenta: Janka Vaskova
som object predmetu: dejepis, mam znamky: [1, 2, 3] a priemer: 0
som object predmetu: biologia, mam znamky: [] a priemer: 0
som object predmetu: english, mam znamky: [] a priemer: 0
som object predmetu: fyzika, mam znamky: [1] a priemer: 0
1
None
here is a complete code:

class Cstudent():
    def __init__(self, name):
        self.name = name
        self.predmety = []
        self.mark = []
        self.absence = 0

    def add_subject(self, predmet):
        self.predmety.append(predmet)

    def add_mark(self,predmet,mark):
        for i in self.predmety:
            if i.nazov == predmet:
                i.add_znamka(mark)

    def priemer_predmet(self,predmet):
        for i in self.predmety:
            if i.nazov == predmet:
                i.average_predmet(predmet)

    def __str__(self):
        #return self.name
        #return 'som objekt studenta: ' + (self.name)
        return 'som object studenta: %s'% (self.name)

    def print_zoznam_predmetov(self):
        lst = []
        for prd in self.predmety:
            lst.append(str(prd))
        return '\n'.join(lst)
        #return '\n'.join(lst)


class Cpredmet():
    def __init__(self, nazov):
        self.nazov = nazov
        self.znamky = []
        self.priemer = int()

    def add_znamka(self, znamka): …
vlady 0 Junior Poster in Training

I do not think I understand what is all this fuss but maybe something like:

def add_mark(self, predmet,mark):
        for p in self.predmety:
            #print p.nazov
            if p.nazov == predmet:
                p.add_znamka(mark)
                break
        else:
            raise ValueError("%s not taking course %s" % (self.name, predmet))

super! thank you!

vlady 0 Junior Poster in Training

Hello!

I don´t understand how to use a condition " if i == predmet: " i is an objet type of subject

In my code I need to reach the condition:

def add_mark(self,predmet,mark):
        for i in self.predmety:
            if i == predmet:
                print True

but I don´t know how to make this condition true => "if i == predmet"
"i" is an object and it will never match this condition.
I need to get like:
if fyzika == fyzika:
print True

but i is always object and I don´t know how to chanhe it to non object. Can you help?

here is the rest of the code:

class Cstudent():
    def __init__(self, name):
        self.name = name
        self.predmety = []
        self.mark = []
        self.absence = 0

    def add_subject(self, predmet):
        self.predmety.append(predmet)

    def add_mark(self,predmet,mark):
        for i in self.predmety:
            if i == predmet:
                print True
                #predmet.add_znamka(mark)

    def __str__(self):
        return self.name
        #return 'som objekt studenta: ' + (self.name)
##        return 'som object studenta: %s'% \
##            (self.name)

    def print_zoznam_predmetov(self):
        lst = []
        for prd in self.predmety:
            lst.append(str(prd))
        return '\n'.join(lst)


class Cpredmet():
    def __init__(self, nazov):
        self.nazov = nazov
        self.znamky = []

    def add_znamka(self, znamka):
        self.znamky.append(znamka)

    def average_predmet(self, predmet):
        return sum(self.znamky) / len(self.znamky)

    def __str__(self):
        return self.nazov
##        return 'som object predmetu: %s a mam znamky: %s' % \
##            (self.nazov, str(self.znamky))

def main():

#-------------------------------
    janko = Cstudent('Janko Mrkvicka')
    janka = Cstudent ('Janka Vaskova')

#-------------------------------
    janko.add_subject(Cpredmet('fyzika'))
    janko.add_subject(Cpredmet('english'))

    janka.add_subject(Cpredmet('dejepis'))
    janka.add_subject(Cpredmet('fyzika'))

#-------------------------------
    janko.add_mark(predmet='fyzika',mark=4)
    janko.add_mark(predmet='fyzika',mark=1)
    janko.add_mark(predmet='english',mark=1)

    janka.add_mark(predmet='dejepis',mark=2)
    janka.add_mark(predmet='dejepis',mark=3)
    janka.add_mark(predmet='fyzika',mark=1)

# output:
#------------------------------- …
vlady 0 Junior Poster in Training

Hello,

pls can anybody show how works printing? here is the code:

class Student(object):
    def __init__(self, name):
        self.name = name
        self.report = dict()


    def add_subject(self, subject):
        self.report[subject] = list()


    def subjects(self):
        return self.report.keys()


    def s_subjects(self):
        lpre=[]
        for subject in self.subjects():
            lpre.append(str(subject))
        print lpre


class Subject(object):
    def __init__(self, name, teacher = "unknown"):
        self.name = name
        self.teacher = teacher

def main():
    janko = Student('Janko Moor')
    janka = Student ('Janka Vaskova')

    fyz = Subject('fyzic')
    eng = Subject('english')
    mat = Subject('matematic')
    hist= Subject('history')
    bio = Subject('biology')

    janko.add_subject(fyz)
    janko.add_subject(eng)
    janko.add_subject(mat)


    print janko.s_subjects()

if __name__ == '__main__':
    main()

I just need to know the principe how to print the subjects of the student (janko). I am a bit struggling because it always shows me "objects" of all subjects. I need to see it like: matematic, fyzic,...etc. I really don´t know what I need to add to the code to make it appropriate. Pls can you show me?

vlady 0 Junior Poster in Training

hello

Thank you for the example! I don´t understand this method you wrote, pls can you explain it for better understanding? (if you can make a simple equivalent it would be great)
I appreciate!

def s_subjects(self):
        return ", ".join(subject.name for subject in self.subjects())
def __repr__(self):
        return "Student({0})".format(repr(self.name))
vlady 0 Junior Poster in Training

pls can you show me an example? (using code)

I tried something like this but doesn´t work.

class Cstudent():
    def __init__(self, name):
        self.name = name
        self.subjets = []
        self.mark = []
        self.report={}

        def test(self,subject):
             self.report[subject]=self.mark  

sefl.mark is supposed to be a list of marks => [1,2,3]
so I simly want to add to a subject for example fyz these mark
=> self.report={'fyz':[1,2,3]}
and this I like to joint to student name janko

I have a view but because I learn classes it´s quiet difficult to make it. If I have an examle, it´s better... I can progres quickly rather than spending a lot of time on it.

vlady 0 Junior Poster in Training

Hello!

Here is the code, pls have a look fist:

class Cstudent():
    def __init__(self, name):
        self.name = name
        self.subjets = []
        self.mark = []

    def add_subject(self, subject):
        self.subjets.append(subject)

    def add_mark_student(self, subject, mark):
            subject.add_mark(mark)

    def __str__(self):
        return 'I am object of student: %s'% \
        (self.name)

    def print_list_of_subjects(self):
        lst = []
        for prd in self.subjets:
            lst.append(str(prd))
        return '\n'.join(lst)

class Csubject():
    def __init__(self, name):
        self.name = name
        self.mark = []

    def add_mark(self, mark):
        self.mark.append(mark)

    def average_subject(self, subject):
        return sum(self.mark) / len(self.mark)

    def __str__(self):
        return 'I am object of subject: %s  and have marks: %s' % \
            (self.name, str(self.mark))


def main():

# inicalization of objekt - student:
#-------------------------------
    janko = Cstudent('Janko Moor')
    janka = Cstudent ('Janka Vaskova')

# inicialization of subjects:
#-------------------------------
    fyz = Csubject('fyzic')
    eng = Csubject('english')
    mat = Csubject('matematic')
    hist= Csubject('history')
    bio = Csubject('biology')

# adding a subject to a particular object:
#-------------------------------
    janko.add_subject(fyz)
    janko.add_subject(eng)
    janko.add_subject(mat)

    janka.add_subject(hist)
    janka.add_subject(bio)
    janka.add_subject(eng)
    janka.add_subject(fyz)

# adding a mark to a particular object:
#-------------------------------
    janko.add_mark_student(fyz, mark=4)
    janko.add_mark_student(fyz, mark=1)
    janko.add_mark_student(fyz, mark=1)

    janka.add_mark_student(hist,mark=1)
    janka.add_mark_student(hist,mark=2)
    janka.add_mark_student(hist,mark=3)
    janka.add_mark_student(fyz,mark=1)

# output:
#-------------------------------
    print janko
    print janko.print_list_of_subjects()
    print fyz.average_subject('fyzic')
    print '-----------------------------------------------------'
    print janka
    print janka.print_list_of_subjects()
    print hist.average_subject('history')


if __name__ == '__main__':
    main()

output:
I am object of student: Janko Moor
I am object of subject: fyzic and have marks: [4, 1, 1, 1]
I am object of subject: english and have marks: []
I am object of subject: matematic and have marks: []
1
-----------------------------------------------------
I am object of student: Janka Vaskova
I …

vlady 0 Junior Poster in Training

hello guys!

So I did something but I found out that is messy a bit. Look at the code:

class Cstudent():
    def __init__(self, name):
        self.name = name
        self.subjets = []
        self.mark = []

    def add_subject(self, subject):
        self.subjets.append(subject)

    def add_mark_student(self, subject, mark):
            subject.add_mark(mark)

    def __str__(self):
        return 'I am object of student: %s'% \
        (self.name)

    def print_list_of_subjects(self):
        lst = []
        for prd in self.subjets:
            lst.append(str(prd))
        return '\n'.join(lst)

class Csubject():
    def __init__(self, name):
        self.name = name
        self.mark = []

    def add_mark(self, mark):
        self.mark.append(mark)

    def average_subject(self, subject):
        return sum(self.mark) / len(self.mark)

    def __str__(self):
        return 'I am object of subject: %s  and have marks: %s' % \
            (self.name, str(self.mark))


def main():

# inicalization of objekt - student:
#-------------------------------
    janko = Cstudent('Janko Moor')
    janka = Cstudent ('Janka Vaskova')

# inicialization of subjects:
#-------------------------------
    fyz = Csubject('fyzic')
    eng = Csubject('english')
    mat = Csubject('matematic')
    hist= Csubject('history')
    bio = Csubject('biology')

# adding a subject to a particular object:
#-------------------------------
    janko.add_subject(fyz)
    janko.add_subject(eng)
    janko.add_subject(mat)

    janka.add_subject(hist)
    janka.add_subject(bio)
    janka.add_subject(eng)
    janka.add_subject(fyz)

# adding a mark to a particular object:
#-------------------------------
    janko.add_mark_student(fyz, mark=4)
    janko.add_mark_student(fyz, mark=1)
    janko.add_mark_student(fyz, mark=1)

    janka.add_mark_student(hist,mark=1)
    janka.add_mark_student(hist,mark=2)
    janka.add_mark_student(hist,mark=3)
    janka.add_mark_student(fyz,mark=1)

# output:
#-------------------------------
    print janko
    print janko.print_list_of_subjects()
    print fyz.average_subject('fyzic')
    print '-----------------------------------------------------'
    print janka
    print janka.print_list_of_subjects()
    print hist.average_subject('history')


if __name__ == '__main__':
    main()

output:

I am object of student: Janko Moor
I am object of subject: fyzic and have marks: [4, 1, 1, 1]
I am object of subject: english and have marks: []
I am object of subject: matematic and have marks: []
1
-----------------------------------------------------

vlady 0 Junior Poster in Training

here is output>

False
som object predmet matematika  a mam znamky: []
som object predmet fyzika  a mam znamky: []
som object predmet english  a mam znamky: []
vlady 0 Junior Poster in Training

ok, but I meant it differently..

class Cstudent():
    def __init__(self, name):
        self.name = name
        self.predmety = []
        self.mark = []
        self.absence = 0

    def add_subject(self, predmet):
        '''

        @param predmet: objekt typu predmet
        '''
        self.predmety.append(predmet)

    def add_mark(self, predmet, mark):
        if predmet in self.predmety:
            print True
        else:
            print False
        # TODO: dokoncit!
        #- prehladat vsetky predmety
        #  - a tomu ktory ma rovnaky nazov zavolat metodu add_znamka


    def print_zoznam_predmetov(self):
        lst = []
        for prd in self.predmety:
            lst.append(str(prd))
        return '\n'.join(lst)
        #return self.predmety

class Cpredmet():
    def __init__(self, nazov):
        self.nazov = nazov
        self.znamky = []

    def add_znamka(self, znamka):
        self.znamky.append(znamka)

    def average_predmet(self, predmet):
        return sum(self.znamky) / len(self.znamky)

    def __str__(self):
        return 'som object predmet %s  a mam znamky: %s' % \
            (self.nazov, str(self.znamky))


def main():

    janko = Cstudent('janko mrkvicka')

    fyz = Cpredmet('fyzika')
    eng = Cpredmet('english')

    janko.add_subject(Cpredmet('matematika'))
    janko.add_subject(fyz)
    janko.add_subject(eng)

    janko.add_mark(predmet='fyzika', mark=4)

    print janko.print_zoznam_predmetov()


if __name__ == '__main__':
    main()
vlady 0 Junior Poster in Training

Hello,
I am learning classes, and find it a bit difficult... :-(

Mine intention is to add subject(predmet) and mark to the objet janko but
if I search in self.predmety, I get False, means that it can't
recognise predmet in self.predmety list
State of self.predmety is as folloving:
[<__main__.Cpredmet instance at 0x010F5260>, <__main__.Cpredmet instance at 0x010F5210>, <__main__.Cpredmet instance at 0x010F5238>]

I presume that it can not recognize predmet (subject) in that state... Pls I need advice how to find a predmet in self.predmety list.
I approciate your help!

class Cstudent():
    def __init__(self, name):
        self.name = name
        self.predmety = []
        self.mark = []
        self.absence = 0

    def add_subject(self, predmet):
        '''

        @param predmet: objekt typu predmet
        '''
        self.predmety.append(predmet)

    def add_mark(self, predmet, mark):
        if predmet in self.predmety:
            print True
        else:
            print False
   
    def print_zoznam_predmetov(self):
        return self.predmety
   
class Cpredmet():
    def __init__(self, nazov):
        self.nazov = nazov
        self.znamky = []

    def add_znamka(self, znamka):
        self.znamky.append(znamka)

    def average_predmet(self, predmet):
        return sum(self.znamky) / len(self.znamky)

    
def main():

    janko = Cstudent('janko mrkvicka')

    fyz = Cpredmet('fyzika')
    eng = Cpredmet('english')

    janko.add_subject(Cpredmet('matematika'))
    janko.add_subject(fyz)
    janko.add_subject(eng)

    janko.add_mark(predmet='fyzika', mark=4)

    print janko.print_zoznam_predmetov()


if __name__ == '__main__':
    main()
vlady 0 Junior Poster in Training

thanks! but I knew that...

vlady 0 Junior Poster in Training

hello

I have a problem concerning of changing mark. I don´t understand why it doesn´t work...thought the old_mark is type LIST. It works for one student and not for more (for loop) Pls can you help me?
Thanks Vlady

def change_mark(changed_mark):
    for student in changed_mark:
        old_mark=changed_mark[student]
        position=old_mark.index[old_mark]   
        old_mark[position] = raw_input('new_mark')
        print changed_mark

## approach for one student:

##    old_mark=changed_mark['vlado']
##    position = old_mark.index('a')
##    old_mark[position] = raw_input('new_mark')
##    print changed_mark


def main():
    changed_mark={'vlado': [u'a'], 'juraj': [u'b'], 'alica': [u'c'], 'peto': [u'a'],
    'natalia': [u'b'], 'roman': [u'c'], 'kristina': [u'a'], 'silvia': [u'b']}
    change_mark(changed_mark)

if __name__ == '__main__':
    main()
vlady 0 Junior Poster in Training

thank you. I try it trough the module pickle as Gribouillis has shown in his example...
Friend of mine also told me to try it using pickle but I thought there is simple way... It might be, I don´t know but pickle works, so I can get by with it.

again thanks!

vlady 0 Junior Poster in Training

Hello Guys!

Can anybody help me with this code? So what I need?
here is it:
I want to fill out global variable "student_marks" with a grade for each student and keep it once is loaded. So it means without calling the function "def add_mark()" I will be able to print just global variable "student_marks" with its all students and marks.
I can do it in interpreter but not in script code. Pls, I need your help.

I approciate it, many thanks!

student_list=['juraj','kristina','peto','alica','vlado','natalia','roman','silvia']
student_marks = {}


def add_student(student):
    student_list.append(student)

def remove_student(student):
    student_list.remove(student)

def marks_student(student_list):
    for student in student_list:
        student_marks[student]=[]
    return student_marks

def add_mark():
    global student_marks
    number_students=len(student_list)
    for n in range(number_students):
        student_marks[raw_input('student')].append(raw_input('mark'))
    return student_marks



def main():
    marks_student(student_list)
    #print student_marks
    add_mark()
    print student_marks1
##    add_mark('juraj','A')
##    add_mark('kristina','B')
##    add_mark('peto','A')
##    add_mark('alica','C')
##    add_mark('vlado','A')
##    add_mark('natalia','B')
##    add_mark('roman','A')
##    add_mark('silvia','C')
    #print student_marks

if __name__ == '__main__':
    main()
vlady 0 Junior Poster in Training

Hello,

As I wrote before I follow the manual "Think Python: How to Think Like a Computer Scientist" chapter classes and method, polymorphism. I just try to solve a task. I don´t know more what is written there. Please have a look the link.
http://www.greenteapress.com/thinkpy...18.html#toc189

vlady 0 Junior Poster in Training

thanks Tony.

I´d like to use this structure : sum([t1,t2,t3])

yours is a bit different.

vlady 0 Junior Poster in Training

helo,

I learn Classes and methods according to a manual "Think Python: How to Think Like a Computer Scientist"
I am stuck on "Polymorphism" There is a part using built-in function sum.
I don't know what to do... It should be connected to __add__ function, but still the code must be somhow changed. If I use just total=t1+t2+t3 it works.
Here is a link to a web manual:
http://www.greenteapress.com/thinkpython/html/book018.html#toc189

total=sum([t1,t2,t3])

here is a code:

def int_to_time(seconds):
    time = Time()
    minutes, time.second = divmod(seconds, 60)
    time.hour, time.minute = divmod(minutes, 60)
    return time

class Time(object):
     def __init__(self, hour=0, minute=0, second=0):
        self.hour = hour
        self.minute = minute
        self.second = second

     def __add__(self, other):
        seconds = self.time_to_int() + other.time_to_int()
        return int_to_time(seconds)

     def time_to_int(self):
        minutes = self.hour * 60 + self.minute
        seconds = minutes * 60 + self.second
        print seconds
        return seconds

     def __str__(self):
        return '%.2d:%.2d:%.2d' % (self.hour, self.minute, self.second)

def main():
    t1 = Time(7, 43)
    t2 = Time(7, 41)
    t3 = Time(7, 37)
    total = sum([t1, t2, t3])
    print total

if __name__ == '__main__':
    main()

I really approciate your help guys. Many thanks!

vlady 0 Junior Poster in Training

You are very helpful MR TONY!

vlady 0 Junior Poster in Training

Hello,

I am learning classes and object and I have a problem with this code. Simply does not work. Can you tell me the reason please? Error message tells me that Distance is not defined...(I don´t understand this message)

Thank you for help!

Vlady

class Distance(object):
    'return distance between 2 points'
    point=Distance()
    point.x=3.0
    point.y=4.0
    print_distance(point)

def print_distance(d):
    distance = math.sqrt(d.x**2 + d.y**2)
    print distance

def main():
    pass

if __name__ == '__main__':
    main()
vlady 0 Junior Poster in Training

thank you all of you! Here is my version.

def most_frequent(s):
    t=s.split()
    delimiter= ''
    s=delimiter.join(t) # jankosielnapivo
    slabiky=list(s) #['j', 'a', 'n', 'k', 'o', 's', 'i', 'e', 'n', 'a', 'p', 'i', 'v', 'o']
    frekvencia=[]
    for i in slabiky:
        frekvencia.append(slabiky.count(i)) # [1, 2, 2, 1, 2, 1, 2, 1, 2, 2, 1, 2, 1, 2]
    tup=zip(slabiky,frekvencia)

    vysledok=[]
    for i in tup:
        if i not in vysledok:
            vysledok.append(i)
    vysledok.sort(reverse=False)
    return vysledok

def main():
    s='janko siel na pivo'
    print most_frequent(s)

if __name__ == '__main__':
    main()
vlady 0 Junior Poster in Training

Hello,

I do the following exercise:
Write a function called most_frequent that takes a string and prints the letters in decreasing order of frequency. Find text samples from several different languages and see how letter frequency varies between languages. Compare your results with the tables at wikipedia.org/wiki/Letter_frequencies.
I try my best but I am not sure if it corresponds to a required result thought there is not answer provided (in order to check it and compare if my method it´s not very different (deviated) from desired one)
The result might be like this (below) and if do so, I don´t know how to remove duplicate in "tuples". Please can you help me?
[(2, 'o'), (2, 'n'), (2, 'i'), (2, 'a'),(1, 'v'), (1, 's'), (1, 'p'),...]
My result is like this:
but we can´t see the frequencies...

What would be the most appropriate result?

Thank you very much!

Vlady

def most_frequent(s):
    t=s.split()
    delimiter= ''
    s=delimiter.join(t)
    l=list(s) #['j', 'a', 'n', 'k', 'o', 's', 'i', 'e', 'n', 'a', 'p', 'i', 'v', 'o']
    f=[]
    for i in l:
        f.append(l.count(i)) # [1, 2, 2, 1, 2, 1, 2, 1, 2, 2, 1, 2, 1, 2]
    tup=zip(f,l)
    tup.sort(reverse=True)
    res=[]
    for freq,letter in tup:
        if letter not in res:
            res.append(letter)
    print res # ['o', 'n', 'i', 'a', 'v', 's', 'p', 'k', 'j', 'e']


def main():
    s='janko sie na pivo'
    most_frequent(s)

if __name__ == '__main__':
    main()
vlady 0 Junior Poster in Training

Hello,

pls can anybody help me to break following string?

example:

output is 000 (type str) an I need to get [0,0,0]

here is a script:

def test(n_input):
    bin_n=2
    r=bin_n**n_input
##    print r

    for x in range(r):
##        print bin(x)
        f=str(bin(x))[2:].zfill(n_input) # x is type int, f is type str
        print type(f)

result is:
000
001
010
011
100
101
110
111

vlady 0 Junior Poster in Training

yes, it works , now the result is :

0000000000
0000000001
0000000010
0000000011
0000000100
0000000101
.
.
.etc

but I'd like to have output as a list : [0,0,0,0,0,0,1,0,1], is it posible to do it? I 've tried to use split but it doesn't work.
thank you for advice

vlady 0 Junior Poster in Training
def test(n_input):
    bin=2
    r=bin**n_input
    l=[]
##    print type(r)
    for x in range(r):
        print type(x)


##        print bin(x)
##        f=str(bin(x))[2:].zfill(10) # x is type int
##        print f

x is type ineger. I the documentation is writen:
bin(x)
Convert an integer number to a binary string. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer.

I don't understant why int can't convert to bin.

vlady 0 Junior Poster in Training

If I don't use bin, I don't get result I need.

vlady 0 Junior Poster in Training

I don't understand, can you give me an example pls?

thank you

vlady 0 Junior Poster in Training

I got a small problem. Message error is 'int' object is not callable...
I don't understand why I can't generate output.

def test(n_input):
    bin=2
    r=bin**n_input
##    print r
##    print type(r) # r type int
    for x in range(n_input): # n_input type int
##        print x
##        print type(n_input)
        f=str(bin(x))[2:].zfill(10) # x is type int
        print f

test(10)
vlady 0 Junior Poster in Training

yes, that's it! thank you

vlady 0 Junior Poster in Training

I have just trie this script:

def test():
    k=range(10)
    for x in k:
        f=bin(x) # x is type int
        print f

test()

result is :

0b0
0b1
0b10
0b11
0b100
0b101
0b110
0b111
0b1000
0b1001

I don't know how to get rid of 0b and add 0 to get lenght 10 numbers for instance
0b0 => 0000000000
0b1 => 0000000001

etc

can you help me pls?

thank you

vlady 0 Junior Poster in Training

yes!

vlady 0 Junior Poster in Training

I got an idea to make conversion from number to binary. Do you know any py statement?

thank you

vlady 0 Junior Poster in Training

Hello,

I try to generate output (all posibilities) for logical AND. Nb inputs is 10 and that means there are 1024 combination.

example:

n i1 i2 i3 i4 i5 i6 i7 i8 i9 i10 output
1 0 0 0 0 0 0 0 0 0 0 0
2 0 0 0 0 0 0 0 0 0 1 0
3 0 0 0 0 0 0 0 0 1 0 0
.
.
.
etc

How can I make a simple script to generate this output (for all posibilities) as is shown in the example above (of course which is not complete...)

Thank you for hint or help

vlady 0 Junior Poster in Training

vegaseat means that you must reduce the f to be reasonable size by choosing scaling factor (in case of normal book size material for input).

The biggest problem is that some rare words are going to be multiplied be zero, means they never appear in output even they are in input.

I am not sure if I am able to do it, I found it difficult.

vlady 0 Junior Poster in Training

Looks like the author is talking about the fact that a word:frequency dictionary of the book would be a lot shorter than a word list. Efficiency would be to get a representative random word from the book, that also reflects the frequency of the word, directly from the dictionary without expanding it into a long word list.

Imagine a book of 1 million words. A word list of every word in the book would have 1 million items. A word:frequency dictionary might only have 5,000 to 10,000 items, since duplicate words are taken care of in the frequency value.

do you think like this? :

import random

def random_words(t):
    g=words(t)
    t=[]
    for w, f in g.items():
        t.extend([w]*f)
    return random.choice(t)


def words(t):
    k=hist(t)
##    print k
    d=dict()
    t=[]
    for i in k:
        if i not in d:
            d[i]=1
        else:
            d[i]+=1
    return d # {'a': 1, 'went': 1, 'vlady': 1, 'beer': 2, 'for': 1}



def hist(t):
       l=t.split() # ['vlady-went', 'for', 'a', 'beer', 'beer']
       for i in l:
           i=t.replace('-',' ') # vlady went for a beer beer
           l=i.split()
       return l # ['vlady', 'went', 'for', 'a', 'beer', 'beer']
##hist('vlady-went for a beer beer')


##random_words('vlady-went for a beer beer')

print random_words('vlady-went for a beer beer')
vlady 0 Junior Poster in Training

I've corrected a bit a script because it wasn't what I'd expected.

import random

def random_words(t):
    k=hist(t)
    d=dict()
    t=[]
    a=1
    for i in k:
        d[i]=a
        a+=1
    for w, f in d.items():
        t.extend([w]*f)
    return random.choice(t)


def hist(t):
    l=t.split()
    return l


print random_words('vlady went for a beer')

but still, I don't know how I would proceed with exercise 7. Is it worthy to learn it?

vlady 0 Junior Poster in Training

13.7 Random words

To choose a random word from the histogram, the simplest algorithm is to build a list with multiple copies of each word, according to the observed frequency, and then choose from the list:

def random_word(h):
t = []
for word, freq in h.items():
t.extend([word] * freq)

return random.choice(t)

The expression [word] * freq creates a list with freq copies of the string word. The extend method is similar to append except that the argument is a sequence.
Exercise 7

This algorithm works, but it is not very efficient; each time you choose a random word, it rebuilds the list, which is as big as the original book. An obvious improvement is to build the list once and then make multiple selections, but the list is still big.

An alternative is:

1. Use keys to get a list of the words in the book.
2. Build a list that contains the cumulative sum of the word frequencies (see Exercise 10.1). The last item in this list is the total number of words in the book, n.
3. Choose a random number from 1 to n. Use a bisection search (See Exercise 10.8) to find the index where the random number would be inserted in the cumulative sum.
4. Use the index to find the corresponding word in the word list.

Write a program that uses this algorithm to choose a random word from …

vlady 0 Junior Poster in Training

can you give me an example pls?

vlady 0 Junior Poster in Training

Hello,

I make an exercise from a book : Think Python: How to Think Like a Computer Scientist by Allen B. Downey, Version 1.1.22, random words exercise 7.

I made a script like this (see below) but how can I make list (named book) just once and since then after each execution of the script it will make random choice from this list (if I well understand the task). There are more alternatives (in this manual book) and I don't know which one is more efficient, can you also tell me?

import random
def random_word(h):
    k=histogram(h)
##    print k
    t=[]
    for word, freq in k.items():
        t.extend([word]*freq) # output is a list but it will be build again after each execution of the script
    return random.choice(t)

def histogram(h):
    d = dict()
    for c in h:
        if c not in d:
            d[c] = 1
        else:
            d[c] += 1
    return d


print random_word('I went out for a walk')

Thank you

Vlady

vlady 0 Junior Poster in Training

Thank you very much, it helped me a lot!

vlady 0 Junior Poster in Training

I study manual "Think Python: How to Think Like a Computer Scientist by Allen B. Downey, Version 1.1.22, chapter 13, 13.6 Dictionary subtraction. There is an exercise 6. I did it by not using set types. The result will be the same?
Pls can you show me how to use this set types in the script? (+ probably my version of the script is too long, is it possible to make it more simple & understandable? I did it in the best way I can do it right now as a reason that I am a debutant in this field)

here is the script:

import string
def subtract(filename1,filename2):
    d1=file1(filename1)
    d2=file2(filename2)
    res = dict()
    for key in d1:
        if key not in d2:
            res[key] = None
    print res


def file1(filename):
    d1 = dict()
    fp = open(filename)
    for line in fp:
        process_line1(line, d1)
        return d1

def file2(filename):
    d2 = dict()
    fp = open(filename)
    for line in fp:
        process_line(line, d2)
        return d2

def process_line1(line, d1):
    line = line.replace('-', ' ')
    for word in line.split():
        word = word.strip(string.punctuation + string.whitespace)
        word = word.lower()
        d1[word] = d1.get(word, 0) +1


d1 = file1('emma.txt')
d2 = file2('words.txt')

subtract('emma.txt','words.txt')

file emma.txt contains these words:
Hossa-už-dlhšie patrí medzi najlepších hrácov v lige, ale to už všetci vedia, preto si nan dávajú velký pozor. Otvára sa tak šanca pre dalších, napríklad aj pre mna. Hossa vie vynikajúco pracovat s pukom, má výborný prehlad v hre," cituje ESPN krídelníka Troya Brouwera, ktorý po dvoch prihrávkach od staršieho …

vlady 0 Junior Poster in Training

ok, I correct it. But still I am not sure if I did it according to textbook "Think Python: How to Think Like a Computer Scientist, from Allen B. Downey, Version 1.1.22" in chapter 13, 13.6 Dictionary subtraction, there is exercise 6. I don't use the same text but that should not be the issue.

script:

import string
def subtract(filename1,filename2):
    d1=file1(filename1)
    d2=file2(filename2)
    res = dict()
    for key in d1:
        if key not in d2:
            res[key] = None
    print res

def file1(filename):
    d1 = dict()
    fp = open(filename)
    for line in fp:
        process_line1(line, d1)
        return d1

def file2(filename):
    d2 = dict()
    fp = open(filename)
    for line in fp:
        process_line(line, d2)
        return d2

def process_line1(line, d1):
    line = line.replace('-', ' ')
    for word in line.split():
        word = word.strip(string.punctuation + string.whitespace)
        word = word.lower()
        d1[word] = d1.get(word, 0) +1


d1 = file1('emma.txt')
d2 = file2('words.txt')

subtract('emma.txt','words.txt')
vlady 0 Junior Poster in Training

Hello,

pls can somebody have a look at my script and tell me why I can't get a value from d1? (print d1). Thank you for help.

here is a script:

def subtract():
    d1=file1(filename)
    dd2=file2(filename)
    res = dict()
    print d1
##    for key in d1:
##        if key not in d2:
##            res[key] = None
##    print res

def file1(filename):
    d1 = dict()
    fp = open(filename)
    for line in fp:
        process_line1(line, d1)
        return d1

def file2(filename):
    d2 = dict()
    fp = open(filename)
    for line in fp:
        process_line(line, d2)
        return d2

def process_line1(line, d1):
    line = line.replace('-', ' ')
    for word in line.split():
        word = word.strip(string.punctuation + string.whitespace)
        word = word.lower()
        d1[word] = d1.get(word, 0) +1

d1 = file1('emma.txt')
d2 = file2('words.txt')

emma.txt consist of these words:

Hossa-už-dlhšie patrí medzi najlepších hrácov v lige, ale to už všetci vedia, preto si nan dávajú velký pozor. Otvára sa tak šanca pre dalších, napríklad aj pre mna. Hossa vie vynikajúco pracovat s pukom, má výborný prehlad v hre," cituje ESPN krídelníka Troya Brouwera, ktorý po dvoch prihrávkach od staršieho z bratov Hossovcov dvakrát rozvlnil siet za gólmanom hostí Leightonom. Hossa Hossa Hossa Hossa Hossa Hossa Hossa Hossa Hossa Hossa Hossa Hossa Hossa Hossa Hossa Hossa Hossa Hossa Hossa

words.txt consist of these words:

Finding the words from the book that are not in the word list from words.txt is a problem you might recognize as set subtraction; that is, we want to find all the words from …

vlady 0 Junior Poster in Training

Great! Thank you very much, I would not come up with this idea. You helped me to move on!

vlady 0 Junior Poster in Training

Hello,

pls.can anybody help me? I try to solve a exercise where I need to involve random module. Here is a text:

Exercise 2
In this example, ties are broken by comparing words, so words with the same length appear in alphabetical order. For other applications you might want to break ties at random.
Modify this example so that words with the same length appear in random order.
Hint: see the random function in the random module.

here is a script which I try to modify according to the text.

def test(words):
    t = []
    for word in words:
       t.append((len(word), word))

    t.sort(reverse=True)

    res = []
    for length, word in t:
        res.append(word)
    print res
test(['hello','my','friend','Peter'])

here in the result I have 2 words with the same lenght (hello, peter). My aim is to sort these words according to the lenght, from highest to shortest words but for those words which have the same lenght I want to use random method in order to change their position after each run or execution of the script. So it should look like:
1 run:
2 run: