The Self-Taught Computer Scientist


Introduction to Algorithms


Download 1.48 Mb.
Pdf ko'rish
bet61/147
Sana17.06.2023
Hajmi1.48 Mb.
#1540634
1   ...   57   58   59   60   61   62   63   64   ...   147
Bog'liq
books-library.net-11301817Az7X6

Introduction to Algorithms
70
Your function 
is_power
takes the number in question. Inside your function, you use an 
if
state-
ment to check if using bitwise AND on 
n
and 
n − 1
is equal to 0. If it is, 
n
is a power of 2, and you 
return 
True
. Otherwise, it is not, and you return 
False
.
FizzBuzz
FizzBuzz is one of the all- time classic interview challenges. I once heard a story about an engineer 
interviewing for a principal software engineer position, and they asked him to solve FizzBuzz. He 
couldn’t, and he was very embarrassed. Don’t worry, though; you are about to learn how to solve it, 
so that won’t happen to you.
Here’s the FizzBuzz challenge: write a program that prints the numbers from 1 to 100. If the number 
is a multiple of 3, print “Fizz.” If the number is a multiple of 5, print “Buzz.” If the number is a mul-
tiple of 3 and 5, print “FizzBuzz.”
The key to this challenge is using the modulo operator, which divides two values and returns the 
remainder. If the remainder is 0, you know the dividend (the number you divided) is a multiple of 
the divisor (the number you divided by). For example, 
6 % 3
divides 6 by 3 and returns a remainder of 0.
print(6 % 3)
>> 0
Because there is no remainder, you know 6 is a multiple of 3.
When you evaluate 7 % 3, there is a remainder, so you know 7 is not a multiple of 3.
print(7 % 3)
>> 1
To solve FizzBuzz, you iterate through the numbers 1 to 100 and use modulo to check whether 
each number is a multiple of 3 and 5, only 3, or only 5.
Here is how you do it:
def fizzbuzz(n):
for i in range(1, n + 1):
if i % 3 == 0 and i % 5 == 0:
print('FizzBuzz')
elif i % 3 == 0:
print('Fizz')
elif i % 5 == 0:
print('Buzz')
else:
print(i)



Download 1.48 Mb.

Do'stlaringiz bilan baham:
1   ...   57   58   59   60   61   62   63   64   ...   147




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling