Python - Using a created list as a parameter - python

When I run my code it tells me: Type Error: unorderable types: str() < float(). I can't figure out why it won't let me compare these two numbers. The list I am using is defined, and the numbers in it have been redefined as floats, so I'm not sure what else to do. Any suggestions?
def countGasGuzzlers(list1, list2):
total = 0
CCount = 0
HCount = 0
for line in list1:
if num < 22.0:
total = total + 1
CCount = CCount + 1
for line in list2:
if num < 27.0:
total = total + 1
Hcount = Hcount = 1
print('City Gas Guzzlers: ',CCount)
print('Highway Gas Guzzlers: ',HCount)
print('Total Gas Guzzlers: ',total)
This is my list definition. I'm pretty sure it's fine, but maybe there are some bugs in here as well?
CityFile = open('F://SSC/Spring 2015/CSC 110/PythonCode/Chapter 8/HW 4/carModelData_city','r')
for line in CityFile:
CityData = CityFile.readlines()
for num in CityData:
numCityData = float(num)
CityList = numCityData
HwyFile = open('F://SSC/Spring 2015/CSC 110/PythonCode/Chapter 8/HW 4/carModelData_hwy','r')
for line in HwyFile:
HwyData = HwyFile.readlines()
for num in HwyData:
numHwyData = float(num)
HwyList = numHwyData

I believe you are incorrectly referencing to num instead of line which is the counter variable in your for loops, you either need to use num as the counter variable, or use line in the if condition.
def countGasGuzzlers(list1, list2):
total = 0
CCount = 0
HCount = 0
for line in list1:
if float(line) < 22.0:
total = total + 1
CCount = CCount + 1
for line in list2:
if float(line) < 27.0:
total = total + 1
Hcount = Hcount = 1
print('City Gas Guzzlers: ',CCount)
print('Highway Gas Guzzlers: ',HCount)
print('Total Gas Guzzlers: ',total)
Another issue I see is with the way you are creating the lists . The issue is that you are converting each num in file to float and then storing that directly in list variable, which causes list variable to actually store a float value instead of a list, you need to append each value into list, instead of doing list = num
The code would look like -
CityFile = open('F://SSC/Spring 2015/CSC 110/PythonCode/Chapter 8/HW 4/carModelData_city','r')
for line in CityFile:
CityData = CityFile.readlines()
for num in CityData:
numCityData = float(num)
CityList.append(numCityData)
HwyFile = open('F://SSC/Spring 2015/CSC 110/PythonCode/Chapter 8/HW 4/carModelData_hwy','r')
for line in HwyFile:
HwyData = HwyFile.readlines()
for num in HwyData:
numHwyData = float(num)
HwyList.append(numHwyData)
Please also make sure CityList and HwyList are initialized before this code as lists. Like below -
CityList = []
HwyList = []

Related

Dictionary task in Python: Elections

The first line gives the number of entries. Further, each entry contains the name of the candidate and the number of votes cast for him in one of the states. Summarize the results of the elections: for each candidate, determine the number of votes cast for him. Use dictionaries to complete the tasks.
Input:
Number of voting records (integer number), then pairs <> - <>
Output:
Print the solution of the problem.
Example:
Input:
5
McCain 10
McCain 5
Obama 9
Obama 8
McCain 1
Output:
McCain 16
Obama 17
My problem is at the step when I have to sum keys with same names but different values.
My code is:
cand_n = int(input())
count = 0
countd = 0
cand_list = []
cand_f = []
num = []
surname = []
edict = {}
while count < cand_n:
cand = input()
count += 1
cand_f = cand.split(' ')
cand_list.append(cand_f)
for k in cand_list:
for i in k:
if i.isdigit():
num.append(int(i))
else: surname.append(i)
while countd < cand_n:
edict[surname[countd]] = num[countd]
countd += 1
print(edict)
You can add the name and vote to the dictionary directly instead of using one more for() and while().
If the name does not exist in the dictionary, you add the name and vote. If the name exists in the dictionary, increase the vote.
cand_n = int(input())
count = 0
cand_list = []
cand_f = []
edict = {}
while count < cand_n:
cand = input()
count += 1
cand_f = cand.split(' ')
if cand_f[0] in edict:
edict[cand_f[0]] += int(cand_f[1])
else:
edict[cand_f[0]] = int(cand_f[1])
print(edict)

Trying to find same digits in a row [duplicate]

This question already has answers here:
Longest sequence of consecutive duplicates in a python list
(4 answers)
Closed 2 years ago.
Im trying to find the biggest series of digit in a row in a list which i can input. And im doing this way:
list = []
count_max_numbers = 0
while True:
x = int(input('число: '))
if x == 0:
break
list.append(int(x))
max_number = max(list)
for i in list:
if i != max_number:
pass
else:
count_max_numbers += 1
current_result = 0
max_result = 0
last_seen = list[0]
longest_digit = 0
for i in list:
if i == last_seen:
current_result += 1
else:
if current_result > max_result:
max_result = current_result
longest_digit = i
last_seen = i
current_result = 1
if current_result > max_result:
max_result = current_result
longest_digit = i
print(f'{list}')
print(f'max number: {max_number} reapeted{count_max_numbers} times')
print(f'the biggest series: {longest_digit} repeated {max_result} times')
this works only with first digit in a list. But i need to work it with whole list.
For example if input (1,2,3,3,3,3,5,55)
It need to get output: the biggest series: 3 repeated 4 times
I still have a problem with output of {longest_digit} it's incorrect
Try this:
mylist = [1,2,3,3,3,3,5,55]
val_holder = {}
for val in mylist:
if val not in val_holder.keys():
val_holder[val] = 1
else:
val_holder[val] += 1
max_key = max(val_holder, key=val_holder.get)
print(max_key)
My aproach to this will be using dictionary
lst = [1,2,3,3,3,3,5,55]
dict = {}
for val in lst:
if val not in dict.keys():
dict[val] = 1
else:
dict[val] = dict[val] + 1
Once we get the dictionary we sort this using the value
sorted_dict = sorted(dict.items(), key=lambda keyVal: keyVal[1], reverse=True)
print(dict[0][0])
Here's a simple algorithm:
Initialize longest = None, longest_digit = None, current = 0, previous_digit, and current_digit = None.
Then, for each item in the list:
If the item is equal to current_digit, increment current by one.
Otherwise:
(A) If current > longest, set longest = previous_digit and longest_digit = item
(B) Then, reset current to 1 and current_digit to item
Set previous_digit to item
At the end of the list, also do step (A) above.
Now you should have the answer in longest (4) and longest_digit (3)

Program that reads a vote text file and prints the outcome not printing the right numbers

Here is my code I need it to read a line of text that just composes of y's a's and n's y meaning yes n meaning no a meaning abstain, I'm trying to add up the number of yes votes. The text file looks like this:
Aberdeenshire
yyynnnnynynyannnynynanynaanyna
Midlothian
nnnnynyynyanyaanynyanynnnanyna
Berwickshire
nnnnnnnnnnnnnnnnnnnnynnnnnynnnnny
here is my code:
def main():
file = open("votes.txt")
lines = file.readlines()
votes = 0
count = 0
count_all = 0
for m in range(1,len(lines),2):
line = lines[m]
for v in line:
if v == 'a':
votes += 1
elif v == 'y':
count_all += 1
count += 1
votes += 1
else:
count_all += 1
print("percentage:" + (str(count/count_all)))
print("Overall there were ", (count/count_all)," yes votes")
main()
First of all, you should note that your file.readlines() actually gives you the \n at the end of each line, which in your code will both be treated in the else block, so as no's:
>>> with open("votes.txt","r") as f:
... print(f.readlines())
...
['Aberdeenshire\n',
'yyynnnnynynyannnynynanynaanyna\n',
'Midlothian\n',
'nnnnynyynyanyaanynyanynnnanyna\n',
'Berwickshire\n',
'nnnnnnnnnnnnnnnnnnnnynnnnnynnnnny\n']
So that might explain why you don't find the good numbers...
Now, to make the code a bit more efficient, we could look into the count method of str, and maybe also get rid of those \n with a split rather than a readlines:
with open("votes.txt","r") as f:
full = f.read()
lines = full.split("\n")
votes = 0
a = 0
y = 0
n = 0
for m in range(1,len(lines),2):
line = lines[m]
votes += len(line) # I'm counting n's as well here
a += line.count("a")
y += line.count("y")
n += line.count("n")
print("Overall, there were " + str(100 * y / (y + n)) + "% yes votes.")
Hope that helped!
More or less pythonic one liner, it doesn't give you the votes for each person/city tho:
from collections import Counter
l = """Aberdeenshire
yyynnnnynynyannnynynanynaanyna
Midlothian
nnnnynyynyanyaanynyanynnnanyna
Berwickshire
nnnnnnnnnnnnnnnnnnnnynnnnnynnnnny"""
Counter([char for line in l.split('\n')[1::2] for char in line.strip()])
Returns:
Counter({'a': 11, 'n': 60, 'y': 22})

