Collatz sequence comma code character graph grid instance

  • 2020-06-03 07:19:07
  • OfStack

1. collatz sequence

Write a function called collatz() that takes a parameter called number. If the argument is even, collatz() prints out number // 2 and returns the value. If number is odd, collatz() prints and returns 3 * number + 1. Then write a program that asks the user to enter an integer and calls collatz() repeatedly on that number until the function returns the value 1.


#!/usr/bin/env python3
# -*- coding:utf-8 -*-

def collatz(number):
 print(number)
 if number ==1:
  return number
 elif number % 2 ==0:
  return collatz(number//2)
 else:
  return collatz(3*number +1)

A = int(input('Input a number: '))
while True:
 if collatz(A) != 1:
  continue
 else:
  break

Output results:


Input a number: 6
6
3
10
5
16
8
4
2
1

Comma code

Suppose you have the following list: spam = ['apples', 'bananas', 'tofu', 'cats']

Write a function that takes a list value as an argument and returns a string. The string contains all the table entries, separated by commas and Spaces, and inserts and before the last one. For example, passing the previous spam list to the function returns 'apples, bananas, tofu, and cats'. But your function should be able to handle any list passed to it.


#!/usr/bin/env python3
# -*- coding:utf-8 -*-

def func(spam):
 spam[-1]='and'+ ' ' + spam[-1]
 for i in range(len(spam)):
  print(spam[i], end=',')


spam = ['apple', 'bananas', 'tofu', 'cats', 'dog']
func(spam)
# The output 
apple,bananas,tofu,cats,and dog,

3. Character graph grid

Suppose there is a list of lists, and each value of the inner list is a 1-character string, like this:

grid =[['.', '.', '.', '.', '.', '.'],

['.', 'O', 'O', '.', '.', '.'],

['O', 'O', 'O', 'O', '.', '.'],

['O', 'O', 'O', 'O', 'O', '.'],

['.', 'O', 'O', 'O', 'O', 'O'],

['O', 'O', 'O', 'O', 'O', '.'],

['O', 'O', 'O', 'O', '.', '.'],

['.', 'O', 'O', '.', '.', '.'],

['.', '.', '.', '.', '.', '.']]

You can think of grid[x][y] as the character of a graph at the x and y coordinates. The graph consists of text characters. The origin (0, 0) in the upper left corner increases to the right x and increases to the lower y. Copy the previous grid value and write code to print out the image.

..OO.OO..

.OOOOOOO.

.OOOOOOO.

..OOOOO..

...OOO...

....O....


#!/usr/bin/env python3
# -*- coding:utf-8 -*-

grid = [
 ['.', '.', '.', '.', '.', '.'],
 ['.', 'O', 'O', '.', '.', '.'],
 ['O', 'O', 'O', 'O', '.', '.'],
 ['O', 'O', 'O', 'O', 'O', '.'],
 ['.', 'O', 'O', 'O', 'O', 'O'],
 ['O', 'O', 'O', 'O', 'O', '.'],
 ['O', 'O', 'O', 'O', '.', '.'],
 ['.', 'O', 'O', '.', '.', '.'],
 ['.', '.', '.', '.', '.', '.']]
# Nested loop 
for n in range(len(grid[0])):
 for m in range(len(grid)):
  print(grid[m][n], end='')
 print('\n')# A newline 

# The output 
..OO.OO..

.OOOOOOO.

.OOOOOOO.

..OOOOO..

...OOO...

....O....

Related articles: