Wheeler, Gabriel | 17 Apr 03:10 2014

List issues

Hi

Im having trouble completing this function with lists. Im supposed to create a function that will let me know if there are repeating elements so I wrote this and am not sure where the error lies. It is supposed to count the number of times a number appears and if its greater than 1 then it will say True.

#Problem 3                                                                      

list = [1,2,2,2,3,4]

def duplicate(list):

    for i in range(len[list]):

        if list.count(i) > 1:

            return True


print duplicate(list)



Gabe Wheeler
(512)964-5421
_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Qianyun Guo | 15 Apr 14:56 2014
Picon

questions when define a class

Hi all, I am trying to get a suffix tree from a string. I use three classes, Node, Edge, SuffixTree. I have two questions when implementing:

【1】

>>> a = Edge(1,2,3,4)

>>> a.length

1

if I remove  ' <at> property' in my code, it returns as below:

>>> a = Edge(1,2,3,4)

>>> a.length

<bound method Edge.length>

>>> a.length()

1



I don't really understand the differences w/ <at> property, and the differences of a.length and a.length(), could you explain?

【2】

In SuffixTree, I define two functions, _get_str_from_edge, _get_str_from_node, the latter depend on the first one (please see my code).  Then I have this problem:

>>> a = SuffixTree('abcd')

>>> a._get_str_from_edge(a.edges[(0,1)])

'abcd$'

>>> a._get_str_from_node(0,1)

TypeError: _get_str_from_edge() takes exactly 2 arguments (3 given)

Could you tell me what's wrong here?




below is my code, __repr__ are removed for convenience.
###################################


class Node:

    def __init__(self, parent_node):
        self.suffix_node = -1  
        self.parent = parent_node
        self.children = []

    def add_child(self, child_node_index):
        self.children.append(child_node_index)

class Edge:

    def __init__(self, first_char_index, last_char_index,\
            source_node_index, dest_node_index):
        self.first_char_index = first_char_index
        self.last_char_index = last_char_index
        self.source_node_index = source_node_index
        self.dest_node_index = dest_node_index

    <at> property
    def length(self):
        return self.last_char_index - self.first_char_index

class SuffixTree:

    def __init__(self, string):
        self.string = string+'$'
        self.N = len(self.string) 
        self.nodes = []
        self.num_nodes = 0
        self.edges = {}
       
        #initialize two node tree

        root = Node(-1)
        root.suffix_node = -1
        self._add_node(root)

        leaf = Node(0)
        leaf.suffix_node = 0 
        self._add_node(leaf)
        self.nodes[0].add_child(1)

        edge = Edge(0, self.N, 0, 1) 
        self._add_edge(edge)

    def _get_str_from_edge(self, edge):
        return self.string[edge.first_char_index : edge.last_char_index]

    def _get_str_from_node(self, source_node_index, dest_node_index):
        return self._get_str_from_edge(self, self.edges[(source_node_index, \
                dest_node_index)])
    
    
    def _add_node(self, node):
        self.nodes.append(node)
        self.num_nodes += 1

    def _add_edge(self, edge):
        self.edges[(edge.source_node_index, edge.dest_node_index)] = edge
        self.nodes[edge.source_node_index].add_child(edge.dest_node_index)
        self.nodes[edge.dest_node_index].parent = edge.source_node_index




    

_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Victoria Kuritza | 15 Apr 07:06 2014
Picon

Quick Question

How can I search in a corpus for three or more occurrences of capitalized words in a line? What would I input as my search? 


Cheers, 

Victoria K. 






_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Sunil Tech | 15 Apr 08:24 2014
Picon

Fwd: Puzzle - Next Step to our interviewing process - Pramati Technologies!

Kindly assess the problem carefully including all the possibilities, including but not limited to:

 

1. Menu directly available(1 item or all items).

2. Menu available but distributed over multiple items.

3. Menu need not be present in all restaurants listed.

4. Menu not available at all.


Please complete the puzzle using the development language that you are being interviewed for. 

Most people have send responses that work for the dataset and the test cases described along with the problem. However we do use a different dataset and test cases that try and check some boundary conditions. We have seen many solutions that work for the test cases below but fail with our internally used test cases.

 

Because it is the Internet Age, but also it is a recession, the Comptroller of the town of Jurgensville has decided to publish the prices of every item on every menu of every restaurant in town, all in a single CSV file (Jurgensville is not quite up to date with modern data serializationmethods).  In addition, the restaurants of Jurgensville also offer Value Meals, which are groups of several items, at a discounted price.  The Comptroller has also included these Value Meals in the file.  The file's format is:

 for lines that define a price for a single item:

restaurant ID, price, item label

 for lines that define the price for a Value Meal (there can be any number of

items in a value meal)

restaurant ID, price, item 1 label, item 2 label, ...

 All restaurant IDs are integers, all item labels are lower case letters and

underscores, and the price is a decimal number.

 Because you are an expert software engineer, you decide to write a program that accepts the town's price file, and a list of item labels that someone wants to eat for dinner, and outputs the restaurant they should go to, and the total price it will cost them.  It is okay to purchase extra items, as long as the total cost is minimized.

 

Here are some sample data sets, program inputs, and the expected result:

 ----------------------------

Data File data.csv

1, 4.00, burger

1, 8.00, tofu_log

2, 5.00, burger

2, 6.50, tofu_log

 Program Input

program data.csv burger tofu_log

 Expected Output

=> 2, 11.5

---------------------------

 ----------------------------

Data File data.csv

3, 4.00, chef_salad

3, 8.00, steak_salad_sandwich

4, 5.00, steak_salad_sandwich

4, 2.50, wine_spritzer

 

Program Input

program data.csv chef_salad wine_spritzer

