IndexError with dict in python, - python

classes = []
due = []
minutes =[]
grade = []
classname = []
classnume = []
form_orderer = []
listobj = []
i = 0
n = 0
k = 0
def classesl(): #setup class list
classesnum = int(input("How many classes do you have?"))
classnume.append(classesnum)
for _ in range(0,int(classnume[0])):
classname = input("What is the class name??")
classes.append(classname)
def duel(): #setup class list
print("How many days is this assignment for", classes[i], "due in?")
c = input()
due.append(c)
def minutesl(): #setup class list
print("How many minutes will this take", classes[i], "?")
e = input()
minutes.append(e)
def gradesl(): #setup class list
print("What is your grade in that", classes[i], "?")
g = input()
grade.append(g)
def getvars():
global i
for _ in range(0,int(classnume[0])):
duel()
minutesl()
gradesl()
make_dicts()
i += 1
def form_order():
for n in range(0,int(classnume[0])):
a = int(minutes[n])
b = int(grade[n])
form_orderer.append(a/b)
print(form_orderer)
n += 1
def make_dicts():
for k in range(0,int(classnume[0])):
dictx = {'keyz': 'valz'}
dictx.update({'class': classes[k], 'form_order': int(form_orderer[k])})
listobj.append(dictx)
k += 1
def sort(form_orderer):
size = len(form_orderer)
for x in range(form_orderer):
for y in range(form_orderer-x-1):
if(form_orderer[y] > form_orderer[y+1]):
tmp = form_orderer[j]
form_orderer[y] = form_orderer[y+1]
form_orderer[y+1] = tmp
def setup():
while True:
classesl()
getvars()
form_order()
make_dicts()
# sort(form_orderer)
print()
break
setup()
I was wondering how would I get it so the form_orderer list corresponds with a classes list in a dict. So I can then print out the classes in order based off of the order of the form_order list sorted from least to greatest. I already have the bubble sort method down, just need help with the dict.

You call make_dicts twice, which leads to an exception, it's called in get_vars and in setup, if i comment it out in get_vars i don't get any errors
classes = []
due = []
minutes =[]
grade = []
classname = []
classnume = []
form_orderer = []
listobj = []
i = 0
n = 0
k = 0
def classesl(): #setup class list
classesnum = int(input("How many classes do you have?"))
classnume.append(classesnum)
for _ in range(0,int(classnume[0])):
classname = input("What is the class name??")
classes.append(classname)
def duel(): #setup class list
print("How many days is this assignment for", classes[i], "due in?")
c = input()
due.append(c)
def minutesl(): #setup class list
print("How many minutes will this take", classes[i], "?")
e = input()
minutes.append(e)
def gradesl(): #setup class list
print("What is your grade in that", classes[i], "?")
g = input()
grade.append(g)
def getvars():
global i
for _ in range(0,int(classnume[0])):
duel()
minutesl()
gradesl()
#make_dicts()
i += 1
def form_order():
for n in range(0,int(classnume[0])):
a = int(minutes[n])
b = int(grade[n])
form_orderer.append(a/b)
print(form_orderer)
n += 1
def make_dicts():
for k in range(0,int(classnume[0])):
dictx = {'keyz': 'valz'}
dictx.update({'class': classes[k], 'form_order': int(form_orderer[k])})
listobj.append(dictx)
k += 1
def sort(form_orderer):
size = len(form_orderer)
for x in range(form_orderer):
for y in range(form_orderer-x-1):
if(form_orderer[y] > form_orderer[y+1]):
tmp = form_orderer[j]
form_orderer[y] = form_orderer[y+1]
form_orderer[y+1] = tmp
def setup():
while True:
classesl()
getvars()
form_order()
make_dicts()
# sort(form_orderer)
print()
break
setup()

Related

Function call not working proparly (python)

