1) Repeat the magician's exercise from last week, but this time asking
for user input. Write a script that asks a user for a number. The
script adds 3 to that number. Then multiplies the result by 2,
subtracts 4, subtracts twice the original number, adds 3, then
prints the result.
number = input ("Please, type in a number: ")
newresult = ((number + 3) * 2) - 4
finalresult = newresult - (2 * number) + 3
print "The result is", finalresult
-----------------------------
2) Write a script that evaluates whether two sets are equal, subset of
each other or disjoint. The script outputs a sentence: "The two
sets are ..." stating whether they are equal, subset or
disjoint. In order to test the script use the sets odd and even or
students and programmers from the examples above.
from sets import Set
set1 = Set([1,3,5])
set2 = Set([2,4,6])
if set1 == set2:
print "The sets are equal."
elif set1.issubset(set2):
print "The set", set1, "is subset of", set2
elif set2.issubset(set1):
print "The set", set2, "is subset of", set1
elif set1 & set2 == Set([]):
print "The sets are disjoint."
-----------------------------
3) Change the code so that it prints prime numbers.
has_no_factor = True
for number in range(1,11):
for factor in range(2,number):
if number % factor == 0: ### the remainder is 0
has_no_factor = False
if has_no_factor == True:
print number
has_no_factor = True
-----------------------------
4) Find a number n so that n**2 + n + 41 is not a prime number.
from sympy import isprime, Symbol
n = Symbol('n')
for x in range(35,45):
result = (n**2 + n + 41).subs(n,x)
if not isprime(result):
print result
-----------------------------
5) Write a script that calculates the Fibonacci numbers below 100.
fib1 = 0
fib2 = 1
print fib1,
while fib2 < 100:
print fib2,
temporary = fib1 + fib2
fib1 = fib2
fib2 = temporary
-----------------------------
6) Write a script that computes all two element subsets of a set.
from sets import Set
numbers = Set([1,2,3,4])
numberscopy = numbers.copy()
for number1 in numbers:
for number2 in numberscopy:
if number1 != number2:
set = Set([number1, number2])
print set
numberscopy.discard(number1)