Forwarding variables between functions - python

I'm trying to do a calculation in the following code:
def traffic_intensity(count):
"""Number of cars passing by"""
int(count)
if count < 5000:
level = "Very Low"
elif 5000 <= count < 10000:
level = "Low"
elif 10000 <= count < 18000:
level = "Moderate"
elif count >= 18000:
level = "High"
return level
def number_of_busy_days(counts):
"""Busy days based on traffic flow"""
daily_counts = 0
for count in counts:
if traffic_intensity(level) == "Moderate" or "High":
daily_counts = daily_counts + 1
return daily_counts
counts = [18000, 10000, 500, 9999, 12000]
print(number_of_busy_days(counts))
What I'm trying to achieve is to use the traffic_intensity function to calculate the number of busy days - a busy day is defined as having more than the "Moderate" amount of traffic given in the traffic_intensity function. I've tried a lot of different ways but I'm running out of ideas at this point.
The problem I'm encountering is that it doesn't find the level variable form the first function. I get the following error:
if traffic_intensity(level) == "Moderate" or "High":
NameError: name 'level' is not defined
Is anyone able to help me? Thanks! ^_^

You were passing in a variable level that doesn't exist into the function traffic_intensity. I presume you meant to pass in the variable count.
Likewise, having or "High" as a condition will always result in true since non-empty strings are convertible true in python
def traffic_intensity(count):
"""Number of cars passing by"""
int(count)
if count < 5000:
level = "Very Low"
elif 5000 <= count < 10000:
level = "Low"
elif 10000 <= count < 18000:
level = "Moderate"
elif count >= 18000:
level = "High"
return level
def number_of_busy_days(counts):
"""Busy days based on traffic flow"""
daily_counts = 0
for count in counts:
state = traffic_intensity(count)
if state == "Moderate" or state == "High":
daily_counts = daily_counts + 1
return daily_counts
counts = [18000, 10000, 500, 9999, 12000]
print(number_of_busy_days(counts))

Related

Incrementing a variable by condition

What am I doing wrong? I would like to use count as a global variable.
count = 0
card = low
def running_count ():
if card == low:
count = count+1
elif card == mid:
count = count
elif card == high:
count = count-1
print(count)
I get 0 as the result
count = 0
card = 'low'
def running_count(card):
global count
if card == 'low':
count = count+1
elif card == 'mid':
count = count
elif card == 'high':
count = count-1
running_count(card)
print(count)
#1
running_count(card)
print(count)
#2
But it safer to not use global if you don't have to.
You should try to avoid using global variables where possible.
card should be a string, which you compare to a string inside your function.
You need to call the function you have defined so it gets exectued.
This is an example of how you could do it.
count = 0
card = 'low'
def running_count(count, card):
if card == 'low':
count = count+1
elif card == 'mid':
count = count
elif card == 'high':
count = count-1
return count
count = running_count(count, card)
print(count)
Also you don't really need
elif card == 'mid':
count = count
since you don't change the value of count, you could simply skip this step, because all value besides 'low' and 'high' don't change count.
I hope this helps

Python Problem: Unable to access option in program