For input 1 to self.trying, the set_jump() method doesn't work. the program dosent execute the while loop in it
Code:
jump = []
z = []
class jumps:
def __init__(self, numberOfJumps, trying):
self.numberOfJumps = numberOfJumps
self.trying = int(trying)
def setJumps(self):
if self.trying == 1:
# print("hello")
self.set_jump()
if self.trying == 2:
self.get_jump()
return ""
def set_jump(self):
counterSetJump = 0
while counterSetJump < int(self.numberOfJumps):
print("what was the distance the athlete jumped at jump number" + str(counterSetJump + 1))
z.append(float(input()))
counterSetJump += 1
return ""
def get_jump(self):
counterGetJumps = 0
while counterGetJumps < int(self.numberOfJumps):
print(z[counterGetJumps])
print("this is the jump for the " + str(counterGetJumps) + " time")
counterGetJumps += 1
return ""
class athlete:
def __init__(self, name, yearsPro):
self.name = name
self.yearsPro = yearsPro
def information(self):
print("the athletes name is " + self.name)
print("he as been active for " + str(self.yearsPro))
return ""
a = []
b = []
i = 0
know = int(input("how many athletes you know the information for"))
while i < know:
a.append(0)
b.append(0)
i = i + 1
j = 0
while j < know:
a[j] = athlete(input("what is the athletes name?"), input("how many years as the athlete been active"))
b[j] = jumps(input("how many jumps did the athlete jumped?"),
input("input 1 for settig and 2 for getting the jumps")) # not getting called?
b[j].setJumps()
j = j + 1
infoFor = int(input("who do you want the info for"))
print(a[int(infoFor) - 1].information())
print(b[int(infoFor) - 1].get_jump())
Check the code out
jump = []
z = []
class jumps:
def __init__(self, numberOfJumps, trying):
self.numberOfJumps = numberOfJumps
self.trying = int(trying)
print("trying = "+str(self.trying))
def setJumps(self) :
if self.trying == 1:
#print("hello")
self.set_jump()
if self.trying == 2:
self.get_jump()
print("Yes I have chnaged trying to = :"+str(self.trying))
return ""
def set_jump(self):
print("set_jump finally called")
i = 0
while(i < int(self.numberOfJumps)):
print("what was the distance the athlete jumped at jump number" + str(i))
z.append(int(input()))
i = i + 1
def get_jump(self):
i = 0
while(i < int(self.numberOfJumps)):
return z[i]
i = i + 1
class athlete:
def __init__(self, name, yearsPro):
self.name = name
self.yearsPro = yearsPro
def information(self):
print("the athletes name is " + self.name)
print("he as been active for " + str(self.yearsPro))
return ""
a = []
b = []
i = 0
know = int(input("how many athletes you know the information for"))
while(i < know):
a.append(0)
b.append(0)
i = i + 1
j = 0
while(j <know):
a[j] = athlete(input("what is the athletes name?"), input("how many years as the athlete been active"))
b[j] = jumps(input("how many jumps did the athlete jumped?"),
input("input 1 for settig and 2 for getting the jumps")) #not getting called?
b[j].setJumps()
k=j
for k in b:
k.setJumps()
#j=j+1
j = j + 1
infoFor = int(input("who do you want the info for"))
print(a[int(infoFor) - 1].information())
print(b[int(infoFor) - 1].setJumps())

Hash table problem for education perposes

The problem is this:
It is required to create and use the hash table structure in a problem
large number of keys.
Here are the steps:
Creating one million (1,000,000) visits to a department store
and Credit Card Payment.
From the very large number of different cards, a relatively small subset is created
as follows. Credit cards for visits will have
sixteen (16) specific fixed digits eg 1234567890123456,
but in four (4) of the sixteen (16) random positions they will also have
four characters: X, Y, Z, W in random order.
eg 12Y45W789012Z4X6
In the other places the prices are the initial ones.
I have written the codes. Is is supposed to run super fast but it runs super slowly and I don't know why... Currently, I am running my code for 10,000 cards. Could you help me? Please excuse my poor english...
The code is bellow:
import string
import random
import time
random.seed(1059442)
global max_load_factor
max_load_factor = 0.6
def printGreaterThan2(num):
while True:
if num % 2 == 1:
isPrime = True
for x in range(3,int(num**0.5),2):
if num % x == 0:
isPrime = False
break
if isPrime:
return num
num += 1
N = printGreaterThan2(1000)
arr = [ [] for _ in range(N)]
arr = [ None for _ in range(N)]
def CreatNewItem():
letters = "WXZY"
days = ["Mon", "Tue", "Wed" , "Thu" , "Fri", "Sat"]
s = ''
count = 0
num = ['1','2','3','4','5','6','7','8','9','0','1','2','3','4','5','6']
list_a = []
while(count!=4):
a = random.randint(0,15)
b = random.choice(letters)
if b not in num and a not in list_a:
num[a] = b
count = count + 1
list_a.append(a)
s = ''.join(num)
d = random.randint(0,5)
day = days[d]
money = random.randint(10,100)
a = [s,day,money]
return a
def hash(key, tablesize):
sum = 0
for pos in range(len(key)):
sum = sum + ord(key[pos])
hash = sum % tablesize
return hash
#--------------------------------------
def rehash(oldhash , tablesize):
rehash = ( oldhash + 1 ) % tablesize
return rehash
#--------------------------------------
def put2 (arr,a,N,lenght,collitions):
if float(lenght)/float(N) >= max_load_factor:
(arr,N,collitions) = Resize(arr,N,lenght,collitions)
key = a[0]
i = hash(key,N)
j =0
while (True):
if arr[i] is None:
arr[i] = a
lenght = lenght + 1
break
elif arr[i][0] == key:
arr[i][2] = arr[i][2] + a[2]
arr[i][1] = arr[i][1] + a[1]
break
else:
if j == 0 :
collitions = collitions +1
j = 1
i = rehash(i,N)
return (lenght,N,arr,collitions )
#----------------------------------------
def Resize(arr,N,lenght,collitions):
print("resize")
N = printGreaterThan2(2*N)
collitions = 0
arr2 = [ [] for _ in range(N)]
arr2 = [ None for _ in range(N)]
for p in arr:
if p is not None:
(lenght,N,arr2,collitions)=put2(arr2,p,N,lenght,collitions)
return (arr2,N,collitions)
#-----------------------------------------
l = 0
cards = []
collitions = 0
t0 = time.time()
i=0
while i!=10000:
b = CreatNewItem()
(l,N,arr,collitions) = put2(arr,b,N,l,collitions)
i=i+1
t1 = time.time() - t0
print('\ntime is {:0.20f}'.format(t1))

Python Elevator Code Simulation Error

I'm really new to this, and am always stuck by basic issues. Please can you show and explain my errors in this chunk of code. Right now the problem is that self is not defined, but I don't understand why.
It would be amazing if someone could clear this up.
import random
import time
class Building:
number_of_floors = 0
customer_list = []
elevator = 0
def __init__(self, floors, customers):
self.number_of_floors = floors
for customerID in range(1, customers + 1):
new = Customer(customerID,self.number_of_floors)
self.customer_list.append(new)
self.customer_list.sort(key = lambda x: x.current_floor)
self.elevator = Elevator(floors,self.customer_list)
self.run()
def run(self):
print('++++++++++++++++++++++++++ELEVATOR IS NOW STARTING+++++++++++++++')
print('Ther are %d customers in the building' % (len(self.customer_list)))
number_of_customers = len(self.customer_list)
self.output()
def output(self):
for customer in self.customer_list:
print("Customer",customer.customerID,"is on floor",customer.current_floor,"and wants to go",customer.destination_floor)
# ELEVATOR MOVING UP
while (self.elevator.current_floor <= self.number_of_floors) & (self.elevator.current_floor > 1):
self.elevator.current_floor -= 1
print(len(self.customer_list),'Customers in lift.')
print('ELEVATOR MOVING DOWN')
print('++++++++++++++++++++++++++++++++++++++++++++++++++++')
print('FLOOR',self.elevator.current_floor)
for customer in self.customer_list:
if (customer.in_elevator == True):
customer.current_floor = self.elevator.current_floor
if (slef.elevator.current_floor == customer.destination_floor) & (customer.in_elevator == True) & (customer.customer_direction == -1):
customer.in_elevator = False
self.customer_list.remove(customer)
print('Customer',customer.customerID,'has reached their destination')
print('There are',len(self.customer_list),'trapped in the elevator')
print('There are',len(Elevator.register_list),'people left on the register')
print('Elevator run is done!!!')
print('CUSTOMERS STUCK IN LIFT ARE BELOW')
for stuck in self.customer_list:
print('Cust. ID:',stuck.customerID,'Dest. Floor:',stuck.destination_floor,'Curr. Floor:',stuck.current_floor,'In Elevator',stuck.in_elevator,'Direction',stuck.customer_direction)
class Elevator:
number_of_floors = 0
register_list = []
current_floor = 0
up = 1
down = -1
def __init__(self, number_of_floors, register_list):
self.number_of_floors = number_of_floors
self.register_list = register_list
def move(self):
pass;
def register_customer(self, customers):
for reg in customers:
self.register_list.append(reg)
def cancel_customer(self, customers):
pass;
class Customer:
current_floor = 0
destination_floor = 0
customerID = 0
in_elevator = False
finished = False
customer_direction = 0
def __init__(self, customerID, floors):
self.customerID = customerID
self.current_floor = random.randint(1, floors)
self.destination_floor = random.randint(1, floors)
while self.destination_floor == self.current_floor:
self.desination_floor = random.randint(1, floors)
if self.current_floor < self.destination_floor:
self.customer_direction = 1
else:
self.customer_direction = -1
def header(): # elevator animation at beginning of program
print(" ELEVATOR OPENING ")
time.sleep(.2)
print("+++++++++++++++++++++++++++++||+++++++++++++++++++++++++++++++++++")
time.sleep(.2)
print("+++++++++++++++++++++++++| |++++++++++++++++++++++++++++++++")
time.sleep(.2)
print("++++++++++++++++| |+++++++++++++++++++")
time.sleep(.2)
print("++++++| |+++++++++")
time.sleep(.2)
print(" ")
time.sleep(.2)
print(" ELEVATOR CLOSING ")
time.sleep(.2)
print("++++++| |+++++++++")
time.sleep(.2)
print("++++++++++++++++| |+++++++++++++++++++")
time.sleep(.2)
print("+++++++++++++++++++++++++| |++++++++++++++++++++++++++++++++")
time.sleep(.2)
print("+++++++++++++++++++++++++++++||+++++++++++++++++++++++++++++++++++")
def main():
try:
floors = int(input('Enter the number of floors: '))
customers = int(input('Enter number of customers: '))
building = Building(floors, customers)
except ValueError:
print('YOU DIDNT ENTER A NUMBER. START AGAIN.')
main()
if __name__ == "__main__":
main()
You haven't indented the functions in your Building class.

How to return values of variables from a function in Python 2.7?

import random
import time
#universal variables
attack = 1
defend = 2
heal = 3
v = False
player_health = 0
player_damage = 0
player_heal = 0
player_block = 0
ai_health = 0
ai_damage = 0
ai_heal = 0
ai_block = 0
#player classes in the form of dictionaries
sniper = {}
sniper["health"] = 50
sniper["damage"] = random.randint(20,40)
sniper["heal"] = random.randint(2,10)
sniper["block"] = 5
tank = {}
tank["health"] = 200
tank["damage"] = random.randint(2,8)
tank["heal"] = random.randint(5,20)
tank["block"] = 20
def start():
print "lets play"
while clas():
pass
while game():
pass
win()
#get the class of the player
def clas():
while True:
Class = raw_input("choose a class:\nsniper = 1\ntank =2\n") #change as stats are added
try:
Class = int(Class)
if Class in (1,2): #change as stats are added
Class1 = random.randint(1,2)
#get the class' stats for the player
if Class == 1:
player_health = sniper["health"]
player_damage = sniper["damage"]
player_heal = sniper["heal"]
player_block = sniper["block"]
if Class == 2:
player_health = tank["health"]
player_damage = tank["damage"]
player_heal = tank["heal"]
player_block = tank["block"]
#get the class' stats for the ai
if Class1 == 1:
ai_health = sniper["health"]
ai_damage = sniper["damage"]
ai_heal = sniper["heal"]
ai_block = sniper["block"]
if Class1 == 2:
ai_health = tank["health"]
ai_damage = tank["damage"]
ai_heal = tank["heal"]
ai_block = tank["block"]
break
except ValueError:
pass
print "Oops! I didn't understand that. Please enter a valid number"
In the above code, there is a function called clas(). In that function, there are 8 variables about the player and ai stats. I want those variables to copy to the variables at lines 10-18, but I'm not sure how.
In general to copy value of any variable use copy.deepcopy function:
from copy import deepcopy
z = 1
x = {'a': {'z': 12}}
def copy_args(z, x):
copy_z = deepcopy(z)
copy_x = deepcopy(x)
return copy_z, copy_x
copy_z, copy_x = copy_args(z, x)
print(copy_z, copy_x)
See more on python-course deepcopy article and python copy module documentation
Good Luck

Python error: "global name 'counter1' is not defined"

My code:
class Persistence:
num = 0
counter1 = 0
counter2 = 0
def __init__(self, num):
self.num = num
#num = input("Enter a non-negative number:: ")
if num < 0:
raise NameError("Negative")
#test else:
#print "ok!"
num_list = []
def digitize(self, num):
num_list = []
n = str(num)
for digit in n:
num_list.append(int(digit))
return num_list
def sum_digits(self, num):
the_list = self.digitize(num)
the_sum = 0
for digit in the_list:
the_sum = the_sum + digit
return the_sum
def times_digits(self, num):
the_list = self.digitize(num)
the_product = 0
for digit in the_list:
the_product = the_product * digit
return the_product
def additive(self, num):
global counter1
sum1 = self.sum_digits(num)
list1 = []
list1 = self.digitize(sum1)
if list1.__len__() > 1:
global counter1
counter1 = counter1 + 1
self.additive(sum1)
return sum1, counter1
def multiplicative(self, num):
global counter2
prod1 = self.times_digits(num)
list1 = []
list1 = self.digitize(prod1)
if list1.__len__() > 1:
global counter1
counter2 = counter2 + 1
self.multiplicative(prod1)
return prod1, counter2
c = Persistence(5)
print c.additive(5)
print c.multiplicative(5)
Not sure why I'm getting this error? It seems to me that I have defined the global variable counter1. I'm also getting this error for counter2, and the only way I've been able to resolve the error is by inserting counter1 = 0 (or any other number) a single line above the return statement on the additive() method. Help would be much appreciated!!
One of the solutions is to move the counters out of class like:
# global variables
num = 0
counter1 = 0
counter2 = 0
class Persistence:
....
....
Leave the rest of your code unmodified.
counter1 and counter2 are defined as class attributes currently, if you want to keep it that way, just access them as classname.attrname:
class Persistence:
num = 0
counter1 = 0
counter2 = 0
def __init__(self, num):
self.num = num
#num = input("Enter a non-negative number:: ")
if num < 0:
raise NameError("Negative")
#test else:
#print "ok!"
num_list = []
def digitize(self, num):
...
def sum_digits(self, num):
...
def times_digits(self, num):
...
def additive(self, num):
sum1 = self.sum_digits(num)
list1 = []
list1 = self.digitize(sum1)
if list1.__len__() > 1:
Persistence.counter1 = Persistence.counter1 + 1
self.additive(sum1)
return sum1, Persistence.counter1
def multiplicative(self, num):
prod1 = self.times_digits(num)
list1 = []
list1 = self.digitize(prod1)
if list1.__len__() > 1:
Persistence.counter2 = Persistence.counter2 + 1
self.multiplicative(prod1)
return prod1, Persistence.counter2
c = Persistence(5)
print c.additive(5)
print c.multiplicative(5)
The appropriate way of solving this issue will be to move the 3 class variables to init method. These variable will become associated with the object can be accessed using 'self'
class Persistence(object):
def __init__(self):
self.counter1 = 0
self.counter2 = 0
def digitize(self, num):
return [int(digit) for digit in str(num)]
def sum_digits(self, num):
return sum(self.digitize(num))
def times_digits(self, num):
the_list = self.digitize(num)
the_product = 0
for digit in the_list:
the_product = the_product * digit
return the_product
def additive(self, num):
sum1 = self.sum_digits(num)
list1 = []
list1 = self.digitize(sum1)
if len(list1) > 1:
self.counter1 += 1
self.additive(sum1)
return sum1, self.counter1
def multiplicative(self, num):
prod1 = self.times_digits(num)
list1 = []
list1 = self.digitize(prod1)
if len(list1) > 1:
self.counter2 += 1
self.multiplicative(prod1)
return prod1, self.counter2
c = Persistence()
print c.additive(5)
print c.multiplicative(5)
You don't num in the constructor if you are not actually using it.

Categories

Resources