Python dynamic size of integer arguments into list - python

I am having an issue with putting a dynamic number of arguments into a list, then being able to access them later. Here is the code. I am passing arguments such as '2,3,4,5'
def puesdoPrime(*args):
from string import ascii_lowercase
primeInput = []
print "puesdoPrime not yet implemeneted"
for arg in args:
primeInput.append(arg)
for i in primeInput:
print "primeInput value are %i" % primeInput[i]
I am getting the following error:
Traceback (most recent call last):
File "homework3.py", line 41, in <module>
main()
File "homework3.py", line 34, in main
puesdoPrime(printInput)
File "homework3.py", line 15, in puesdoPrime
print "primeInput value are %i" % primeInput[i]
TypeError: list indices must be integers, not tuple
This is how the function is being called:
userInput = input()
if userInput == 1:
print "What numbers do you want to find that are simultaneously Puesdo Prime?"
printInput = input()
puesdoPrime(printInput)
Any help would be very much appreciated in helping solve this.

Using for i in primeInput will loop over the values of your list, not the indices. So you would want to change your second for loop to the following:
for item in primeInput:
print "primeInput value are %i" % item
Or to loop over the indices:
for i in range(len(primeInput)):
print "primeInput value are %i" % primeInput[i]
It would also help to see how you are calling puesdoPrime(), but to use *args correctly your call should look something like the following:
puesdoPrime(2, 3, 4, 5)
Or if you have an existing collection of arguments:
the_args = (2, 3, 4, 5)
puesdoPrime(*the_args)
Without the * in the previous code you would only be passing a single argument which would be a four element tuple.
As a side note, I think you mean "pseudo", not "puesdo".

Related

TypeError: 'int' object is not callable python 2.7

I know this question has been asked a lot before, but I can't seem to find any place in my code where I'm binding my list a to an integer value. I've changed all my variable names but to no avail.
Here's the entire code I'm running:
import sys
def powerset(a):
# returns a list of all subsets of the list a
if (len(a) == 0):
return [[]]
else:
allSubsets = [ ]
for subset in powerset(a[1:]):
allSubsets += [subset]
allSubsets += [[a[0]] + subset]
return allSubsets
if __name__ == '__main__':
no_test = int(sys.stdin.readline())
for i in xrange(no_test):
xor_res = 0
len = int(sys.stdin.readline())
numbers_array = map(int,sys.stdin.readline().split())
numbers = []
for i in numbers_array:
numbers.append(i)
maxset = powerset(numbers)
for set in maxset:
if len(set) != 0:
temp = 0
for i in set:
temp = temp^i
xor_res = xor_res ^ temp
print xor_res
And this is the error I'm getting:
Traceback (most recent call last):File "solution.py", line 24, in <module>maxset = powerset(numbers)File "solution.py", line 6, in powerset if (len(a) == 0):TypeError: 'int' object is not callable
Can someone please tell me what's going wrong here?
Thanks!
You've created a variable called len that shadows the built in function len():
len = int(sys.stdin.readline())
When you try to call the len function throughout your code, the interpreter finds the len variable first and tries to call it like a function. Since it's an int, this can't be done and we see the error.
To solve your problem, call your variable something different. In general, avoid creating variables with names like "len", "list", "map", etc, since using these names shadows the built in ones.

ValueError in range function (to print 3^(2^n)) in python

while trying to print the sequence of power(3,2^n), i.e, 3^2,3^4,3^8 , I tried using the following line using range function.Is it possible to use the range function to get the desired output? If so please let me know where did I went wrong.
for i in range(3,1000, i*(i-1)): print (i*i)
for example, the following output is expected for i=3,9,81
i*i:=9,81,6561
But the error is :
Traceback (most recent call last):
File "<pyshell#28>", line 1, in <module>
for i in range(3,1000, i*(i-1)): print (i*i)
ValueError: range() arg 3 must not be zero
How can the step value be zero in this case?
You could use a list comprehension to build a list of all of your powers:
mylist = [3**(2**n) for n in range(1,10)] # or whatever range
and then iterate through the comprehension to print all of your results if you want. You can do other stuff with your results in this loop instead of print them.
for item in mylist:
print(item) # print each item on a new line
i = 2
while 3**i < 1000:
print(3**i)
i *= 2
I'm pretty sure what you want to do is very similar to this question. You want to be calling a list comprehension:
powersofthree = [3**(2**i) for i in range(10)]
which returns
[3, 9, 81, ... ]
Then you can print the result at you leisure.
Also, as many in the comments have pointed out, you used i before it was defined, which is why you encountered an error

