0% found this document useful (0 votes)
3 views

Homework Submission - Python

Uploaded by

hoainguyenm.426
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Homework Submission - Python

Uploaded by

hoainguyenm.426
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Exercise 1:

while True:
s=input("Enter a binary string: ")
d=decimalvalue=0
l=len(s)
for i in range(l):
if s[i]!='1' and s[i]!='0':
print("Error.Please enter a string only containing 0 and 1.")
else:
for i in range(l):
d += int(s[l - 1 - i]) * (2 ** i)
print("The decimal value of the binary string", s, "is: ",d)
break

Exercise 2:
s=input("Enter a list of integers: ")
a=count_positive=0; b=count_negative=0
numbers=[]
for n in s.split():
numbers.append(int(n))
for n in numbers:
if n > 0:
a += 1
elif n < 0:
b += 1
print("Number of positive integers: ",a)
print("Number of negative integers: ",b)
sorted_numbers=sorted(numbers)
i=0
while i<len(sorted_numbers):
count=1
while i+1<len(sorted_numbers) and sorted_numbers[i]==sorted_numbers[i+1]:
count +=1
i+=1
print(count,end=" ")
i+=1

Exercise 3:
s=input("Enter a string: ")
character=s.split()
totalsum=0
numbers=''
for character in s:
if character.isdigit():
numbers += character
else:
if numbers:
totalsum += int(numbers)
numbers=''
print("The sum of the numbers in the string is: ",totalsum)
Exercise 4:
n=int(input("Enter a positive number (1 <= n <= 105): "))
count_4 = 0
count_7 = 0
while n>0:
digit = n%10
if digit==4:
count_4 +=1
elif digit==7:
count_7 +=1
else:
break
if count_4 == count_7 and count_4>0:
print("True. This is a super lucky number")
else:
print("False. This not a super lucky number")

You might also like