Skip to content

Instantly share code, notes, and snippets.

@Bundi-py
Last active December 13, 2019 12:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Bundi-py/a2b8b2c3ca885454aec0d2b4be09b5d5 to your computer and use it in GitHub Desktop.
Save Bundi-py/a2b8b2c3ca885454aec0d2b4be09b5d5 to your computer and use it in GitHub Desktop.
Zadatak broj 2: Funkcija "Collatzov niz" radi tako što za neki zadati broj, ako je paran, računa broj // 2 vrednost. Ako je uneti broj neparan, tada collatz() izračunava 3 * broj + 1 vrednost. Koristeći ovaj metod, uvek stižemo do 1
# Zadatak broj 2: Collatzov niz
nekiBroj = int(input('Unesi neki broj: '))
def collatz(nekiBroj):
if nekiBroj % 2 == 0:
print(nekiBroj // 2)
return nekiBroj // 2
else:
nekiBroj % 2 == 1
rezultat = nekiBroj * 3 + 1
print(rezultat)
return rezultat
while nekiBroj != 1:
nekiBroj = collatz(nekiBroj)
===============================
Panta:
from typing import Iterator
def collatz(number: int) -> Iterator[int]:
while number != 1:
number = number // 2 if number % 2 == 0 else number * 3 + 1
yield number
try:
user_input = int(input('Enter some number: '))
for num in collatz(user_input):
print(num)
except ValueError as err:
print(f'Value must be an integer.\n{err}')
==============================
Đoka:
def colatz(n):
lista = [n]
try:
if (n != int(n) or n<1):
raise ValueError
except ValueError:
lista.append("Error: positive integer expected")
return lista
while (n>1):
if(n%2==0):
n=int(n/2)
else:
n=int(3*n+1)
lista.append(n)
return lista
print(colatz(1))
print(colatz(2))
print(colatz(10))
print(colatz(1.5))
print(colatz("a"))
print(colatz(-1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment