Range function is not working properly in jupyter notebook - jupyter-notebook

for i in range():
for j in range(i):
print("*",end = " ")
print()
Error:
TypeError
Traceback (most recent call last) <ipython-input-81-6bc40b03c32e> in <module>
----> 1 for i in range():
2 for j in range(i):
3 print("*",end = " ")
4 print()
5
TypeError: 'int' object is not callable

In Python, range() is not valid, you need to provide an argument to allow it to create a range.
For example:
range(3) will give you a generator for the integers { 0, 1, 2 };
range(3, 20, 7) will generate { 3, 10, 17 };
range() will just generate an error :-)

You have to pass an int parameter in range() just the way you did in the second for loop. like, range(10).
for i in range(10):
for j in range(i):
print("*",end = " ")
print()

Related

errors when hashing data in Python

I'm hoping somebody could please assist. When running the following code (below) in Jupyter notebook, I get an error
dummydata["ID_NUMBER"] = dummydata["ID_NUMBER"].to_string()
def clean_dummydata(dummydata,cols):
for col_name in cols:
keys = {cats: i for i,cats in str(hash(dummydata[col_name].unique()))}
dummydata[col_name] = dummydata[col_name].apply(lambda x: keys[x])
return dummydata
cols = ['ID_NUMBER']
dummydata = clean_dummydata(dummydata,cols)
dummydata.to_csv('anon_dummydata.csv')
This is the error:
TypeError Traceback (most recent call
last) ~\AppData\Local\Temp/ipykernel_3140/2100616149.py in
7
8 cols = ['ID_NUMBER']
----> 9 dummydata = clean_dummydata(dummydata,cols)
10 dummydata.to_csv('anon_dummydata.csv')
~\AppData\Local\Temp/ipykernel_3140/2100616149.py in
clean_dummydata(dummydata, cols)
2 def clean_dummydata(dummydata,cols):
3 for col_name in cols:
----> 4 keys = {cats: i for i,cats in str(hash(dummydata[col_name].unique()))}
5 dummydata[col_name] = dummydata[col_name].apply(lambda x: keys[x])
6 return dummydata
TypeError: unhashable type: 'numpy.ndarray'
Mutable types like NumPy arrays and lists are not hashable because they could change and break the lookup based on the hashing algorithm.
So, you can use hash only with immutable datatypes like a tuple. So, you can convert your numpy array into a tuple and then hash it, for eg:
import numpy as np
z = np.array(['one', 'two', 'three'])
tuple_z = tuple(z)
hash_z = hash(z)
and it should run perfectly.

add() missing 1 required positional argument: 'sum1'

class A:
def __init__(self):
print(" ")
def have (self,a,b):
a=int(input("Enter A : "))
b=int(input("Enter b : "))
class B(A):
def add(self,sum1):
sum1=A+B
print("Sum is: ",sum1)
obj = B()
obj.add()
the errors came
TypeError Traceback (most recent call last)
<ipython-input-47-714fd5e33719> in <module>
13
14 obj = B()
---> 15 obj.add()
TypeError: add() missing 1 required positional argument: 'sum1'
Change your code a bit like so:
class A:
def __init__(self):
print(" ")
def have (self):
# tell code to use this class's a and b variabes
self.a = int(input("Enter A : "))
self.b = int(input("Enter b : "))
class B(A):
# don't include anything in add except self
# because a and b are already in class A
def add(self):
# use self.a and self.b that were inherited from A
sum1 = self.a + self.b
print("Sum is: ",sum1)
obj = B()
# call the have method first to ask for inputs
obj.have()
obj.add()
Now, when you call obj.have(), you will be asked what A and B should be. But note that you are using capital A and B only as display. You are storing data into lowercase a and b. In the code above, we are using the class's a and b variables by using self.a and self.b.
Once those variables are populated, then we call obj.add(), which adds those 2 variables.
Check out some interesting literature about classes here: https://www.digitalocean.com/community/tutorials/understanding-class-and-instance-variables-in-python-3

Associate letters with its value and sort output in python

Please help on this. I have an input like this:
a = """A|9578
C|547
A|459
B|612
D|53
B|6345
A|957498
C|2910"""
I want to print in sorted way the numbers related with each letter like this:
A_0|459
A_1|957498
A_2|9578
C_0|2910
C_1|547
B_0|612
B_1|6345
D_0|53
So far I was able to store in array b the letters and numbers, but I'm stuck when I try to create dictionary-like array to join a single letter with its values, I get this error.
b = [i.split('|') for i in a.split('\n')]
c = dict()
d = [c[i].append(j) for i,j in b]
>>> d = [c[i].append(j) for i,j in b]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <listcomp>
TypeError: list indices must be integers or slices, not str
I'm working on python 3.6 just in case. Thanks in advance.
We'll split the string into pairs, sort those pairs, then use groupby and enumerate to come up with the indices.
from itertools import groupby
from operator import itemgetter
def process(a):
pairs = sorted(x.split('|') for x in a.split())
groups = groupby(pairs, key=itemgetter(0))
for _, g in groups:
for index, (letter, number) in enumerate(g):
yield '{}_{}|{}'.format(letter, index, number)
for i in process(a): print(i)
gives us
A_0|459
A_1|957498
A_2|9578
B_0|612
B_1|6345
C_0|2910
C_1|547
D_0|53

Python: Type Error unsupported operand type(s) for +: 'int' and 'str'

I'm really stuck, I am currently reading Python - How to automate the boring stuff and I am doing one of the practice projects.
Why is it flagging an error? I know it's to do with the item_total.
import sys
stuff = {'Arrows':'12',
'Gold Coins':'42',
'Rope':'1',
'Torches':'6',
'Dagger':'1', }
def displayInventory(inventory):
print("Inventory:")
item_total = sum(stuff.values())
for k, v in inventory.items():
print(v + ' ' + k)
a = sum(stuff.values())
print("Total number of items: " + item_total)
displayInventory(stuff)
error i get:
Traceback (most recent call last):
File "C:/Users/Lewis/Dropbox/Python/Function displayInventory p120 v2.py", line 17, in
displayInventory(stuff)
File "C:/Users/Lewis/Dropbox/Python/Function displayInventory p120 v2.py", line 11, in displayInventory
item_total = int(sum(stuff.values()))
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Your dictionary values are all strings:
stuff = {'Arrows':'12',
'Gold Coins':'42',
'Rope':'1',
'Torches':'6',
'Dagger':'1', }
yet you try to sum these strings:
item_total = sum(stuff.values())
sum() uses a starting value, an integer, of 0, so it is trying to use 0 + '12', and that's not a valid operation in Python:
>>> 0 + '12'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
You'll have to convert all your values to integers; either to begin with, or when summing:
item_total = sum(map(int, stuff.values()))
You don't really need those values to be strings, so the better solution is to make the values integers:
stuff = {
'Arrows': 12,
'Gold Coins': 42,
'Rope': 1,
'Torches': 6,
'Dagger': 1,
}
and then adjust your inventory loop to convert those to strings when printing:
for k, v in inventory.items():
print(v + ' ' + str(k))
or better still:
for item, value in inventory.items():
print('{:12s} {:2d}'.format(item, value))
to produce aligned numbers with string formatting.
You are trying to sum a bunch of strings, which won't work. You need to convert the strings to numbers before you try to sum them:
item_total = sum(map(int, stuff.values()))
Alternatively, declare your values as integers to begin with instead of strings.
This error produce because you was trying sum('12', '42', ..), so you need to convert every elm to int
item_total = sum(stuff.values())
By
item_total = sum([int(k) for k in stuff.values()])
The error lies in line
a = sum(stuff.values())
and
item_total = sum(stuff.values())
The value type in your dictionary is str and not int, remember that + is concatenation between strings and addition operator between integers. Find the code below, should solve the error, converting it into int array from a str array is done by mapping
import sys
stuff = {'Arrows':'12',
'Gold Coins':'42',
'Rope':'1',
'Torches':'6',
'Dagger':'1'}
def displayInventory(inventory):
print("Inventory:")
item_total = (stuff.values())
item_total = sum(map(int, item_total))
for k, v in inventory.items():
print(v + ' ' + k)
print("Total number of items: " + str(item_total))
displayInventory(stuff)

Return statement from base case of recursive function (Python)

I’m trying to get a better understanding of recursion using the merge sort algorithm using Python 2.7. I have written a small snippet of code to break down a list recursively. The code seems to work fine except for the last step. For the base case, the program is supposed to return a list of size 1. However, it is returning the value “none”. Where am I going wrong?
mylist = [14,88,2,14,9,123,1,5]
def concour(thelist):
mid = len(thelist) / 2
LeftSide = thelist[:mid]
print LeftSide,'length is ', len(LeftSide)
if len(LeftSide) == 1: #the base case here
print LeftSide
return LeftSide
else:
concour(LeftSide) #recursive call
print concour(mylist)
"""
[14, 88, 2, 14] length is 4
[14, 88] length is 2
[14] length is 1
[14]
None
"""
You're missing your return statement in the recursive call.

Resources