06-10 loops and Lists

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

Given the string, s, and the list, lst, assign True to the variable contains if every string in lst appears in s (and False otherwise). Thus, given the string "Hello world" and the list ["H", "wor", "o w"], contains would be assigned True.

for e in lst: [Tab Key]if e in s: [Tab Key][Tab Key]contains = True [Tab Key][Tab Key]break [Tab Key]contains = False

In the following sequence, each number (except the first two) is the sum of the previous two numbers: 0, 1, 1, 2, 3, 5, 8, 13, .... This sequence is known as the Fibonacci sequence. We speak of the i'th element of the sequence (starting at 0)-- thus the 0th element is 0, the 1st element is 1, the 2nd element is 1, the 3rd element is 2 and so on. Given the positive integer n, assign the nth value of the fibonacci sequence to the variable result. For example, if n contains the value 8 then result would contain 21.

if n <= 1: [Tab Key]result = n else: [Tab Key]count = 2 [Tab Key]i = 1 [Tab Key]lastI = 0 [Tab Key]while count <= n: [Tab Key][Tab Key]lastI, i = i, lastI + i [Tab Key][Tab Key]count += 1 [Tab Key]result = i

Given the list lst of positive integers, assign the largest duplicated element to the variable max_dup. If the list contains no duplicates, assign -1 to max_dup.

max_dup = -1 for i in range(len(lst)): [Tab Key]if lst[i] in lst[i+1:] and max_dup < lst[i]: [Tab Key][Tab Key]max_dup = lst[i]

A triangular number is a number that is the sum of the integers from 1 to some integer n. Thus 1 is a triangular number because it is the sum of the integers from 1 to 1; 6 is a triangular number because 1+2+3=6. Given the non-negative integer n, create a list of the first n triangular numbers. Thus if n was 5, the list would be: [1, 3, 6, 10, 15]. Assign the list to the variable triangulars.

triangular = [] t = 0 for i in range(1, n+1): [Tab Key]t += i [Tab Key]triangulars.append(t)

A triangular number is a number that is the sum of the integers from 1 to some integer n. Thus 1 is a triangular number because it is the sum of the integers from 1 to 1; 6 is a triangular number because 1+2+3=6. Given the non-negative integers m and n (with m < n), create a list of the triangular numbers between (and including) m and n. Thus if m is 3 and n is 20, the list would be: [3, 6, 10, 15]. Assign the list to the variable triangulars.

triangulars = [] t = 0 i = 1 while t+i <= n: [Tab Key]t += i [Tab Key]if t >= m: triangulars.append(t) [Tab Key]i += 1


संबंधित स्टडी सेट्स

session 6 - financial management

View Set

Question & Answer page 15 (Headway Plus Beginner) Special Edition, 2nd Edition

View Set

Equilibrium and Acids and Bases Part 2

View Set

ICND1 Test #2: LAN Switching Fundamentals

View Set

CHLD-3304.783 Experimental Psychology

View Set