Python - How to add a random number to list? - list

Hello awesome coding folks!
Does anyone have a good idea to add a random number to a list? I am trying to get a list to log the random numbers that are generated inside a loop. Here is an example of the code inside the loop:
stuff = {'name': 'Jack', 'age': 30, 'height': '6 foot 9 inches'}
tester = [0]
print(tester)
tester.append[random.randint(1, len(stuff))]
print(tester)
Apparently the output of random.randint is not subscriptable, but I'm not sure how else to write this.
Thank you in advance for the help!

tester.append[random.randint(1, len(stuff))]
# wrong ^ wrong ^
# should be
tester.append(random.randint(1, len(stuff)))
Methods, such as append, are called with parentheses rather than brackets.

It's simple, Try this
from random import randint # import randint from random
listone = [] # Creating a list called listone
for i in xrange(1,10): # creating a loop so numbers can add one by one upto 10 times
ic = randint(1,10) # generating random numbers from 1 to 10
listone.append(ic) # append that numbers to listone
pass
print(listone) # printing list
# for fun you can sort this out ;)
print(sorted(listone))

do this modifications in your code
import random
stuff = {'name': 'Jack', 'age': 30, 'height': '6 foot 9 inches'}
tester = [0]
print(tester)
tester.append(random.randint(1, len(stuff)))
print(tester)

Related

append multiple numbers into a list

