In: Computer Science
Python Practice Sample:
Generate lists containing the numbers between 1 and 50 as follows:
same is a list of all the two-digit numbers whose digits are the same (11, 22, etc.)
addsto6 is a list of all numbers the sum of whose digits is 6
rest contains the rest of the numbers.
A number can appear only in one of the lists; with same having higher priority. (So for example, 33 would appear in the same, but NOT the addsto6 list).
Same = [11, 22, 33, 44]
AddsTo6 = [6, 15, 24, 42]
Rest = [1, 2, 3, 4, 5, 7, 8, 9, 10, 12, 13, 14, 16, 17, 18, 19, 20, 21, 23, 25, 26, 27, 28, 29, 30, 31, 32, 34, 35, 36, 37, 38, 39, 40, 41, 43, 45, 46, 47, 48, 49, 50]
Code and outptut
Code for copying
Same=[]
AddsTo6=[]
Rest=[]
for i in range(10,51):
j=str(i)
if j[0]==j[1]:
Same.append(i)
for i in range(1,51):
total=0
j=str(i)
if i<10:
for n in j:
total+=int(n)
if i>=10:
if j[0]!=j[1]:
for n in j:
total+=int(n)
if total==6:
AddsTo6.append(i)
for i in range(1,51):
if i not in (Same + AddsTo6):
Rest.append(i)
print("Same={}".format(Same))
print("AddsTo6={}".format(AddsTo6))
print("Rest={}".format(Rest))
Code snippet
Same=[]
AddsTo6=[]
Rest=[]
for i in range(10,51):
j=str(i)
if j[0]==j[1]:
Same.append(i)
for i in range(1,51):
total=0
j=str(i)
if i<10:
for n in j:
total+=int(n)
if i>=10:
if j[0]!=j[1]:
for n in j:
total+=int(n)
if total==6:
AddsTo6.append(i)
for i in range(1,51):
if i not in (Same + AddsTo6):
Rest.append(i)
print("Same={}".format(Same))
print("AddsTo6={}".format(AddsTo6))
print("Rest={}".format(Rest))