max() arg is an empty sequence [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I have written a program for Radix Sort in Python. But when I execute the code I get following error message max() arg is an empty sequence.
Here is my code:
class RadixSort:
num=0
array=[]
def getData(self):
print 'Enter the number of elements you want to enter: '
num=int(input())
print 'Now enter the elements: '
for i in range(0,self.num):
print 'Element ',i+1,': '
value=int(input())
self.array.append(value)
def radixSort(self):
bin=[[],[],[],[],[],[],[],[],[],[]]
r=1
m=max(self.array)
while m>r:
for ele in self.array:
bin[(ele/r)%10].append(ele)
r=r*10
self.array=[]
for i in range(10):
self.array.extend(bin[i])
bin[i]=[]
def displayArray(self):
print ''
for ele in self.array:
print ele
RObject=RadixSort()
RObject.getData()
RObject.radixSort()
RObject.displayArray()
I get this error before entering values in array. How can I solve this?

I think you should replace:
num = int(input())
to
self.num = int(input())
Not superfluous will be to check that the array is not empty:
m = max(self.array) if self.array else 0

You should show the complete traceback. When I run your code I get this:
Enter the number of elements you want to enter:
3
Now enter the elements:
Traceback (most recent call last):
File "radix.py", line 35, in <module>
RObject.radixSort()
File "radix.py", line 17, in radixSort
m=max(self.array)
ValueError: max() arg is an empty sequence
so m=max(self.array) fails because you can't do a max function on an object that doesn't exist. You need to have an init method to create self.array
Why are you using input and not raw_input? You are using python 2.7

Related

global variable python, doesn't run [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 4 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I try to run this code in python 3.6
def Arrange(num):
global sec
sec=0
def Digit(nmb):
return nmb%10
def WithoutTheLastDigit(nmb2):
return nmb2//10
def IsEven(even):
if even%2==0:
return True
else:
return False
def AddDigit(number,dig):
number=number*10+dig
while num>0:
Digit(num)
if IsEven(Digit(num))==True:
sec=sec+AddDigit(sec,Digit(num))
WithoutTheLastDigit(num)
print(sec)
and it shows this error:
>>> Arrange(500)
Traceback (most recent call last):
File "", line 1, in
Arrange(500)
File "C:\Users\Yair\Desktop\hw3.py", line 56, in Arrange
sec=sec+AddDigit(sec,Digit(num))
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
Your problem is that the function AddDigit() returns None:
def AddDigit(number,dig):
number=number*10+dig
# this return None by default. mussing `return number`
while num>0:
Digit(num)
if IsEven(Digit(num))==True:
sec=sec+AddDigit(sec,Digit(num)) # This is 0 + None
WithoutTheLastDigit(num)
Note that you code can be simplify greatly with a few things. I didn't change the logic, so you might have some errors here.
def Digit(number):
return number % 10
def WithoutTheLastDigit(number):
return number // 10
def IsEven(number):
return number % 2 == 0:
def AddDigit(number, digit):
return number*10 + digit
while number > 0:
digit = Digit(number)
if IsEven(digit):
sec += AddDigit(sec, digit)
print(sec)

Error: 'str' object is not callable python [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I have been stuck dealing with an error in python and have been searching for a while to fix it but to no avail.
Here is the error I am getting
Traceback (most recent call last):
File "C:\Users\wood\Desktop\Software design\Program 4\program3_4QuinnWood.py", line 62, in <module>
main()
File "C:\Users\wood\Desktop\Software design\Program 4\program3_4QuinnWood.py", line 23, in main
displayOutput(letterCount,middleCharacter,spaceAmount,aReplace)
File "C:\Users\wood\Desktop\Software design\Program 4\program3_4QuinnWood.py", line 56, in displayOutput
print('Number of letters:'(letterCount))
TypeError: 'str' object is not callable
Here is the code I have written so far.
def main():
while True:
sentence= userInput()
letterCount= characterCount(sentence)
middleCharacter= middleLetter(sentence)
spaceAmount= spaceCount(sentence)
aReplace= letterReplace(sentence)
displayOutput(letterCount,middleCharacter,spaceAmount,aReplace)
def userInput():
sentence = str(input('Enter a sentence at least 10 letters long, or type STOP to quit:'))
if sentence == 'STOP':
quit()
return sentence
def characterCount(sentence):
letterCount = len(sentence) - sentence.count(' ')
if letterCount < 10:
print('Sorry that is less than 10 letters')
def middleLetter(sentence):
sentence = len(sentence)/2
middleCharacter = [sentence +1]
def spaceCount(sentence):
spaceAmount = sentence.count(' ')
def letterReplace(sentence):
aReplace= sentence.replace("a", "&")
def displayOutput(letterCount,middleCharacter,spaceAmount,aReplace):
print('Number of letters:'(letterCount))
print('Middle letter:'(middleCharacter))
print('Spaces counted:'(spaceAmount))
print('Sentence with letter replaced:'(aReplace))
main()
The solution is probably something simple that I am overlooking but any help would be appreciated.
The error states str object not callable which meant you were treating strings like functions or anything which is callable () in your code.
The issue is in the print statements in displayOutput() function
Corrected code
def displayOutput(letterCount,middleCharacter,spaceAmount,aReplace):
print('Number of letters:',letterCount)
print('Middle letter:',middleCharacter)
print('Spaces counted:',spaceAmount)
print('Sentence with letter replaced:',aReplace)
main()

AttributeError: 'function' object has no attribute 'save' - Python PIL QR Code not saving [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I'm a newcomer to programming so i apologize for my lack of technical ability.
I'm trying to create a qrcode generator in python, however, when i try to increment the number on the filename save, i get this error.
Traceback (most recent call last):
File "/home/sam/Desktop/QR Code Gen/run.py", line 52, in <module>
purchase_code_fn()
File "/home/sam/Desktop/QR Code Gen/run.py", line 32, in purchase_code_fn
qr_code_fn()
File "/home/sam/Desktop/QR Code Gen/run.py", line 41, in qr_code_fn
im.save("filename"+ count + ".png")
AttributeError: 'function' object has no attribute 'save'
>>>
Is there anyway to rectify this?
(see below for my full code - it's still a WIP)
from qrcode import *
import csv
import time
active_csv = csv.writer(open("active_codes.csv", "wb"))
void_csv = csv.writer(open("void_codes.csv", "wb"))
active_csv.writerow([
('product_id'),
('code_id'),
('customer_name'),
('customer_email'),
('date_purchased'),
('date_expiry')])
void_csv.writerow([
('code_id'),
('customer_email'),
('date_expiry')])
count = 0
def purchase_code_fn():
global count
count =+ 1
customer_email = raw_input("Please enter your email: ")
product_id = raw_input("Which product would you like (1 - 5): ")
qr_code_fn()
def qr_code_fn():
qr = QRCode(version=5, error_correction=ERROR_CORRECT_M)
qr.add_data("asaasasa")
qr.make() # Generate the QRCode itself
# im contains a PIL.Image.Image object
im = qr.make_image
im.save("filename"+ count + ".png")
def restart_fn():
restart_prompt = raw_input("Would you like to purchase another code? : ").lower()
if restart_prompt == "yes" or restart_prompt == "y":
purchase_code_fn()
elif restart_prompt =="n" or restart_prompt == "no":
print("exit")
purchase_code_fn()
The error is here : im = qr.make_image. You are storing into im the function make_image of object qr. As you can store functions in variables in Python, this is a valid syntax.
So, you are not calling the function make_image, just storing it. It should be im = qr.make_image().
After you'll implement T. Claverie answer - it is likely that you'll fail in .save() as you are concating string and integer.
Can you try to change the following line:
im.save("filename"+ count + ".png")
to be:
im.save("filename"+ str(count) + ".png")

I need to sum numbers in a file [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Ok I'm learning read and write files at the moment but I need a little help to sum the numbers in a file.
def main ():
sample = open (r'C:\user\desktop\text.txt','r')
for i in range (the range of int is unknown)
file = sample.read ()
sample.close ()
main ()
You may iterate over the file like this:
for i in sample:
and convert using int() to an integer.
The for loop can be done with map and the sum with sum.
This is the final code:
def main ():
sample = open (r'C:\user\desktop\text.txt','r')
result = sum(map(int, sample))
print(result)
sample.close ()
main ()
What you want is:
for line in sample:
# process the line
If each line just contains an integer, you can simplify it further to sum(map(int, sample)).
To add safety, you should cast your integers with error checking and ensure that the file exists before reading it.
import os
def safecast(newtype, val, default=None):
try:
return newtype(val)
except ValueError:
pass
return default
def sumfile(filename):
if not os.path.isfile(filename):
return None
sum = 0
with open(filename, "r") as file:
for line in file:
sum += safecast(int, line, 0)
return sum
sum = sumfile(r'C:\user\desktop\text.txt')
print(sum)

Can't return a dictionary from my function [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I am getting an invalid syntax error
SyntaxError: invalid syntax
root#collabnet:/home/projects/twitterBot# python twitterBot2.py
File "twitterBot2.py", line 58
return screenNames
when returning a dictionary from this function:
def getUserName(lookupIds):
l = len(lookupIds) # length of list to process
i = 0 #setting up increment for while loop
screenNames = {}#output dictionary
count = 0 #count of total numbers processed
print 'fetching usernames'
while i < l:
toGet = []
toAppend = []
if l - count > 100:#blocks off in chunks of 100
for m in range (0,100):
toGet.append(lookupIds[count])
count = count + 1
print toGet
else:#handles the remainder
print 'last run'
r = l - count
print screenNames
for k in range (0,r):#takes the remainder of the numbers
toGet.append(lookupIds[count])
count = count + 1
i = l # kills loop
toAppend = api.lookup_users(user_ids=toGet)
print toAppend
screenNames.append(zip(toGet, toAppend)
#creates a dictionary screenNames{user_Ids, screen_Names}
#This logic structure breaks up the list of numbers in chunks of 100 or their
#Remainder and addes them into a dictionary with their count number as the
#index value
#print str(len(toGet)), 'screen names correlated'
return screenNames
I am running the function like so:
toPrint = {}#Testing Only
print "users following", userid
toPrint = getUserName(followingids)#Testing Only
I have tried commenting out and just printing screenNamesand I still get the same error except on the print statement instead. I am pretty sure I am running the return right thanks for the look.
You forgot a closing parenthesis on a preceding line:
screenNames.append(zip(toGet, toAppend)
# ^ ^ ^^?
# | \---- closed ---/|
# \----- not closed ---/
You'll have another problem here, as screenNames is a dict object, not a list, and has no .append() method. If you wanted to update the dictionary with key-value pairs, use update() instead:
screenNames.update(zip(toGet, toAppend))

Categories