I keep recieving an TypeError: cannot unpack non-iterable int object when I select option 4 in the menu. How do I fix this, I have tried for hours with no success. Code is below:
from turtle import right
def selection_sort(altered_number_list, sorting_order):
if sorting_order == 1:
for value in range (0, len(altered_number_list)-1):
least_value = value
for index in range (value+1, len(altered_number_list)):
if altered_number_list[index] < altered_number_list[least_value]:
altered_number_list[index], altered_number_list[least_value] = altered_number_list[least_value], altered_number_list[index]
return altered_number_list
else:
for value in range (0, len(altered_number_list)-1):
least_value = value
for index in range (value+1, len(altered_number_list)):
if altered_number_list[index] > altered_number_list[least_value]:
altered_number_list[index], altered_number_list[least_value] = altered_number_list[least_value], altered_number_list[index]
return altered_number_list
def bubble_sort(altered_number_list, sorting_order):
if sorting_order == 1:
for value in range (len(altered_number_list)):
for index in range (0, len(altered_number_list)-1):
if altered_number_list[index] > altered_number_list[index+1]:
altered_number_list[index], altered_number_list[index+1] = altered_number_list[index+1], altered_number_list[index]
return altered_number_list
else:
for value in range (len(altered_number_list)):
for index in range (0, len(altered_number_list)-1):
if altered_number_list[index] < altered_number_list[index+1]:
altered_number_list[index], altered_number_list[index+1] = altered_number_list[index+1], altered_number_list[index]
return altered_number_list
def insertion_sort(altered_number_list, sorting_order):
if sorting_order == 1:
for value in range(1, len(altered_number_list)):
insert_value = number_list[value]
data_switch = value
while data_switch > 0 and altered_number_list[data_switch-1] > insert_value:
altered_number_list[data_switch] = altered_number_list[data_switch-1]
data_switch -= 1
altered_number_list[data_switch] = insert_value
return altered_number_list
else:
for value in range(1, len(altered_number_list)):
insert_value = number_list[value]
data_switch = value
while data_switch > 0 and altered_number_list[data_switch-1] < insert_value:
altered_number_list[data_switch] = altered_number_list[data_switch-1]
data_switch -= 1
altered_number_list[data_switch] = insert_value
return altered_number_list
def quick_sort(altered_number_list, number_list_min, number_list_max, sorting_order):
if number_list_min < number_list_max:
split_value = partition_sort(altered_number_list, number_list_min, number_list_max, sorting_order)
quick_sort(altered_number_list, number_list_min, split_value-1, sorting_order)
quick_sort(altered_number_list, split_value+1, number_list_max, sorting_order)
def partition_sort(alter_number_list, number_list_min, number_list_max, sorting_order):
if sorting_order == 1:
pivot_value = alter_number_list[number_list_min]
left_value = number_list_min + 1
right_value = number_list_max
complete = False
while not complete:
while left_value <= right_value and alter_number_list[left_value] <= pivot_value:
left_value = left_value + 1
while alter_number_list[right_value] >= pivot_value and right_value >= left_value:
right_value = right_value - 1
if right_value < left_value:
complete = True
else:
alter_number_list[left_value], alter_number_list[right_value] = alter_number_list[right_value], alter_number_list[left_value]
alter_number_list[number_list_min], alter_number_list[right_value] = alter_number_list[right_value] = alter_number_list[number_list_min]
return alter_number_list
else:
pivot_value = alter_number_list[number_list_min]
left_value = number_list_min + 1
right_value = number_list_max
complete = False
while not complete:
while left_value <= right_value and alter_number_list[left_value] >= pivot_value:
left_value = left_value + 1
while alter_number_list[right_value] <= pivot_value and right_value >= left_value:
right_value = right_value - 1
if right_value < left_value:
complete = True
else:
alter_number_list[left_value], alter_number_list[right_value] = alter_number_list[right_value], alter_number_list[left_value]
alter_number_list[number_list_min], alter_number_list[right_value] = alter_number_list[right_value] = alter_number_list[number_list_min]
return alter_number_list
import random
print("This program will sort a list of random numbers using a user determined sorting algorithm.")
sorting_algorithms = ["Selection Sort", "Bubble Sort", "Insertion Sort", "Quick Sort"]
sorting_orders = ["Ascending", "Descending"]
number_list = []
while True:
try:
random_numbers = int(input("Input number of random integers generated: "))
print("Sorting Algorithms: ")
for sort in range (0, len(sorting_algorithms)):
print(f"{sort+1} - {sorting_algorithms[sort]}")
sorting_algorithm = int(input("Select sorting algorithm: "))
print("Sorting Orders: ")
for sort in range (0, len(sorting_orders)):
print(f"{sort+1} - {sorting_orders[sort]}")
sorting_order = int(input("Select sorting algorithm order: "))
if random_numbers < 1 or random_numbers > 999999:
print("Invalid input, integer values greater then or equal to one and integer values less then or equal to 999999 are accepted.")
continue
elif sorting_algorithm < 1 or sorting_algorithm > 4:
print("Invalid input, integer values greater then or equal to one and integer values less then or equal to four are accepted.")
continue
elif sorting_order < 1 or sorting_order > 2:
print("Invalid input, integer values greater then or equal to one and integer values less then or equal to two are accepted.")
continue
for i in range(random_numbers):
number_list.append(random.randint(0, 999999))
print (number_list)
number_list_min = 0
number_list_max = len(number_list) - 1
if sorting_algorithm == 1:
altered_number_list = selection_sort(number_list, sorting_order)
break
elif sorting_algorithm == 2:
altered_number_list = bubble_sort(number_list, sorting_order)
break
elif sorting_algorithm == 3:
altered_number_list = insertion_sort(number_list, sorting_order)
break
elif sorting_algorithm == 4:
altered_number_list = quick_sort(number_list, number_list_min, number_list_max, sorting_order)
break
except:
print("Invalid input, integer values in the program specified parameters are accepted.")
print(altered_number_list)
In the code above, I am able to access options 1, 2, and 3 with no difficulty but I am unable to access the 4th option as it displays an error message. At this point, I have tried renaming variables, using different loops and operations, and creating separate functions but I am still unable to access the 4th option which is the quick sort algorithm. Any help is greatly appreciated!
Here is the code for the quick sort and partition sort:
def quick_sort(altered_number_list, number_list_min, number_list_max, sorting_order):
if number_list_min < number_list_max:
split_value = partition_sort(altered_number_list, number_list_min, number_list_max, sorting_order)
quick_sort(altered_number_list, number_list_min, split_value-1, sorting_order)
quick_sort(altered_number_list, split_value+1, number_list_max, sorting_order)
def partition_sort(alter_number_list, number_list_min, number_list_max, sorting_order):
if sorting_order == 1:
pivot_value = alter_number_list[number_list_min]
left_value = number_list_min + 1
right_value = number_list_max
complete = False
while not complete:
while left_value <= right_value and alter_number_list[left_value] <= pivot_value:
left_value = left_value + 1
while alter_number_list[right_value] >= pivot_value and right_value >= left_value:
right_value = right_value - 1
if right_value < left_value:
complete = True
else:
alter_number_list[left_value], alter_number_list[right_value] = alter_number_list[right_value], alter_number_list[left_value]
alter_number_list[number_list_min], alter_number_list[right_value] = alter_number_list[right_value] = alter_number_list[number_list_min]
return alter_number_list
else:
pivot_value = alter_number_list[number_list_min]
left_value = number_list_min + 1
right_value = number_list_max
complete = False
while not complete:
while left_value <= right_value and alter_number_list[left_value] >= pivot_value:
left_value = left_value + 1
while alter_number_list[right_value] <= pivot_value and right_value >= left_value:
right_value = right_value - 1
if right_value < left_value:
complete = True
else:
alter_number_list[left_value], alter_number_list[right_value] = alter_number_list[right_value], alter_number_list[left_value]
alter_number_list[number_list_min], alter_number_list[right_value] = alter_number_list[right_value] = alter_number_list[number_list_min]
return alter_number_list
I believe the main issue lies in the following code:
while True:
try:
random_numbers = int(input("Input number of random integers generated: "))
print("Sorting Algorithms: ")
for sort in range (0, len(sorting_algorithms)):
print(f"{sort+1} - {sorting_algorithms[sort]}")
sorting_algorithm = int(input("Select sorting algorithm: "))
print("Sorting Orders: ")
for sort in range (0, len(sorting_orders)):
print(f"{sort+1} - {sorting_orders[sort]}")
sorting_order = int(input("Select sorting algorithm order: "))
if random_numbers < 1 or random_numbers > 999999:
print("Invalid input, integer values greater then or equal to one and integer values less then or equal to 999999 are accepted.")
continue
elif sorting_algorithm < 1 or sorting_algorithm > 4:
print("Invalid input, integer values greater then or equal to one and integer values less then or equal to four are accepted.")
continue
elif sorting_order < 1 or sorting_order > 2:
print("Invalid input, integer values greater then or equal to one and integer values less then or equal to two are accepted.")
continue
for i in range(random_numbers):
number_list.append(random.randint(0, 999999))
print (number_list)
number_list_min = 0
number_list_max = len(number_list) - 1
if sorting_algorithm == 1:
altered_number_list = selection_sort(number_list, sorting_order)
break
elif sorting_algorithm == 2:
altered_number_list = bubble_sort(number_list, sorting_order)
break
elif sorting_algorithm == 3:
altered_number_list = insertion_sort(number_list, sorting_order)
break
elif sorting_algorithm == 4:
altered_number_list = quick_sort(number_list, number_list_min, number_list_max, sorting_order)
break
except:
print("Invalid input, integer values in the program specified parameters are accepted.")
The error message:
TypeError: cannot unpack non-iterable int object
is most likely telling you that somewhere in your code, you must have a line that looks like:
a, b = c
where c is an int, and thus cannot be split into a and b as if it were a pair.
There is only one line in your code that looks like this, and it is indeed suspicious:
alter_number_list[number_list_min], alter_number_list[right_value] = alter_number_list[right_value] = alter_number_list[number_list_min]
I believe you meant to swap the two values, and the second equal sign = should instead be a comma ,:
alter_number_list[number_list_min], alter_number_list[right_value] = alter_number_list[right_value], alter_number_list[number_list_min]
Note that the full error trace given by python usually includes more information than just this short error message. You should see a longer message telling you in which function and at which line the error occurred. Reading that full error message would have made it a lot faster to find the suspicious line in your code.

Linking Memory Script

I am trying to make a linking memory script in python. Script should select a few words (user determined number) from several lists. These are my lists and a dictionary for taking user number (determines how many word will be displayed).
import random
LIST_THAT_WILL_BE_DISPLAYED = []
Number_of_Every_List = {
"numberObject":0,
"numberVerb":0,
"numberName":0,
"numberTerm":0,
"numberCountryAndCity":0
}
listObject = ["computer","monitor","apple","banana","car"]
listVerb = ["fill","fly","emphasize","probe","write"]
listTerm = ["Protocol","FTP","SSH","VPN","base64"]
listName = ["John","Amy","Math","Elizabeth","Andrew"]
listCountryAndCity = ["Paris","Czech Republic","USA","Mexico","Netherlands"]
Then It should take inputs from user and append all these to the list above.
# TAKING INPUTS FROM USER
Number_of_Every_List["numberObject"] = int(input(f"Number of Object (max {len(listObject)}): "))
Number_of_Every_List["numberVerb"] = int(input(f"Number of Verb (max {len(listVerb)}): "))
Number_of_Every_List["numberName"] = int(input(f"Number of Name (max {len(listName)}): "))
Number_of_Every_List["numberTerm"] = int(input(f"Number of Term (max {len(listTerm)}): "))
Number_of_Every_List["numberCountryAndCity"] = int(input(f"Number of Country&City (max {len(listCountryAndCity)}): "))
while Number_of_Every_List["numberObject"] != 0:
LIST_THAT_WILL_BE_DISPLAYED.append(random.choice(listObject))
# CHECKING IF THERE IS A DUPLICATE IN "LIST THAT WILL BE DISPLAYED"
if LIST_THAT_WILL_BE_DISPLAYED.count(LIST_THAT_WILL_BE_DISPLAYED[-1]) > 1:
LIST_THAT_WILL_BE_DISPLAYED.pop()
else:
Number_of_Every_List["numberObject"] -= 1
while Number_of_Every_List["numberVerb"] != 0:
LIST_THAT_WILL_BE_DISPLAYED.append(random.choice(listVerb))
if LIST_THAT_WILL_BE_DISPLAYED.count(LIST_THAT_WILL_BE_DISPLAYED[-1]) > 1:
LIST_THAT_WILL_BE_DISPLAYED.pop()
else:
Number_of_Every_List["numberVerb"] -= 1
while Number_of_Every_List["numberName"] != 0:
LIST_THAT_WILL_BE_DISPLAYED.append(random.choice(listName))
if LIST_THAT_WILL_BE_DISPLAYED.count(LIST_THAT_WILL_BE_DISPLAYED[-1]) > 1:
LIST_THAT_WILL_BE_DISPLAYED.pop()
else:
Number_of_Every_List["numberName"] -= 1
while Number_of_Every_List["numberTerm"] != 0:
LIST_THAT_WILL_BE_DISPLAYED.append(random.choice(listTerm))
if LIST_THAT_WILL_BE_DISPLAYED.count(LIST_THAT_WILL_BE_DISPLAYED[-1]) > 1:
LIST_THAT_WILL_BE_DISPLAYED.pop()
else:
Number_of_Every_List["numberTerm"] -= 1
while Number_of_Every_List["numberCountryAndCity"] != 0:
LIST_THAT_WILL_BE_DISPLAYED.append(random.choice(listCountryAndCity))
if LIST_THAT_WILL_BE_DISPLAYED.count(LIST_THAT_WILL_BE_DISPLAYED[-1]) > 1:
LIST_THAT_WILL_BE_DISPLAYED.pop()
else:
Number_of_Every_List["numberCountryAndCity"] -= 1
# SHUFFLING LIST SO SAME TYPE WORDS WON'T BE SHOWN RESPECTIVELY
random.shuffle(LIST_THAT_WILL_BE_DISPLAYED)
print(LIST_THAT_WILL_BE_DISPLAYED)
The problem is if I don't give input that bigger than length of lists, it works fine. But if I give 6 for example, script can't go out from while loop.
Why it happens ?
Lastly I know it's an easy question but I couldn't find why it happens despite hours of searching in internet. :/

Issues with replicating results from R to python by writing customised function

I am trying to convert the R code to python by writing customised function or without function in python based on this following lines of code
customers_df$segment = "NA"
customers_df$segment[which(customers_df$recency > 365*3)] = "inactive"
customers_df$segment[which(customers_df$recency <= 365*3 & customers_df$recency > 365*2)] = "cold"
customers_df$segment[which(customers_df$recency <= 365*2 & customers_df$recency > 365*1)] = "warm"
customers_df$segment[which(customers_df$recency <= 365)] = "active"
customers_df$segment[which(customers_df$segment == "warm" & customers_df$first_purchase <= 365*2)] = "new warm"
customers_df$segment[which(customers_df$segment == "warm" & customers_df$amount < 100)] = "warm low value"
customers_df$segment[which(customers_df$segment == "warm" & customers_df$amount >= 100)] = "warm high value"
customers_df$segment[which(customers_df$segment == "active" & customers_df$first_purchase <= 365)] = "new active"
customers_df$segment[which(customers_df$segment == "active" & customers_df$amount < 100)] = "active low value"
customers_df$segment[which(customers_df$segment == "active" & customers_df$amount >= 100)] = "active high value"
table(customers_2015$segment)
active high value active low value cold inactive
573 3313 1903 9158
new active new warm warm high value warm low value
1512 938 119 901
Python Function
I tried to replicate the same code as above in python by writing function. However, I was not able to get the same categories as R as a well number in each category also differs.
def mang_segment (s):
if (s['recency'] > 365*3):
return ("inactive")
elif (s['recency'] <= 365*3) & (s['recency'] > 365*2):
return ("cold")
elif (s['recency'] <= 365*2) & (s['recency'] > 365*1):
return ("warm")
elif (s['recency'] <= 365):
return ("active")
def mang_segment_up (s):
# if (s['recency'] > 365*3):
# return ("inactive")
# elif (s['recency'] <= 365*3 & s['recency'] > 365*2):
# return ("cold")
# elif (s['recency'] <= 365*2 & s['recency'] > 365*1):
# return ("warm")
if (s['segment'] == "warm") & (s['first_purchase'] <= 365*2):
return ("new warm")
elif (s['segment'] == "warm") & (s['amount'] < 100):
return ("warm low value")
elif (s['segment'] == "warm") & (s['amount'] >= 100):
return ("warm high value")
elif (s['segment'] == "active") & (s['first_purchase'] <= 365):
return ("new active")
elif (s['segment'] == "active") & (s['amount'] < 100):
return ("active low value")
elif (s['segment'] == "active") & (s['amount'] >= 100):
return ("active high value")
active low value 19664
warm low value 4083
active high value 3374
new active 1581
new warm 980
warm high value 561
Any pointer/suggestion would be appreciated.
Thanks in advance
I am a little confused about the purpose of the function (and if it is working as you expect). If you are seeking to mimic your R code within a function, your syntax can line up much closer with your initial code than it currently is. Assuming you are using panads/numpy:
import numpy as np
import pandas as pd
#toy example
s = pd.DataFrame({'rec' : [2000, 1500, 3000, 750]})
def mang_segment (s):
s.loc[(s['rec'] > 365*3), 'seg'] = "inactive" # creating a new column seg with our values
s.loc[(s['rec'] <= 365*3) & (s['rec'] > 365*2), 'seg'] = "cold"
#etc...
#run function
mang_segment(s)
#get value counts
s['seg'].value_counts()
Here we add a column to our dataframe to capture our values, which we can later summarize. This is different than the return function that, if it were working and call appropriately, would not assign it directly to your data frame.
There are other function and ways to get it at this, too. Check out np.where as another option.

I keep getting None

My code:
def get_feedback(mark, out_of):
percentage = int((mark / out_of) * 100)
if percentage >= 80:
print("Excellent")
if 60 < percentage < 70:
print("Good")
if 50 < percentage < 59:
print("Pass")
if percentage < 50:
print("Not a pass")
I know I have to use a return statement somewhere but I'm not really sure how it works or when to use it. If anyone could help, that would be great thank you!
def get_feedback(mark, out_of):
percentage = int((mark / out_of) * 100)
remark = ''
if percentage >= 80:
remark = "Excellent"
elif 60 <= percentage <= 79:
remark = "Good"
elif 50 <= percentage <= 59:
remark = "Pass"
else percentage < 50:
remark = "Not a pass"
return remark
Some suggestions:
I believe you need inclusive range, so include <= instead of <
If one condition satisfies, no need to check the rest of the conditions. So instead of using if for every check, use if - elif- else checks.
Also your question says the range between 60 and 79 for grade 'Good'. You haven't checked it.
Use return in place of print. Example :- return "Excellent".
Another way to do it :
def get_feedback(mark, out_of):
percentage = int((mark / out_of) * 100)
if percentage >= 80:
return "Excellent"
elif 60 <= percentage <= 79:
return "Good"
elif 50 <= percentage <= 59:
return "Pass"
else:
return "Not a pass"
You can make a variable to represent the value of its condition.
def get_feedback(mark, out_of):
percentage = int((mark / out_of) * 100)
if percentage >= 80:
feedback = "Excellent"
elif 60 < percentage < 70:
feedback = "Good"
elif 50 < percentage < 59:
feedback = "Pass"
elif percentage < 50:
feedback = "Not a pass"
return print(feedback)
At the very end, we use return to give us the result of the function. Also, notice that I used elif statements, which are faster than just using if statements.

Categories

Resources