CS50P Problem Set 2 Solution

CS50’s Introduction to Programming with Python week 2 solution is given below.

Camel Case

def main():
camel = input("Enter camelCase: ")
convert(camel)

def convert(str):
words=[]
current_word = ""
for char in str:
if char.islower():
current_word += char
else:
if current_word:
words.append(current_word)
current_word = char.lower()
if current_word:
words.append(current_word)
with_underscore = '_'.join(words)
print(with_underscore)

if __name__ == "__main__":
main()

Coke Machine

def main():
unit = 50
while True:
coin = int(input("Insert Coin: "))
if coin == 5 or coin == 10 or coin == 25:
unit -= coin
if unit <=0:
print(f"Change Owed: {abs(unit)}")
break
else:
print(f"Amount Due: {unit}")
else:
print(f"Amount Due: {unit}")
print("Please insert 5, 10 or 25 cents coin")

if __name__ == "__main__":
main()

Just setting up my twttr

def main():

text = input("Enter Text: ")
twttr(text)

def twttr(str):
cons = ''
owel = ['a','e','i','o','u','A','E','I','O','U']
for char in str:
if char in owel:
continue
else:
cons += char
print(''.join(cons))

if __name__=='__main__':
main()

Vanity Plates

def main():

plate = input("Enter Plate: ")
if is_valid(plate):
print("Valid")
else:
print("Invalid")

def is_valid(s):
if len(s)<2 or len(s)>6:
return False
if s[0:2].isalpha()==False:
return False
i=0
while i<len(s):
if s[i].isalpha() == False:
if s[i] == '0':
if len(s[i:])>1:
return False
i +=1

for char in s:
if char in ['',',','.']:
return False

else:
return True

if __name__ == "__main__":
main()

Nutrition Facts

def main():

fruit = input("Item: ").lower()
check_calories(fruit)

def check_calories(f):
fruits = {
'apple' : '130',
'avocado' : '50',
'banana' : '110',
'cantaloupe' : '50',
'grapefruit' : '60',
'grapes' : '90',
'honeydew melo' : '50',
'kiwifruit' : '90',
'lemon' : '15',
'lime' : '20',
'nectarine' : '60',
'orange' : '80',
'peach' : '60',
'pear' : '100',
'pineapple' : '50',
'plums' : '70',
'strawberries' : '50',
'sweet cherries' : '100',
'tangerine' : '50',
'watermelon' : '80',
}

for fruit in fruits:
if fruit == f:
print(f"Calories: {fruits[fruit]}")

if __name__ == "__main__":
main()

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.