Solution to problem on slide 2 :
Essentially start from the end of the list, and add 1 to the digit. If the digit is 10, then carry the 1 to the next digit, else you are done. If you reach the end of the list with a carry, add a 1 to the new digit.
i = 1
while(True):
if i==len(digits)+1:
digits = [1]+digits
break
digits[-i]+=1;
if digits[-i]==10:
digits[-i]=0
i+=1
else:
break
return digits
Solution to problem on slide 3:
Use the fact that all node values are between -1e5 and 1e5 so set each node you visited equal to 1e5 +1, then check if the next node is 1e5 +1, if it is, then you have visited the node before so there exists a cycle.
while head:
if head.val == 100001:
return True
head.val = 100001
head = head.next
return False
Solution to problem on slide 4:
l = [0]*numRows
for i in range(numRows):
l[i] = [1]*(i+1) # initialize with ones
for j in range(1, i//2+1):
l[i][j] = l[i-1][j-1] + l[i-1][j] # sum upper two values
l[i][i-j] = l[i][j] #mirror to the other end of list since the values are symmetrical
return l
Solution to HW problem "Solitare"
cards = input()
split_deck = cards.split(", ")
num_cards = int(split_deck[0])
split_deck.pop(0)
for n in range(0, num_cards-1):
if split_deck[n-1][0] == split_deck[n=1][1]==split_deck[n-2][1]:
split_deck.pop(0)
if len(split_deck)==2:
if split_deck[0][0] == split_deck[1][0] or split_deck[0][1] == split_deck[1][1]:
split_deck.pop(0)
print(split_deck)