I did research solution of this problem for hours but ı can't find any solution. What is the problem in my code?
import numpy as np
q_max = 5
for q in range(1, q_max):
for p in range(0, q_max):
if q>p:
#I want to delete duplicates numbers
a = list(set(p/q))
print(a)
Error:
Traceback (most recent call last):
File "C:\Users\MONSTER\Desktop\gcd.py", line 16, in <module>
alfa = list(set(p/q))
TypeError: 'float' object is not iterable
If you want unique divisors you have to create your set before you start looping, and then add your values to the set. When you're finished looping, you can print the whole set.
The set will deduplicate values, ignoring .add() calls when items already exist in the set (as opposed to the list's .append() method).
q_max = 5
values = set()
for q in range(1, q_max):
for p in range(0, q_max):
if q>p:
values.add(p/q)
print(values)
Your problem is here:
a = list(set(p/q))
set() will cast an iterable (and only an iterable) into a set object - effectively eliminating duplicates. However, you pass it the result of p / q, which is an int divided by an int - a float. The error states you can't pass a float to a function that expects an iterable.
It's unclear why you want to use set() or even list() here. If your expectation is to divide p by q, just do that. a will be a float you can print.
Related
I'm stumped as to why my solution for the Recursive Digit Sum question on HackerRank is being rejected.
Background
The question:
For an input of string n and integer k, the number h is created by concatenating n "k" times. Find the "super digit" of h by recursively summing the integers until one is left.
For example:
n = '9875', k = 2, so h = 98759875
sum(98759875)= 58
sum(58)= 13
sum(13) = 4
Submissions
My Solution
def superDigit(n, k):
h=n*k
while len(h)>1:
h=str(sum([int(i) for i in h]))
return int(h)
Solution I've Found
def superDigit(n, k):
return 1 + (k * sum(int(x) for x in n) - 1) % 9
My Inquiry to the Community
What am I missing in my solution? Yes it's not as simple as the supplied solution involving the digital root function (which I don't fully understand, I just found it online) but I don't see how my function is supplying incorrect answers. It passes most of the test cases but is rejecting for 1/3 of them.
Here is the result of my research on your case:
You don't supply the typing, so I had to case check to find out you use one str and one int. How do I know this?
Well if you used 2 strs the multiplication would fail:
>>> "10"*"2"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'str'
And if you used 2 ints, h would also be an int, and your sum would fail:
>>> str(sum([int(i) for i in 100]))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
So as a result you must have one int and one str. But that also doesn't work since the int*str multiplication uses concatenation instead of the "mathematical" addition:
>>> 10 * "2"
'2222222222'
My solution suggestion is simply to:
Use typing for clarity
Use ints for the multiplication and strs for splitting the digits
This can be done simply by editing only the first two lines:
def superDigit(n: int, k:int) -> int:
h=str(n*k)
while len(h)>1:
h=str(sum([int(i) for i in h]))
return int(h)
Let me know if this helps.
Thanks to some helpful comments from #Tim Roberts, #Paul Hankin, and #yagod I was able to solve the issue. It was in fact due to time-out! All I had to do was update one line: h=str(sum([int(i) for i in n])*(k%9))
PEP 465 adds the # infix operator for matrix multiplication. The lists however don't implement this as of now. Thus as directed by the documentation I tried to implement my own version of __matmul__.
This is my first attempt.
class Matrices(list):
def __matmul__(self,matrix):
tempmat = [[0 for row in range(len(self))] for col in range(len(matrix))]
for i in range(len(self)):
for j in range(len(matrix[0])):
for k in range(len(matrix)):
tempmat[i][j] += self[i][k] * matrix[k][j]
return tempmat
a = Matrices()
a.append([[1,2],[3,4]])
b = Matrices()
b.append([[5,6],[7,8]])
print(a#b)
However I am getting an error,
Traceback (most recent call last):
File "test.py", line 14, in <module>
print(a#b)
File "test.py", line 7, in __matmul__
tempmat[i][j] += self[i][k] * matrix[k][j]
TypeError: can't multiply sequence by non-int of type 'list'
How do I solve this problem? That is, how do I implement the # character for lists in python?
Updated for rewritten question: Clearly, either self[i][k] or matrix[k][j] is a list, not an int. Looks like you were appending in the code outside when you should have been extending.
Original answer to first problem:
You used [[0 for row in range(self)] for col in range(matrix)], when you probably meant to wrap both self and matrix in len calls. Unless for some crazy reason you implemented __index__ on your Matrices class, it's not a integer, so you can't range over it.
I'm relatively new to computer science, and I'm learning how to code in python. I'm trying to figure out how to make a function that takes a list and returns a list of suffixes from the inputted list, in order from shortest length to longest length. For example, entering
[3,4,2,-9,7,6,1]
to the function would return
[[],[1],[6,1],[7,6,1],[-9,7,6,1],[2,-9,7,6,1],[4,2,-9,7,6,1],[3,4,2,-9,7,6,1]]
I've tried several approaches, but so far I'm not having much luck. Here is what I have so far:
def h(m):
newlist = []
x = 0
y = (len[m])-1
while x in range(y):
sublist = []
sublist = sublist + m[x:y]
newlist.append(sublist)
x += 1
return new list
When I try to run the function by entering something like
a = [3,4,2,-9,7,6,1]
h(a)
I get an error:
Traceback (most recent call last):
File "<pyshell#239>", line 1, in <module>
h(a)
File "<pyshell#238>", line 4, in h
y = (len[m])-1
TypeError: 'builtin_function_or_method' object has no attribute '__getitem__'
My objective with this bit of code was simply to create a the list of suffixes without sorting them by length. After I figure out how to create this new list I will add the sorting bit of the code. Keep in mind this is not a homework assignment. Any help would be greatly appreciated!
Possible solution is using list comprehension:
[l[i:] for i in range(len(l), -1, -1)]
This code uses slicing and list comprehension to simply return a list of slices from the end. Using your code, small modification is required - len is a function and not a dictionary, therefore you need to use the call operator () instead of subscript operator [].
y = len(m) - 1
That will not yield correct result though, because you will not get the last suffix and empty suffix. In order to cover these two, you will need to modify y or the loop to cover them
y = len(m) + 1
or better
while x in range(y + 1):
use parenthesis to get the length of the list:
y = len(m) - 1
Your error is in your len:
(len[m]) - 1
len is a function, and you can't index or slice or the what not. Do this instead:
y = len(m) - 1
There's also one other error:
return new list
Should be: (You can't have spaces in variables)
return newlist
Why is the for loop not working?
l=[1,2,3,4,5]
def times(x):
for i in len(x):
x[i]+=10
times(l)
print l
Ideally it should print the elements of the list incremented by 10. But it is giving me the following error:
Traceback (most recent call last):
File "ex1.py", line 5, in <module>
times(l)
File "ex1.py", line 3, in times
for i in len(x):
TypeError: 'int' object is not iterable
Where am I going wrong?
len function will return just the length of the list. Its just a number, so you cannot iterate it with the for loop.
Perhaps you wanted to use the xrange function, along with the len(x)
for i in xrange(len(x)):
We use xrange function here, because range function will create the entire list in memory before iterating. For example,
print range(10)
will give you the newly constructed list with elements from 0 to 9. Think about iterating a very big list. Lets say that the list's size is 10000000. It is really a waste of memory to generate numbers from 0 to 10000000, just for the sake of iterating, right? Thats why we use xrange.
xrange returns an iterable object which gives one number at a time while iterating. Its very memory efficient, as we don't have to construct the entire list.
Suggestion: Unless it is absolutely necessary to modify the original list, you can create a new list and return it.
def times(my_list, my_num = 10):
return [current_num + my_num for current_num in my_list]
l = [1,2,3,4,5]
l = times(l)
print l
It will have the same effect on the data, as the first one. But we use list comprehension to create a new list and we assign it to the variable l. So, now l points to the newly generated list instead of the old list.
This is because len(x) is just an integer, you need to create a list, e.g.
l=[1,2,3,4,5]
def times(x):
for i in range(len(x)):
x[i]+=10
times(l)
print l
For my homework assignment I am supposed to randomly select items in a list. so far I have this code,
import random
room = range(0, 365)
r = random.choice(room)
mySet = set(r)
However, when I attempt to run the program, it says that " 'int' is no iterable".
I was wondering how I can fix this problem?
set() requires an iterable (a list or tuple are iterables) as its argument, where you’ve supplied an integer.
If you want to choose random items (with fixed size) from a set:
list = random.sample(your_set, size);
or if you want to choose random items with random size:
size = random.randint(0, your_set_size):
list = random.sample(your_set, size):
Your set also just has a single value in it so you only have one thing to iterate over. random.choice returns only a single element in the sequence in this case an int. This isn't the cause of the python error (int is not iterable as sneeu says) but will lead to a different result than what you are looking for. random.sample is probably a better choice
However, when I attempt to run the program, it says that " 'int' is no iterable".
I was wondering how I can fix this problem?
Use randint:
>>> from random import randint
>>> randint(0, 360)
86
>>> var = randint(0, 360)
>>> isinstance(var, int)
True
set is actually a type in python, an object like list or dict. Thus, when you pass in an int from random.choice, it gives you an error, because it needs a list, something that you can loop through is an iterable object. So, for example:
>>> set([1,3,4,5,2])
set([1, 2, 3, 4, 5])
Will work, but what you tried to do is this:
>>> set(1) # 1 is used as a number here
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: 'int' object is not iterable
If you wish to create a random list, you can do something like this:
>>> [randint(0, 360) for _ in xrange(10)]
[234, 122, 294, 71, 204, 360, 359, 318, 273, 212]
The above code creates 10 random integers for you to work with. If you want a set, you can just use the set function to get one, but I think its important for you to understand what set is and what it does. Documentation.
Based on the description of assigment, you needn't initialize set with something. You should only add elements in set in each test and check size of set and number of insertions.
That why init should be like this:
import random
room = range(0, 365)
mySet = set()
P.S. Your code below initialization isn't correct
You have an error because you are creating a set object from an int.
A set should be created from an iterable (like a list) not a single object:
So instead of this :
mySet = set(r)
You should do this :
mySet = set([r])
Why don't you follow the Notes from your homework ?
Notes
For each test, you should use Random.randint to pick a number
between 0 and 365 to use that represents a birthday
randint() returns a random integer without having to create a list, which is what is required with the function you are using :choice()