calling sum() on a list of numbers extrcted from a document

I need a little help with a sum function. I'm trying to locate all the lines with prefix "X-DSPAM-Confidence:" in a document. After i extract them i want to call sum() on them and calculate the average. Thanks, heaps!!!
for line in (fhand):
line = line.rstrip()
if not line.startswith("X-DSPAM-Confidence:"):
continue
else:
n = float(line[line.find(":") + 1:])
a = sum(n)
count = count + 1
print (n)
print (a)
print (total / count)
I don't know if I understood this correctly, but as far as I can see, you only need to store the sum of the values in a variable, something like:
total = 0.0
count = 0
for line in (fhand):
line = line.rstrip()
if not line.startswith("X-DSPAM-Confidence:"):
continue
else:
n = float(line[line.find(":") + 1:])
total += n
count = count + 1
print (total / count)

Find median and mode from .txt file Python 3.4.1

I am trying to determine the median and mode from a list of numbers in "numbers.txt" file.
I am EXTREMELY new to python and have ZERO coding experience.
This is what I have so far calculating mean, sum, count, max, and min but I have no idea where to go from here.
number_file_name = 'numbers.txt'
number_sum = 0
number_count = 0
number_average = 0
number_maximum = 0
number_minimum = 0
number_range = 0
do_calculation = True
while(do_calculation):
while (True):
try:
# Get the name of a file
number_file_name = input('Enter a filename. Be sure to include .txt after the file name: ')
random_number_count = 0
print('')
random_number_file = open(number_file_name, "r")
print ('File Name: ', number_file_name, ':', sep='')
print('')
numbers = random_number_file.readlines()
random_number_file.close
except:
print('An error occured trying to read', random_number_file)
else:
break
try:
number_file = open(number_file_name, "r")
is_first_number = True
for number in number_file:
number = int(number) # convert the read string to an int
if (is_first_number):
number_maximum = number
number_minimum = number
is_first_number = False
number_sum += number
number_count += 1
if (number > number_maximum):
number_maximum = number
if (number < number_minimum):
number_minimum = number
number_average = number_sum / number_count
number_range = number_maximum - number_minimum
index = 0
listnumbers = 0
while index < len(numbers):
numbers[index] = int(numbers[index])
index += 1
number_file.close()
except Exception as err:
print ('An error occurred reading', number_file_name)
print ('The error is', err)
else:
print ('Sum: ', number_sum)
print ('Count:', number_count)
print ('Average:', number_average)
print ('Maximum:', number_maximum)
print ('Minimum:', number_minimum)
print ('Range:', number_range)
print ('Median:', median)
another_calculation = input("Do you want to enter in another file name? (y/n): ")
if(another_calculation !="y"):
do_calculation = False
If you want to find the median and mode of the numbers, you need to keep track of the actual numbers you've encountered so far. You can either create a list holding all the numbers, or a dictionary mapping numbers to how often you've seen those. For now, let's create a (sorted) list from those numbers:
with open("numbers.txt") as f:
numbers = []
for line in f:
numbers.append(int(line))
numbers.sort()
Or shorter: numbers = sorted(map(int, f))
Now, you can use all sorts of builtin functions to calculate count, sum, min and max
count = len(numbers)
max_num = max(numbers)
min_num = min(numbers)
sum_of_nums = sum(numbers)
Calculating the mode and median can also be done very quickly using the list of numbers:
median = numbers[len(numbers)//2]
mode = max(numbers, key=lambda n: numbers.count(n))
Maybe there is a reason for it but why are you avoiding using the python libraries? Numpy and scipy should have everything you are looking for such a task.
Have a look at numpy.genfromtxt() , numpy.mean() and scipy.stats.mode().

Categories

Resources