jweinst1
10/28/2016 - 10:40 PM

practice problem answers

practice problem answers

#Generator practice with classes

class Link:
	
	def __init__(self, first, next=None):
		self.first = first
		self.next = next
		
	def __repr__(self):
		return "({0}, {1})".format(self.first, self.next)
		
		
#Question 1
#Define a generator that on each next() call, returns a linked list of 
#numbers from 0 to infinity, making the chain one link longer each time
"""
   f = lazy_numbers()
=> None
   next(f)
=> (0, None)
   next(f)
=> (0, (1, None))
   next(f)
=> (0, (1, (2, None)))
   next(f)
=> (0, (1, (2, (3, None))))
   next(f)
=> (0, (1, (2, (3, (4, None)))))
   next(f)
=> (0, (1, (2, (3, (4, (5, None))))))
   next(f)
=> (0, (1, (2, (3, (4, (5, (6, None)))))))
"""
def lazy_numbers():
	chain = Link(0)
	seq = chain
	while True:
		yield chain
		seq.next = Link(seq.first + 1)
		seq = seq.next
		
		
#Question 2
#define a generator that yields the sequence of strings of integers from 1 to infinity, with each next() call returning the next string.
#You cannot use integers for this problem. You must construct integers with strings
#Hint the .join method of an empty string joins an array of strings together
# "".join(["a", "b"]) => "ab"
"""
   f = intseq()
=> None
   next(f)
=> '1'
   next(f)
=> '2'
   next(f)
=> '3'
   next(f)
=> '4'
   next(f)
=> '5'
   next(f)
=> '6'
   next(f)
=> '7'
   next(f)
=> '8'
   next(f)
=> '9'
   next(f)
=> '10'
"""
def intseq():
	nextdict = {
		"0":"1",
		"1":"2",
		"2":"3",
		"3":"4",
		"4":"5",
		"5":"6",
		"6":"7",
		"7":"8",
		"8":"9",
		"9":"0"
	}
	number = ["0"]
	while True:
		incmode = True
		for i in reversed(range(len(number))):
			if incmode:
				if i == 0:
					result = nextdict[number[i]]
					number[i] = result
					if result == "0":
						number = ["1"] + number
						incmode = False
				else:
					result = nextdict[number[i]]
					number[i] = result
					#determins if a carry is needed, such as 89 to 90
					if result != "0":
						incmode = False
		yield "".join(number)
						

"""String Drawing Practice"""

#Question 3
#Define a generator that draws a zigzag line, of some width w. it will generate an infinite number of moving lines
#to mark the line use a star *
#HINT:use the join method here 
def zigzag(w):
	slash_ind = 0 
	line = ["*"] + [" " for i in range(w-1)]
	forward = True
	while True:
		yield "".join(line)
		if forward:
			if slash_ind == 9:
				forward = False
				line[slash_ind], line[slash_ind-1] = line[slash_ind-1], line[slash_ind]
				slash_ind -= 1
			else:
				line[slash_ind], line[slash_ind+1] = line[slash_ind+1], line[slash_ind]
				slash_ind += 1
		else:
			if slash_ind == 0:
				forward = True
				line[slash_ind], line[slash_ind+1] = line[slash_ind+1], line[slash_ind]
				slash_ind += 1 
			else:
				line[slash_ind], line[slash_ind-1] = line[slash_ind-1], line[slash_ind]
				slash_ind -= 1