edX 6.00x textbook (2012) + ответы


Ответы к книге "edX 6.00x textbook" для упражнений "finger exercises"

---

--

  • стр. 16. Write a program that examines three variables - x, y, and z - and print the largest odd number aming them. If none of them are odd, ith should print message to that effect
---
x = int(raw_input('Enter an integer (x):'))
y = int(raw_input('Enter an integer (y):'))
z = int(raw_input('Enter an integer (z):'))

if x%2 != 0:
    if y%2 != 0:
        if z%2 != 0:
            if x > y and x > z:
                name = 'x'; value = x
            elif y > z:
                name = 'y'; value = y
            else:
                name = 'z'; value = z
        else:
            if x > y:
                name = 'x'; value = x
            else:
                name = 'y'; value = y
    else:
        if z%2 != 0:
            if x > z:
                name = 'x'; value = x
            else:
                name = 'z'; value = z
        else:
            name = 'x'; value = x
else:
    if y%2 != 0:
        if z%2 !=0:
            if y > z:
                name = 'y'; value = y
            else:
                name = 'z'; value = z
        else:
            name = 'y'; value = y
    else:
        if z%2 != 0:
            name = 'z'; value = z
        else:
            name = None; value = None

if name == None:
    print ('No odd numbers!')
else:
    print ('Largest odd is ' + name + ', which value is ' +str(value))







Небольшая блок-схема алгоритма для данного упражнения:
Естественно, в реальных программах все делается намного проще (и с гораздо меньшим количеством кода). Но цель данного упражнения - научить пользоваться многократно вложенными условными операторами (nested if expressions). Конкретно для данной задачи (наибольшее нечетное из трех чисел) код выглядел был приблизительно вот так:

# -*- coding: utf-8 -*-
x = int(raw_input('Enter an integer (x):'))
y = int(raw_input('Enter an integer (y):'))
z = int(raw_input('Enter an integer (z):'))

ints = [i for i in (x, y, z) if i%2 !=0] # немного списочной магии

if ints:
    print ('Max odd number is ' + str(max(ints)))
else:
    print ('No odd numbers!')

  ---

 

  • стр. 20. Write a program that asks the user to input 10 integers, and then prints the largest odd number that was entered. If no odd numbers was entered, it should print a message to that effect.
---
num_inputs = 10

max_odd = None

while num_inputs > 0:
    print ('Integers left to enter:' + str(num_inputs))
    x = int(raw_input('Enter an integer:'))
    if x%2 != 0:
        if max_odd != None:
            if x > max_odd:
                max_odd = x
        else:
            max_odd = x
    num_inputs -= 1

if max_odd == None:
    print ('No odd numbers!')
else:
    print ('Largest odd:' + str(max_odd))

---
  • стр. 23.Write a program that asks the user to enter an integer and prints two integers, root an pwr, such that 0 < pwr < 6 and root^pwr is equal to the integer entered by the user. If no such pair of integers exist, it should print a message to that effect
--- 
x = int(raw_input('Enter an integer: '))

pwr = 5
while pwr > 0:
    root = 0
    while root**pwr < abs(x):
        root = root+1
    if root**pwr == abs(x):
        print ('root=' + str(root) + ', pwr=' + str(pwr))
        break
    pwr -= 1
else:
    print ('No integer roots**powers for ' + str(x))
---

Примечание: В задании требуется найти корень степени pwr, но указано что 0 < pwr < 6. Т.к. это означает, что pwr принимает значения от 1 до 5. При этом корень "1й" степени всегда можно найти - это и есть само число. Таким образом, сообщение "не найдена пара чисел..." не появится никогда.
Возможно, это просто ошибка в задании. 1 < pwr < 6 выглядело бы логичнее.

---

  •  стр.25. Let s be a string that contains a sequence of decimal numbers separated by commas, e.g. s='1.23, 2.4, 3.123'. Write a program that prints the sum of the numbers in s
s = raw_input('Input a string with decimals, separated by comma:')

total = 0
cur = ''
for char in s:
    if char == ',':
        total += float(cur)
        cur = ''
    else:
        cur += char
if cur != '':
    total += float(cur)
print (total)


---

---

Комментариев нет:

Отправить комментарий