21.1 LAB: Replacement words - python

Write a program that finds word differences between two sentences. The input begins with the first sentence and the following input line is the second sentence. Assume that the two sentences have the same number of words.
The program displays word pairs that differ between the two sentences. One pair is displayed per line.
Ex: If the input is:
Smaller cars get better gas mileage
Tiny cars get great fuel economy
then the output is:
Smaller Tiny
better great
gas fuel
mileage economy
Hint: Store each input line into a list of strings.
Here is my code:
s1 = input()
s2 = input()
w1 = s1.split()
w2 = s2.split()
for i in len(w1):
if (w1[i] != w2[i]):
print(w1[i],w2[i])
and this is what i got
Traceback (most recent call last):
File "main.py", line 7, in <module>
for i in len(w1):
TypeError: 'int' object is not iterable

put range() before len:
s1 = input()
s2 = input()
w1 = s1.split()
w2 = s2.split()
for i in range(len(w1)):
if (w1[i] != w2[i]):
print(w1[i],w2[i])
#output
Smaller cars get better gas mileage
Tiny cars get great fuel economy
Smaller Tiny
better great
gas fuel
mileage economy

The error in the code for i in len(w1): is that len(w1) returns the length of the list w1, which is an integer, and range() is expected as the argument for the for loop.
Code:
# Hint given: Store each input line into a list of strings.
s1=list(map(str,input().split(" "))) #This is how you can store in the list.
s2=list(map(str,input().split(" ")))
for i in range(len(s1)): #As given in the question The two sentences have the same number of words. there is no worry of index out of range..!
if(s1[i] != s2[i]):
print(s1[i],s2[i])
Output:
Smaller cars get better gas mileage
Tiny cars get great fuel economy
Smaller Tiny
better great
gas fuel
mileage economy

Related

How do I call a math function on each of the items obtained from a list from .split in an input?

def bill_cal():
split_amount = bill_amount_list * (1-cashback_rate) / person_split_no
print(f"each person should pay {split_amount}.")
bill_amount = input("How much is the bill? You can enter multiple bills separated by comma.\n")
bill_amount_list = bill_amount.split(",")
cashback_rate = float(input("Is there any credit card cashback on the bills? 2% = 0.02\n"))
person_split_no = int(input("How many people are splitting the bill?"))
for bill in map(float, bill_amount_list):
bill_cal()
I am trying to cast float on each item obtained from bill_amount.split(","), and perform the bill_cal() function, but got below error:
How much is the bill? You can enter multiple bills separarted by comma.
100,200
Is there any credit card cashback on the bills? 2% = 0.02
.02
How many people are splitting the bill?2
Traceback (most recent call last):
File "main.py", line 10, in <module>
bill_cal()
File "main.py", line 2, in bill_cal
split_amount = bill_amount_list * (1-cashback_rate) / person_split_no
TypeError: can't multiply sequence by non-int of type 'float'
You are "multiplying" your bill_amount_list which is... well, a list. Sequences can be "multiplied" by int (meaning you will repeat the sequence), but not by float, hence your error.
Pass your bill to the function, and use it in the computation:
def bill_cal(amount):
split_amount = amount * (1-cashback_rate) / person_split_no
#...
for bill in map(float,bill_amount_list):
bill_cal(bill)
You need to call the function with a local variable.
Also it's good practice to check your input as well like this:
if item.isnumeric():
'call the function'

Problems with random "Lists"

I want to create a game where a person is drawn out randomly.
Can some1 check the code if everything is setup correctly.
I have tested the code numerous times and its ok in my eyes.
But when I send the code to a review, to an online class I only get 50% score.
import random
# 🚨 Don't change the code below 👇
test_seed = int(input("Create a seed number: "))
random.seed(test_seed)
# Split string method
names_string = input("Give me everybody's names, separated by a comma. ")
names = names_string.split(", ")
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
print(names)
names_count = len(names)
random_name_number = random.randint(0, names_count)
print(f"{names[random_name_number]} is going to buy the meal today!")
The problem here is almost certainly with randint. Unlike most Python conventions, the parameters to randint are inclusive. That means, if you supply (0,10), you are going to get numbers from 0 to 10. In your case, if they supply 10 names, using index 10 is going to cause an exception.
You want random.randrange, not random.randint. randrange(0,10) will supply numbers from 0 to 9.

The sum of a list cannot be placed in a file I am trying to write. What can be done?

I am having a lot of trouble with writing the totals to a new file. When I run this code, it gives me an error code like this:
line 115, in <module>
OutputFile.write("The total amount of money you spent on food is $"+str(round(FoodTotal,2))+"." +'/n')
TypeError: 'list' object is not callable
I have tried surrounding the list with square brackets. I have also tried converting the sum of each list into a string, but I get the same result. What can I do?
#import file and read it, change the Expenses.txt name into the name of the file you wish to read
FileName=input("Please input the name of the file you wish to read and include the .txt! (Remember to place the file in the same folder as this python file): ")
Expense=open(FileName ,"r")
#create five lists which the data will be sorted into based on word after value
FoodList=[]
HousingList=[]
TransportationList=[]
EntertainmentList=[]
MiscList=[]
#create a short term list to sort the expenses into
print()
count=0
for line in Expense:
str=line.split()
print(str)
count+=1
if "Food" in str:
FoodPrice=float(str[0])
FoodList.append(FoodPrice)
elif "Housing" in str:
HousingPrice=float(str[0])
HousingList.append(HousingPrice)
elif "Transportation" in str:
TransportationPrice=float(str[0])
TransportationList.append(TransportationPrice)
elif "Entertainment" in str:
EntertainmentPrice=float(str[0])
EntertainmentList.append(EntertainmentPrice)
elif "Misc" in str:
MiscPrice=float(str[0])
MiscList.append(MiscPrice)
else:
print("The Text File Provided is not in the Correct Format")
break
str.clear()
print(FoodList)
print(HousingList)
print(TransportationList)
print(EntertainmentList)
print(MiscList)
#add all the expenses by category
FoodTotal=round(sum(FoodList),2)
print("The total amount of money you spent on food is $",round(FoodTotal,2)," .")
HousingTotal=sum(HousingList)
print("The total amount of money you spent on housing costs is $",round(HousingTotal,2)," .")
#HousingPrint=str("The total amount of money you spent on housing costs is $",round(HousingTotal,2))," .")
TransportationTotal=sum(TransportationList)
print("The total amount of money you spent on transportation is $",(round(TransportationTotal,2))," .")
#TransportationPrint=str("The total amount of money you spent on transportation is $",(round(TransportationTotal,2))," .")
EntertainmentTotal=sum(EntertainmentList)
print("The total amount of money you spent on entertainment is $",(round(EntertainmentTotal,2))," .")
#EntertainmentPrint=str("The total amount of money you spent on entertainment is $",(round(EntertainmentTotal,2))," .")
MiscTotal=sum(MiscList)
print("The total amount of money you spent on miscellaneous expenses is $",(round(MiscTotal,2))," .")
#MiscPrint=str("The total amount of money you spent on miscellaneous expenses is $",(round(MiscTotal,2))," .")
#add all of the expenses together for the total amount of money spent
TotalExpenses=FoodTotal+HousingTotal+TransportationTotal+EntertainmentTotal+MiscTotal
OutputName=FileName.replace(".txt","-Output.txt")
OutputFile=open(OutputName,"w")
OutputFile.write("The total amount of money you spent on food is $"+str(round(FoodTotal,2))+"." +'/n')
OutputFile.write(HousingPrint+'/n')
OutputFile.write(TransportationPrint+'/n')
OutputFile.write(EntertainmentPrint+'/n')
OutputFile.write(MiscPrint+'/n')
OutputFile.write(TotalString+'/n')
OutputFile.write(OutputString+'/n')
TotalString=str("There were ",count," expenses that totaled: $",round(TotalExpenses,2)," .")
OutputString=str("Output file: "+OutputName+" has been created.")
print("There were ",count," expenses that totaled: $",round(TotalExpenses,2)," .")
print("Output file: "+OutputName+" has been created.")
"""
output=open("OutputFile.txt","w")
output.write(line)
output.write("\n")
output.close()
"""
Expense.close()
You reassigned str here:
str=line.split()
Never name a variable str, list, or any other builtin name -- it will lead to confusing bugs exactly like this one! Running a linter on your code will help you catch things like this.
For what it's worth, using str and + to compose a string is generally considered "unpythonic". Using an f-string is easier:
OutputFile.write(f"The total amount of money you spent on food is ${round(FoodTotal,2)}.\n")
You're overriding the built-in str on str=line.split() change it to something else. Also use f strings since you don't need to do the explicit type conversion:
OutputFile.write(f"The total amount of money you spent on food is ${round(FoodTotal,2)}. \n")
str=line.split() is your issue. You shadowed the built-in name str, replacing it with a list, so lines like str(round(FoodTotal,2)) thus would fail because str is not a function any longer.

Need to write a if statement to determine how many 50KG and 10KG bag are required based on a total KG input from a user