Using str.replace to replace letters in a string at different placeholders of the string

I have a problem that I am working on. The goal of the problem is to take the string placeholder i. If i is an even placeholder, replace the letter at i with the letter at i -1. If the i place holder is odd, then replace the letter i with the letter at i +1.
Here is my code so far:
def easyCrypto (s):
for i in range (0,len(s)-1):
if i % 2 == 0:
str(s).replace(i,((i-1)))
if i % 2 != 0:
str(s).replace(i,((i+2)))
print (s)
My error:
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
easyCrypto('abc')
File "C:/Python/cjakobhomework7.py", line 4, in easyCrypto
str(s).replace(i,((i-1)))
TypeError: Can't convert 'int' object to str implicitly
update!!
New code based on answers:
def easyCrypto (s):
for i in range (0,len(s)-1):
if i % 2 == 0:
s = str(s).replace(s(i),(s(i-1)))
else:
s = s.replace(s(i), s(i + 1))
print (s)
However I still have the following errors:
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
easyCrypto('abc')
File "C:/Python/cjakobhomework7.py", line 4, in easyCrypto
s = str(s).replace(s(i),(s(i-1)))
TypeError: 'str' object is not callable
Any ideas? thank you
Use s[i] instead of s(i), and likewise for the other indexes.
There are two things here:
str.replace does not automatically stringify its arguments. You need to manually convert them into strings. Remember that: "Explicit is better than implicit."
str.replace does not work in-place because strings are immutable in Python. You need to reassign s to the new string object returned by str.replace.
Your code should be:
s = s.replace(str(i), str(i-1))
Also, you can replace if i % 2 != 0: with else: since the condition of the second if-statement can only be true if the first is false:
if i % 2 == 0:
s = s.replace(str(i), str(i-1))
else:
s = s.replace(str(i), str(i+1))
Regarding your edited question, you are trying to call the string s as a function by placing parenthesis after it. You need to use square brackets to index the string:
>>> 'abcde'[0]
'a'
>>> 'abcde'[3]
'd'
>>>
In your case it would be:
s = s.replace(s[i], s[i-1])
As a general rule of thumb, parenthesis (...) are for calling functions while square brackets [...] are for indexing sequences/containers.

How to add elements of a list in Python 3.5.5?

My assignment is:
Write a function sumOfPairs that has one parameter of type list. The
list can be empty or contain integers. The length of the list must be
0 or an even number. If the length of the list is not 0 and is not
even, the function should print an error message and return None. You
can assume the list contains only integers. The function returns the
list of the sum of each consecutive pair of the numbers in the list.
Example: If the list is [1,5,2,10,15,2,9,3], the function returns
[6,12,17,12].
My attempt so far is:
def sumOfPairs (list1: list):
if len(list1) != 0 and len(list1)%2 != 0:
print ("Error")
return (None)
else:
x = list1.index(int)
answer = []
while x<=len(list1):
newListValue=list1(x)+list1(x+1)
answer.insert(x,newListValue)
x=x+2
return (answer)
print (sumOfPairs ([1,5,2,10,15,2,9,3]))
Yet it yields the following error upon execution:
Traceback (most recent call last):
File "C:\Users\Andrew\Desktop\lab3.py", line 79, in <module>
print (sumOfPairs ([1,5,2,10,15,2,9,3]))
File "C:\Users\Andrew\Desktop\lab3.py", line 71, in sumOfPairs
x = list1.index(int)
ValueError: <class 'int'> is not in list
How can I fix this?
def sum_of_pairs(l):
if len(l) % 2: # if the length of the list mod 2 has a remainder, the list length is uneven
print("Error, uneven length list")
else: # else, step through the list in pairs and add each pairing
return [l[i]+ l[i+1] for i in range(0,len(l),2)]
In [3]: (sum_of_pairs([1,5,2,10,15,2,9,3]))
Out[3]: [6, 12, 17, 12]
A python function that does not specify a return value as in the if len(l) % 2: will return None by default so we do not need to explicitly return None.
In [11]: l = [1,5,2,10,15,2,9,3]
In [12]: [sum(pair) for pair in zip(l[0::2],l[1::2])]
Out[12]: [6, 12, 17, 12]
I don't particularly like your approach here, but let's take a look at the error specifically.
Traceback (most recent call last):
File "C:\Users\Andrew\Desktop\lab3.py", line 79, in <module>
print (sumOfPairs ([1,5,2,10,15,2,9,3]))
File "C:\Users\Andrew\Desktop\lab3.py", line 71, in sumOfPairs
x = list1.index(int)
ValueError: <class 'int'> is not in list
Now look at the line it occurs on, and try to say it in English
x equals the first index in list1 where the value is 'int'
Note that it's not the value is AN int! This is crucial, and is the reason for the error. Your list does not INCLUDE the class int. That would be something like:
[1,2,3,int,5,6,7,8] # not your list
Much easier would be to test that ALL your indices contain ints, then just iterate through the list. Let's try that (even though your exercise says otherwise, partially to keep you from just copy/pasting this!! :D)
def sum_of_pairs(lst: list):
if len(lst) == 0 or len(lst) % 2 != 0:
raise ValueError("Invalid list length")
# makes more sense to raise an exception here than print an error
if any(not isinstance(int, el) for el in lst):
# if any element is not an int:
raise ValueError("Invalid list contents")
result_list = []
for element in lst:
first_el = element
second_el = next(lst)
# advance the iterator once to grab the next element
result_list.append(first_el + second_el) # add them and append
return result_list
Or even easier if you know how to use the grouper recipe, which is in the pydocs for the itertools module here:
def grouper(iterable, n):
return zip(*iter([iterable])*n)
def sum_of_pairs(lst: list):
# validate here, I'm not going to re-write it
return [sum(pair) for pair in grouper(lst, 2)]

TypeError: argument of type 'int' is not iterable

#!/usr/bin/python
import time
from array import *
THINKING = 0
HUNGRY = 1
EATING = 2
class Philosopher:
def __init__(self):
self.ph = array('i',[1, 2, 3, 4, 5])
self.sleeptime = array('i',[30, 30, 30, 30, 30])
def initialization_code(self):
for i in range(self.ph.__len__()):
self.ph[i] = THINKING
def pickup(self,i):
self.ph[i] = HUNGRY
self.test(i)
if(EATING not in (self.ph[i])):
while(EATING not in (self.ph[i])):
time.sleep(self.sleeptime[i])
def putdown(self,i):
self.ph[i] = THINKING
self.test((i+4)%5)
self.test((i+1)%5)
def test(self,i):
if((2 not in (self.ph[(i+4)%5]))and(2 not in (self.ph[(i+1)%5]))and(self.ph[i]==HUNGRY)):
self.ph[i] = EATING
def start_process(self):
for i in range(self.ph.__len__()):
self.pickup(i)
self.putdown(i)
def display_status(self):
for i in range(self.ph.__len__()):
if (self.ph[i] == 0):
print "%d is THINKING" % i+1
elif (self.ph[i] == 1):
print "%d is WAITING" % i+1
elif (self.ph[i] == 2):
print "%d is EATING" % i+1
phil = Philosopher()
phil.initialization_code()
phil.start_process()
phil.display_status()
The above is my piece of code in which i'm trying to implement dining philosopher problem in python.
when i run this code it shows me this error:
Traceback (most recent call last):
File "dining.py", line 59, in <module>
phil.start_process()
File "dining.py", line 43, in start_process
self.pickup(i)
File "dining.py", line 27, in pickup
self.test(i)
File "dining.py", line 38, in test
if((2 not in (self.ph[(i+4)%5]))and(2 not in (self.ph[(i+1)%5]))and(self.ph[i]==HUNGRY)):
TypeError: argument of type 'int' is not iterable
Can anyone please help me at this, why is it showing this error. I searched about it but couldn't resolve.
Thanks in advance!!
Your equations result in integers. You can't use in on integers.
>>> 'foo' in 3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: argument of type 'int' is not iterable
Besides the problem with in, which only can applied to iterables and to objects having __contains__ in its class definition, you probably are going to run into the next problem: You don't have parallelization. So you either should use threads or replace the
if(EATING not in (self.ph[i])):
while(EATING not in (self.ph[i])):
time.sleep(self.sleeptime[i])
lines - which are an endless loop, because no one sets the EATING status.
Or you should do the timing by other means, by constantly checking wall clock time or by creating an event scheduling system which takes care of the actions which have to be done.
BTW: The print "%d is THINKING" % i+1 are broken as well, because there are no () around the i+1 and % has higher precedence.
I think you are generally using:
in / not in
incorrectly. It looks like you are trying to compare integers which should be done with
==
!=
>
>=
<
<=
operators instead.

Categories