Expected Output

=> nil (or null or false or something to indicate that no matching

restaurant could be found)

---------------------------

 ----------------------------

Data File data.csv

5, 4.00, extreme_fajita

5, 8.00, fancy_european_water

6, 5.00, fancy_european_water

6, 6.00, extreme_fajita, jalapeno_poppers, extra_salsa

 Program Input

program data.csv fancy_european_water extreme_fajita

 Expected Output

=> 6, 11.0

---------------------------

 We have included all these samples in a single data file, sample_data.csv.    Please include instructions for how to run your program with your submission.

 

 



Attachment (sample_data.csv): application/vnd.ms-excel, 437 bytes
_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Sunil Tech | 15 Apr 08:06 2014
Picon

reading a csv file

Hi,

#!/usr/bin/python

import csv
import sys

def main():
    cr = csv.reader(open("data.csv","rb"))
    for row in cr:
        print row

if __name__ == "__main__":
    sys.exit(main())



when i run this...

i get 

Traceback (most recent call last):
  File "data.py", line 14, in <module>
    sys.exit(main())
  File "data.py", line 9, in main
    cr = csv.reader(open("data.csv","rb"))
AttributeError: 'module' object has no attribute 'reader'


can anyone correct me please.

thank you in advance.

_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
brian arb | 15 Apr 04:09 2014
Picon

Why should modules or packages should define their own domain-specific base exception class?

I don't quite understand why the google python style guide recommends that packages and modules we write should avoid using the catch-all except. Instead the guide encourages you to write domain specific exception classes.

class Error(Exception):
  """..."""

class ThisSpecificError(Error):
  """..."""

class ThatSpecificError(Error):
  """..."""


try:
  ...
except mylib.Error:
  ...


Thoughts?
_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
ALAN GAULD | 14 Apr 22:55 2014

Re: python errors

From: keith papa <keithadu <at> live.com>
To: Alan Gauld <alan.gauld <at> btinternet.com>
Sent: Monday, 14 April 2014, 18:19
Subject: RE: [Tutor] python errors

<!-- #yiv321405325 .yiv321405325hmmessage P { margin:0px;padding:0px;} #yiv321405325 body.yiv321405325hmmessage { font-size:12pt;font-family:Calibri;} -->
>>> x = "foo" - 4

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    x = "foo" - 4
TypeError: unsupported operand type(s) for -: 'str' and 'int'
>>> 

That's right, its a semantic error. You  shouldn't be trying to subtract a number 
from a string. It's not a meaningful thing to do,

The Python errors are not categorised into syntactic, semantic and runtime
error types, (although there is a syntax error exception). Those are computer 
science concepts not explicitly exposed by Python. Python just reports an 
error as above.

Alan g.
_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
keith papa | 14 Apr 13:53 2014

python errors

Hi am a new to programming and I reading the book "Think python" am on chapter one and it mentioned some errors I need to look out for like: Syntax errors, Runtime errors and semantic errors. I wanted to know if you guys have some  examples of the errors?
_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
keith papa | 13 Apr 06:39 2014

A Byte of Python or Learn python the hard way

I want to start learning python today and I wanted to know which book I should start with: A Byte of Python or Learn python the hard way?
_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
bruce | 13 Apr 08:54 2014
Picon

cdata/aml question..

Hi.

The following text contains sample data. I'm simply trying to parse it
using libxml2dom as the lib to extract data.

As an example, to get the name/desc

test data
<class_meta_data><departments><department><name><![CDATA[A
HTG]]></name><desc><![CDATA[American
Heritage]]></desc></department><department><name><![CDATA[ACC]]></name><desc><![CDATA[Accounting]]></desc></department>

    d = libxml2dom.parseString(s, html=1)

    p1="//department/name"
    p2="//department/desc"

    pcount_ = d.xpath(p1)
    p2_ = d.xpath(p2)
    print str(len(pcount_))
    nba=0

    for a in pcount_:
      abbrv=a.nodeValue
      print abbrv
      abbrv=a.toString()
      print abbrv
      abbrv=a.textContent
      print abbrv

neither of the above generates any of the CML name/desc data..

any pointers on what I'm missing???

I can/have created a quick parse/split process to get the data, but I
thought there'd be a straight forward process to extract the data
using one of the py/libs..

thanks
_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Saba Usmani | 11 Apr 22:58 2014

Creating an Invalid message for user

Hi,

I am meant to design code for a program that converts from binary number to decimal and vice versa. 

This is what i have so far:

print "Welcome to the binary and decimal converter"
loop = True
while loop:
    bord = raw_input("Enter b for binary or d decimal or exit to exit")
    if bord == "b":
        d = 0
        b = 0
        factor = 1;
        b = raw_input ("Enter Binary Number:")
        b=b.lstrip("0")
        b = int(b)
        while(b > 0):
            if((int(b) % 10) == 1):
                d += factor
            b /= 10
            factor = factor * 2
        print "The Decimal Number is: ", d
       
    elif bord == "d":
        x=0
        n=int(input('Enter Decimal Number: '))        
        x=n
        k=[] # array
        while (n>0):
            a=int(float(n%2))
            k.append(a)
            n=(n-a)/2
        k.append(0)
        string=""
        for j in k[::-1]:
            string=string+str(j)
        print('The binary Number for %d is %s'%(x, string))
 
    elif bord == "exit" :
        print "Goodbye"
        loop = False

- This code does not recognize invalid inputs e.g in the binary to decimal conversion, if I enter 10021 it will not inform me,the user, that the input is invalid. The same problem occurs with the decimal to binary conversion - if i enter 123&&gf I am not told to try again with a valid input  - how do I implement this in the code above

Thanks
Saba
_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Gmane