I have written a program where a user get shown three types of bird food. Each bird food comes in 10kg and 50kg bags each with different prices. The prices are stored in a list:
Pellets = ['Pellets', 22.75, 100.00]
Mash = ['Mash', 20.50, 90.00]
Enhanced = ['Enhanced', 25.50, 125.50]
Size = ['10KG', '50KG']
I have current code where a user inputs their choice of feed, what size and how many bags. It then calculates the price by how many bags:
if ((foodtype) is '1' and (bagsize) is '1'):
print('$',((NumberOfBags)*Pellets[1]))
I am needing to write a if statement for a user to input there total amount of bird feed required and it tells how many bags of 50kg required and then the left over to be calculated into 10kg bags and for it to round up to a 10kg bag if a user inputs 52kgs required.
I expect the code to end up writing how many 50kg bags I need and how many 10kg bags I will require. e.g user says they need 134kg go bird feed the program will say you need 2 50kg bags and 4 10kg bags. Once this is worked out I plan to write how much the output will cost.
An if statement isn't the way to go about this. What you're describing is simple arithmetic.
kgs_required = 52
First do integer division to get the number of full 50kg bags.
n_50kg_bags = kgs_required // 50
This will give you 1x 50kg bag. Next get the modulo (remainder) from that division.
kg_remaining = kgs_required % 50
This will give you the 2kg left over. Now calculate the number of 10s in this number, rounding up with math.ceil
n_10kg_bags = math.ceil(kg_remaining / 10)
Which will give you 1x again. So for 52kg you require 1x 50kg and 1x 10kg bags.
I feel like perhaps there may be a better way to hold all these items, such as a list of dictionaries.
Consider each dictionary a real life object, and all it's contents to be properties (each property has a name and a corresponding value). If I want pellets, I would search for name = pellets and get the price value
For this, I would assume that each object is a product and it has all it's properties listed inside.
list_of_products = [
{ 'name': 'pellets', 'weight': 10, 'price': 22.75},
{ 'name': 'pellets', 'weight': 50, 'price': 100.00},
... more products
]
This way you can query this list and get what is selected, as shown by this article
I use Javascript more than Python, so here is the answer that makes sense to me (not the highest votes):
def search(name, people):
return [element for element in people if element['name'] == name]

Replace two consecutive items in the list with one item

To analyze the text, we transform it into a list P1 of words. Then we apply the Bigram methods and get a list X of couples of words (ai,bi) such that ai and bi occur one after another in P1 quite a lot of times. How to get in Python 3 a list P2 from P1 so that every two items ai and bi if they go one after another in P1 and (ai,bi ) from X would be replaced by one element ai_bi?
My ultimate goal is to prepare the text as a list of words for analysis in Word2Vec.
I have my own code and it works but I think it will be slow on big texts.
import nltk
from nltk.collocations import *
import re
import gensim
bigram_measures = nltk.collocations.BigramAssocMeasures()
sentences=["Total internal reflection ! is the;phenomenon",
"Abrasive flow machining :is an ? ( interior surface finishing process)",
"Technical Data[of Electrical Discharge wire cutting and] Cutting Machine",
"The greenhouse effect. is the process by which, radiation from a {planet atmosphere warms }the planet surface",
"Absolute zero!is the lowest limit ;of the thermodynamic temperature scale:",
"The term greenhouse effect ?is mentioned (a lot)",
"[An interesting] effect known as total internal reflection.",
"effect on impact energies ,Electrical discharge wire cutting of ADI",
"{Absolute zero represents} the coldest possible temperature",
"total internal reflection at an air water interface",
"What is Electrical Discharge wire cutting Machining and how does it work",
"Colder than Absolute Zero",
"A Mathematical Model for Electrical Discharge Wire Cutting Machine Parameters"]
P1=[]
for f in sentences:
f1=gensim.utils.simple_preprocess (f.lower())
P1.extend(f1)
print("First 100 items from P1")
print(P1[:100])
# bigram
finder = BigramCollocationFinder.from_words(P1)
# filter only bigrams that appear 2+ times
finder.apply_freq_filter(2)
# return the all bi-grams with the highest PMI
X=finder.nbest(bigram_measures.pmi, 10000)
print()
print("Number of bigrams= ",len(X))
print("10 first bigrams with the highest PMI")
print(X[:10])
# replace ai and bi which are one after another in P1 and (ai,bi) in X =>> with ai_bi
P2=[]
n=len(P1)
i=0
while i<n:
P2.append(P1[i])
if i<n-2:
for c in X:
if c[0]==P1[i] and c[1]==P1[i+1]:
P2[len(P2)-1]=c[0]+"_"+c[1]
i+=1 # skip second item of couple from X
break
i+=1
print()
print( "first 50 items from P2 - results")
print(P2[:50])
I guess you are looking for something like this.
P2 = []
prev = P1[0]
for this in P1[1:]:
P2.append(prev + "_" + this)
prev = this
This implements a simple sliding window where the previous token is pasted next to the current token.

Categories

Resources