I have this column of numbers from a txt file that I want to append into a list:
18.0
13.0
10.0
12.0
8.0
my code for placing all these numbers into a list is
last_number_lis = []
for numbers_to_put_in in (path/to/txt):
last_number_lis.append(float(last_number))
print last_number_lis
I want the list to look like
[18.0,13.0,10.0,12.0,8.0]
but instead, when running the code, it shows
[18.0]
[13.0]
[10.0]
[12.0]
[8.0]
Is there any way that all the number can be in one line. Later on, I would like to add all the numbers up. Thanks for your help!!
you can append a list just like :
>>> list=[]
>>> list.append(18.0)
>>> list.append(13.0)
>>> list.append(10.0)
>>> list
[18.0, 13.0, 10.0]
but depend where your number are coming from ...
for example with input in terminal :
>>> list=[]
>>> t=input("type a number to append the list : ")
type a number to append the list : 12.45
>>> list.append(float(t))
>>> t=input("type a number to append the list : ")
type a number to append the list : 15.098
>>> list.append(float(t))
>>> list
[12.45, 15.098]
or reading from file :
>>> list=[]
>>> with open('test.txt', 'r') as infile:
... for i in infile:
... list.append(float(i))
...
>>> list
[13.189, 18.8, 15.156, 11.0]
If it is from a .txt file you would have to do the readline() method,
You could do a for loop and loop through the list of numbers (you never know how many numbers you may be given and might as well let the loop handle it,
with open(file_name) as f:
elemts = f.readlines()
elemts = [x.strip() for x in content]
and then you'd want to loop through the file and add the elements in the list
last_number_list = []
for last_number in elements:
last_number_list.append(float(last_number))
print last_number_list
A slightly less compact but easy to read approach is
num_list = []
f = open('file.txt', 'r') # open in read mode 'r'
lines = f.readlines() # read all lines in file
f.close() # safe to close file now
for line in lines:
num_list.append(float(line.strip()))
print num_list

Python:How can you recursively search a .txt file, find matches and print results

I have been searching for an answer to this, but can not seem to get what I need. I would like a python script that reads my text file and starting from the top working its way through each line of the file and then prints out all the matches in another txt file. Content of the text file is just 4 digit numbers like 1234.
example
1234
3214
4567
8963
1532
1234
...and so on.
I would like the output to be something like:
1234 : matches found = 2
I know that there are matches in the file do to almost 10000 lines. I appreciate any help. If someone could just point me in the right direction here would be great. Thank you.
import re
file = open("filename", 'r')
fileContent=file.read()
pattern="1234"
print len(re.findall(pattern,fileContent))
If I were you I would open the file and use the split method to create a list with all the numbers in and use the Counter method from collections to count how many of each number in the list are dupilcates.
`
from collections import Counter
filepath = 'original_file'
new_filepath = 'new_file'
file = open(filepath,'r')
text = file.read()
file.close()
numbers_list = text.split('\n')
numbers_set = set(numbers_list)
dupes = [[item,':matches found =',str(count)] for item,count in Counter(numbers_list).items() if count > 1]
dupes = [' '.join(i) for i in dupes]
new_file = open(new_filepath,'w')
for i in dupes:
new_file.write(i)
new_file.close()
`
Thanks to everyone who helped me on this. Thank you to #csabinho for the code he provided and to #IanAuld for asking me "Why do you think you need recursion here?" – IanAuld. It got me to thinking that the solution was a simple one. I just wanted to know which 4 digit numbers had duplicates and how many, and also which 4 digit combos were unique. So this is what I came up with and it worked beautifully!
import re
a=999
while a <9999:
a = a+1
file = open("4digits.txt", 'r')
fileContent = file.read()
pattern = str(a)
result = len(re.findall(pattern, fileContent))
if result >= 1:
print(a,"matches",result)
else:
print (a,"This number is unique!")

Why this python script does not work?

Update 1: the last line of code sorted_xlist = sorted(xlist).extend(sorted(words_cp)) should be changed to:
sorted_xlist.extend(sorted(xlist))
sorted_xlist.extend(sorted(words_cp))
Update 1: Code is updated to solve the problem of changing length of words list.
This exercise of list functions is from Google's Python Introduction course. I don't know why the code doesn't work in Python 2.7. The goal of the code is explained in annotation portion.
# B. front_x
# Given a list of strings, return a list with the strings
# in sorted order, except group all the strings that begin with 'x' first.
# e.g. ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] yields
# ['xanadu', 'xyz', 'aardvark', 'apple', 'mix']
# Hint: this can be done by making 2 lists and sorting each of them
# before combining them.
def front_x(words):
words_cp = []
words_cp.extend(words)
xlist=[]
sorted_xlist=[]
for i in range(0, len(words)):
if words[i][0] == 'x':
xlist.append(words[i])
words_cp.remove(words[i])
print sorted(words_cp) # For debugging
print sorted(xlist) # For debugging
sorted_xlist = sorted(xlist).extend(sorted(words_cp))
return sorted_xlist
Update 1: Now error message is gone.
front_x
['axx', 'bbb', 'ccc']
['xaa', 'xzz']
X got: None expected: ['xaa', 'xzz', 'axx', 'bbb', 'ccc']
['aaa', 'bbb', 'ccc']
['xaa', 'xcc']
X got: None expected: ['xaa', 'xcc', 'aaa', 'bbb', 'ccc']
['aardvark', 'apple', 'mix']
['xanadu', 'xyz']
X got: None expected: ['xanadu', 'xyz', 'aardvark', 'apple', 'mix']
The splitting of the original list works fine. But the merging doesn't work.
You're iterating over a sequence as you're changing its length.
Imagine if you start off with an array
arr = ['a','b','c','d','e']
When you remove the first two items from it, now you have:
arr = ['c','d','e']
But you're still iterating over the length of the original array. Eventually you get to i > 2, in my example above, which raises an IndexError.

add_edges_from three tuples networkx

I am trying to use networkx to create a DiGraph. I want to use add_edges_from(), and I want the edges and their data to be generated from three tuples.
I am importing the data from a CSV file. I have three columns: one for ids (first set of nodes), one for a set of names (second set of nodes), and another for capacities (no headers in the file). So, I created a dictionary for the ids and capacities.
dictionary = dict(zip(id, capacity))
then I zipped the tuples containing the edges data:
List = zip(id, name, capacity)
but when I execute the next line, it gives me an assertion error.
G.add_edges_from(List, 'weight': 1)
Can someone help me with this problem? I have been trying for a week with no luck.
P.S. I'm a newbie in programming.
EDIT:
so, i found the following solution. I am honestly not sure how it works, but it did the job!
Here is the code:
import networkx as nx
import csv
G = nx.DiGraph()
capacity_dict = dict(zip(zip(id, name),capacity))
List = zip(id, name, capacity)
G.add_edges_from(capacity_dict, weight=1)
for u,v,d in List:
G[u][v]['capacity']=d
Now when I run:
G.edges(data=True)
The result will be:
[(2.0, 'First', {'capacity': 1.0, 'weight': 1}), (3.0, 'Second', {'capacity': 2.0, 'weight': 1})]
I am using the network simplex. Now, I am trying to find a way to make the output of the flowDict more understandable, because it is only showing the ids of the flow. (Maybe i'll try to input them in a database and return the whole row of data instead of using the ids only).
A few improvements on your version. (1) NetworkX algorithms assume that weight is 1 unless you specifically set it differently. Hence there is no need to set it explicitly in your case. (2) Using the generator allows the capacity attribute to be set explicitly and other attributes to also be set once per record. (3) The use of a generator to process each record as it comes through saves you having to iterate through the whole list twice. The performance improvement is probably negligible on small datasets but still it feels more elegant. Having said that -- your method clearly works!
import networkx as nx
import csv
# simulate a csv file.
# This makes a multi-line string behave as a file.
from StringIO import StringIO
filehandle = StringIO('''a,b,30
b,c,40
d,a,20
''')
# process each row in the file
# and generate an edge from each
def edge_generator(fh):
reader = csv.reader(fh)
for row in reader:
row[-1] = float(row[-1]) # convert capacity to float
# add other attributes to the dict() below as needed...
# e.g. you might add weights here as well.
yield (row[0],
row[1],
dict(capacity=row[2]))
# create the graph
G = nx.DiGraph()
G.add_edges_from(edge_generator(filehandle))
print G.edges(data=True)
Returns this:
[('a', 'b', {'capacity': 30.0}),
('b', 'c', {'capacity': 40.0}),
('d', 'a', {'capacity': 20.0})]

Python: Iterating through a list

I am given a text file that contains many lines like the following... many random information
Spiaks Restaurant|42.74|-73.70|2 Archibald St+Watervliet, NY 12189|http://www.yelp.com/biz/spiaks-restaurant-watervliet|Italian|4|5|4|3|3|4|4
For example, Spiaks Restaurant is in position 0, 42.74 is in position 1, -73.70 is in position 2.... Italian is in position 5...
4|5|4|3|3|4|4 is another list... so basically a list within a list, and the number 4 would be in position 6, 5 in position 7.. etc
I have to ask the user, and the user should reply with:
What type of restaurant would you like => Italian
What is the minimum rating => 3.6
The result should be:
Name: Spiaks Restaurant; Rating 3.86
Name: Lo Portos; Rating 4.00
Name: Verdiles Restaurant; Rating 4.00
Found 3 restaurants.
Here is my code:
rest_type = raw_input("What type of restaurant would you like => ")
min_rate = float(raw_input("What is the minimum rating => "))
def parse_line(text_file):
count = 0.0
a_strip = text_file.strip('\n')
b_split = a_strip.split('|')
for i in range(6, len(b_split)):
b_split[i] = int(b_split[i]) # Takes the current indices in the list and converts it to integers
count += b_split[i] # Add up all of the integers values to get the total ratings
avg_rate = count/len(b_split[6:len(b_split)]) # Takes the total ratings & divides it by the length
#The above basically calculates the average of the numbers like 4|5|4|3|3|4|4
if (rest_type == b_split[5] and avg_rate >= min_rate):
print b_split[0], avg_rate
The problem with the result is.. I get:
None
I know this is a very, very long question, but if someone could give me some insight, I would appreciate it!
Have you trying printing out all of the information you aggregated?
Find out where the error is occurring, be it when you try to parse for specific restaurants, or you just straight up parse nothing and end up with a blank list.