I have a couple of problems to solve for an assignment, and am a bit stuck.
The question is to write a program that gets the user to input an odd number (check it's odd), then print an upside down pyramid of stars based on the size of the input.
For example, if you enter 5, it comes up with
*****
***
*
My problem is therefore two-fold.
1) How do I check if it's even or odd? I tried if number/2 == int in the hope that it might do something, and the internet tells me to do if number%2==0, but that doesn't work.
2) How do I change the asterisks in the middle of each line?
Any help with either problem is greatly appreciated.
Giving you the complete answer would have no point at all since this is homework, so here are a few pointers :
Even or Odd:
number % 2 == 0
definitely is a very good way to find whether your number is even.
In case you do not know %, this does modulo which is here the remainder of the division of number by 2. http://en.wikipedia.org/wiki/Modulo_operation
Printing the pyramid:
First advice: In order to print *****, you can do print "*" * 5.
Second advice: In order to center the asterisks, you need to find out how many spaces to write before the asterisks. Then you can print a bunch of spaces and asterisks with print " "*1 + "*"*3
The modulo 2 solutions with %2 is good, but that requires a division and a subtraction. Because computers use binary arithmetic, a much more efficient solution is:
# This first solution does not produce a Boolean value.
is_odd_if_zero = value & 1
# or
is_odd = (value & 1) == 1
# or
is_even = (value & 1) == 0
A few of the solutions here reference the time taken for various "is even" operations, specifically n % 2 vs n & 1, without systematically checking how this varies with the size of n, which turns out to be predictive of speed.
The short answer is that if you're using reasonably sized numbers, normally < 1e9, it doesn't make much difference. If you're using larger numbers then you probably want to be using the bitwise operator.
Here's a plot to demonstrate what's going on (with Python 3.7.3, under Linux 5.1.2):
Basically as you hit "arbitrary precision" longs things get progressively slower for modulus, while remaining constant for the bitwise op. Also, note the 10**-7 multiplier on this, i.e. I can do ~30 million (small integer) checks per second.
Here's the same plot for Python 2.7.16:
which shows the optimisation that's gone into newer versions of Python.
I've only got these versions of Python on my machine, but could rerun for other versions of there's interest. There are 51 ns between 1 and 1e100 (evenly spaced on a log scale), for each point I do the equivalent of:
timeit('n % 2', f'n={n}', number=niter)
where niter is calculated to make timeit take ~0.1 seconds, and this is repeated 5 times. The slightly awkward handling of n is to make sure we're not also benchmarking global variable lookup, which is slower than local variables. The mean of these values are used to draw the line, and the individual values are drawn as points.
Simple but yet fast:
>>> def is_odd(a):
... return bool(a - ((a>>1)<<1))
...
>>> print(is_odd(13))
True
>>> print(is_odd(12))
False
>>>
Or even simpler:
>>> def is_odd(a):
... return bool(a & 1)
1) How do I check if it's even or odd? I tried "if number/2 == int" in the hope that it might do something, and the internet tells me to do "if number%2==0", but that doesn't work.
def isEven(number):
return number % 2 == 0
if number%2==0
will tell you that it's even. So odd numbers would be the else statement there. The "%" is the mod sign which returns the remainder after dividing. So essentially we're saying if the number is divisible by two we can safely assume it's even. Otherwise it's odd (it's a perfect correlation!)
As for the asterisk placing you want to prepend the asterisks with the number of spaces correlated to the line it's on. In your example
***** line 0
*** line 1
* line 2
We'll want to space accordingly
0*****
01***
012*
la = lambda x : "even" if not x % 2 else "odd"
I guess the easiest and most basic way is this
import math
number = int (input ('Enter number: '))
if number % 2 == 0 and number != 0:
print ('Even number')
elif number == 0:
print ('Zero is neither even, nor odd.')
else:
print ('Odd number')
Just basic conditions and math. It also minds zero, which is neither even, nor odd and you give any number you want by input so it's very variable.
Regarding the printout, here's how I would do it using the Format Specification Mini Language (section: Aligning the text and specifying a width):
Once you have your length, say length = 11:
rowstring = '{{: ^{length:d}}}'.format(length = length) # center aligned, space-padded format string of length <length>
for i in xrange(length, 0, -2): # iterate from top to bottom with step size 2
print rowstring.format( '*' * i )
there are a lot of ways to check if an int value is odd or even.
I'll show you the two main ways:
number = 5
def best_way(number):
if number%2==0:
print "even"
else:
print "odd"
def binary_way(number):
if str(bin(number))[len(bin(number))-1]=='0':
print "even"
else:
print "odd"
best_way(number)
binary_way(number)
hope it helps
This is simple code. You can try it and grab the knowledge easily.
n = int(input('Enter integer : '))
if n % 2 == 3`8huhubuiiujji`:
print('digit entered is ODD')
elif n % 2 == 0 and 2 < n < 5:
print('EVEN AND in between [2,5]')
elif n % 2 == 0 and 6 < n < 20:
print('EVEN and in between [6,20]')
elif n % 2 == 0 and n > 20:
print('Even and greater than 20')
and so on...
Here's my solution:
def is_even(n):
r=n/2.0
return True if r==int(r) else False
Sample Instruction
Given an integer, n, performing the following conditional actions:
If n is odd, print Weird
If n is even and in the inclusive range of 2 to 5, print Not Weird
If n is even and in the inclusive range of 6 to 20, print Weird
If n is even and greater than 20, print Not Weird
import math
n = int(input())
if n % 2 ==1:
print("Weird")
elif n % 2==0 and n in range(2,6):
print("Not Weird")
elif n % 2 == 0 and n in range(6,21):
print("Weird")
elif n % 2==0 and n>20:
print("Not Weird")
def main():
n = float(input('odd:'))
while n % 2 == 0:
#if n % 2 == 1: No need for these lines as if it were true the while loop would not have been entered.
#break not required as the while condition will break loop
n = float(input('odd:'))
for i in range(int((n+1)/2)):
print(' '*i+'*'*int((n-2*i))+' '*i)
main()
#1st part ensures that it is an odd number that was entered.2nd part does the printing of triangular
Modulus method is the usual method. We can also do this to check if odd or even:
def f(a):
if (a//2)*2 == a:
return 'even'
else:
return 'odd'
Integer division by 2 followed by multiplication by two.
My solution basically we have two string and with the & we get the right index:
res = ["Even", "Odd"]
print(res[x & 1])
Please note that it seems slower than other alternatives:
#!/usr/bin/env python3
import math
import random
from timeit import timeit
res = ["Even", "Odd"]
def foo(x):
return res[x & 1]
def bar(x):
if x & 1:
return "Odd"
return "Even"
la = lambda x : "Even" if not x % 2 else "Odd"
iter = 10000000
time = timeit('bar(random.randint(1, 1000))', "from __main__ import bar, random", number=iter)
print(time)
time = timeit('la(random.randint(1, 1000))', "from __main__ import la, random", number=iter)
print(time)
time = timeit('foo(random.randint(1, 1000))', "from __main__ import foo, random", number=iter)
print(time)
output:
8.05739480999182
8.170479692984372
8.892275177990086
1. another odd testing function
Ok, the assignment was handed in 8+ years ago, but here is another solution based on bit shifting operations:
def isodd(i):
return(bool(i>>0&1))
testing gives:
>>> isodd(2)
False
>>> isodd(3)
True
>>> isodd(4)
False
2. Nearest Odd number alternative approach
However, instead of a code that says "give me this precise input (an integer odd number) or otherwise I won't do anything" I also like robust codes that say, "give me a number, any number, and I'll give you the nearest pyramid to that number".
In that case this function is helpful, and gives you the nearest odd (e.g. any number f such that 6<=f<8 is set to 7 and so on.)
def nearodd(f):
return int(f/2)*2+1
Example output:
nearodd(4.9)
5
nearodd(7.2)
7
nearodd(8)
9
This the function
def oddOrEven(num):
if num%2 == 0:
print("even")
else:
for i in range(num):
for j in range(i+1):
print(" ", end="")
for m in range(num-i, 0, -1):
print("* ", end="")
print()
but there is a catch because it is almost impossible to return a pattern so we have to print instead of return it then use it directly oddOrEven(5) will print:
* * * * *
* * * *
* * *
* *
*
Determining even/odd:
is_odd = num & 1
is_even = (num & 1) == 0 # slowly: bitwise and number comparison
is_even = (num & 1) is 0 # faster: bitwise and pointer comparsion
is_even = ~num & 1 # fastest: two bitwise operations
Using is is faster than the comparisons with double equals, but negation with ~ is even faster.
Related
I wrote this code and it's alright with positive numbers, but when I tried negative numbers it crashes. Can you give any hints on how to make it work with negative numbers as well? It needs to be recursive, not iterative, and to calculate the sum of the digits of an integer.
def sum_digits(n):
if n != 0:
return (n % 10 + sum_digits(n // 10))
else:
return 0
if __name__=='__main__':
print(sum_digits(123))
Input: 123
Output: 6
On the assumption that the 'sum' of the three digits of a negative number is the same as that of the absolute value of that number, this will work:
def sum_digits(n):
if n < 0:
return sum_digits(-n)
elif n != 0:
return (n % 10 + sum_digits(n // 10))
else:
return 0
That said, your actual problem here is that Python's handling of modulo for a negative number is different than you expect:
>>> -123 % 10
7
Why is that? It's because of the use of trunc() in the division. This page has a good explanation, but the short answer is that when you divide -123 by 10, in order to figure out the remainder, Python truncates in a different direction than you'd expect. (For good, if obscure, reasons.) Thus, in the above, instead of getting the expected 3 you get 7 (which is 10, your modulus, minus 3, the leftover).
Similarly, it's handling of integer division is different:
>>> -123 // 10
-13
>>> 123 // 10
12
This is un-intuitively correct because it is rounding 'down' rather than 'towards zero'. So a -12.3 rounds 'down' to -13.
These reasons are why the easiest solution to your particular problem is to simply take the absolute value prior to doing your actual calculation.
Separate your function into two functions: one, a recursive function that must always be called with a non-negative number, and two, a function that checks its argument can calls the recursive function with an appropriate argument.
def sum_digits(n):
return _recursive_sum_digits(abs(n))
def _recursive_sum_digits(n):
if n != 0:
return (n % 10 + sum_digits(n // 10))
else:
return 0
Since _recursive_sum_digits can assume its argument is non-negative, you can dispense with checking its sign on every recursive call, and guarantee that n // 10 will eventually produce 0.
If you want to just sum the digits that come after the negative sign, remove the sign by taking the absolute value of the number. If you're considering the first digit of the negative number to be a negative digit, then manually add that number in after performing this function on the rest of the digits.
Here is your hint. This is happening because the modulo operator always yields a result with the same sign as its second operand (or zero). Look at these examples:
>>> 13 % 10
3
>>> -13 % 10
7
In your specific case, a solution is to first get the absolute value of the number, and then you can go on with you approach:
def sum_digits(n):
n = abs(n)
if n != 0:
return (n % 10 + sum_digits(n // 10))
else:
return 0
def Something(number):
if number % 2 == 0:
return (number // 2)
elif number % 2 > 0:
return (3 * number + 1)
Something(12)
I did it with and without parenthesis
As others have mentioned, your function is returning a value and if you run this directly in your terminal you will see the result displayed in standard out.
Note that the integers modulo 2 is {0,1}. Also, idiomatic python uses snake_case.
Furthermore, you can take advantage of the truthy/falsey nature of this set.
I've rewritten your example to show you what I mean:
def number_mod2(number):
#if odd
if number%2:
return 3*number+1
#if not odd (all other cases)
return number // 2
#outputs `6`
print(number_mod2(12))
It likely is returning a number but you need to put the function in a print to have it outputted.
def Something(number):
if number % 2 == 0:
return (number // 2)
elif number % 2 > 0:
return (3 * number + 1)
print(Something(12))
Hope this helps.
There is no problem with the code and the output return a number (6)
I have put together the following code in order to determine if a number has an odd or even number of divisors. The code works well with relatively small numbers but once a larger number like 9 digits is entered it hangs up.
def divisors(n):
num = len(set([x for x in range(1,n+1) if not divmod(n,x)[1]]))
if (num != 0 and num % 2 == 0):
return 'even'
else:
return 'odd'
what can I do to make this more efficient?
Here's your problem:
num = len(set([x for x in range(1,n+1) if not divmod(n,x)[1]]))
This constructs a list, then constructs a set out of that list, then takes the length of the set. You don't need to do any of that work (range(), or xrange() for that matter, does not produce repeated objects, so we don't need the set, and sum() works on any iterable object, so you don't need the list either). While we're on the subject, divmod(n, x)[1] is just a very elaborate way of writing n % x, and consumes a little bit of extra memory to construct a tuple (which is immediately reclaimed because you throw the tuple away). Here's the fixed version:
num = sum(1 for x in xrange(1,n+1) if not n % x)
You do not need to test every possible divisor, testing up to sqrt(n) is enough. This will make your function O(sqrt(n)) instead of O(n).
import math
def num_divisors(n):
sqrt = math.sqrt(n)
upper = int(sqrt)
num = sum(1 for x in range(1, upper + 1) if not n % x)
num *= 2
if upper == sqrt and num != 0:
num -= 1
return num
In my benchmarks using python2 this is 1000 times faster than sum(1 for x in range(1, n + 1) if not n % x) with n = int(1e6) and 10000 times faster for 1e8. For 1e9 the latter code gave me a memory error, suggesting that the whole sequence is stored in memory before doing the sum because in python 2 range() returns a list and I should be using xrange() instead. For python3 range() is fine.
So, I read the pseudocode from http://www.javascripter.net/math/primes/miller_rabin_pseudocode.txt, and thought it would be cool to write it in python. So I wrote this:
n = input('Enter a number to test ')
n = int(n)
a=int(5)
d = n - 1
s = 0
while (d % 2 == 0):
s = s + 1
d = int(d/2)
x = a**d
x = x % n
if (x==1 or x==(n-1)):
print("probably prime")
r = int(1)
while(r<(s-1)):
x = x**2
x = x%n
if (x==1):
print ("composite")
if (x==(n-1)):
print ("probably prime")
print("if nothing above is printed n is composite")
It worked pretty well, but as soon as I got into six digit numbers it was incredibly slow. So I found some code of http://rosettacode.org/wiki/Miller-Rabin_primality_test#Python, and it was almost instant, even with large (10^30) numbers.
So, what did I do wrong int the above code that made it so much slower?
You should also replace:
x = a**d
x = x % n
With:
x = pow(a, d, n)
Which does modular exponentiation much faster than the naive method, as it takes modulus at each multiply, rather than building a ginormous number and taking modulus after.
The second loop in the linked code does only 5 iterations at maximum, whereas your does something like log(n).
EDIT:
Or even more - the "r" variable is never modified, so the loop's exit condition will never be satisfied. The only possibility to exit the loop are the breaks.
This is a rather difficult challenge for me as I am new to Python. How would I write a program in python based off this sequence function:
http://oeis.org/A063655
and does the following:
It asks for the value of the sequence and returns the corresponding number. For example, the number corresponding to the 10th value of the sequence is 7. I'd like to be able to do this for values over 300,000,000.
So, the final product would look like this:
Enter a value: 4
[7]
Any ideas where to start? I have a framework to generate sequences where (x) would be to put a mathematical equation or numbers, but I'm not exactly sure how to go from here or how to implement the "Enter a value" portion:
import math
def my_deltas():
while True:
yield (x)
yield (x)
def numbers(start, deltas, max):
i=start
while i<=max:
yield i
i+=next(deltas)
print(','.join(str(i) for i in numbers((x), my_deltas(),(x))))
If you're looking to have your computer keep track of over 300,000,000 elements of a sequence, if each is a 4 byte integer, you'll need at least 300,000,000 * 4bytes, or over 1.1GB of space to store all the values. I assume generating the sequence would also take a really long time, so generating the whole sequence again each time the user wants a value is not quite optimal either. I am a little confused about how you are trying to approach this exactly.
To get a value from the user is simple: you can use val = input("What is your value? ") where val is the variable you store it in.
EDIT:
It seems like a quick and simple approach would be this way, with a reasonable number of steps for each value (unless the value is prime...but lets keep the concept simple for now): You'd need the integer less than or equal to the square root of n (start_int = n ** .5), and from there you test each integer below to see if it divides n, first converting start_int to an integer with start_int = int(start_int) (which gives you the floor of start_int), like so: while (n % start_int) != 0: start_int = start_int - 1, decrement by one, and then set b = start_int. Something similar to find d, but you'll have to figure that part out. Note that % is the modulus operator (if you don't know what that is, you can read up on it, google: 'modulus python'), and ** is exponentiation. You can then return a value with the return statement. Your function would look something like this (lines starting with # are comments and python skips over them):
def find_number(value):
#using value instead of n
start_int = value ** .5
start_int = int(start_int)
while (n % start_int) != 0:
#same thing as start_int = start_int - 1
start_int -= 1
b = start_int
#...more code here
semiperimeter = b + d
return semiperimeter
#Let's use this function now!
#store
my_val = input("Enter a value: ")
my_number = find_number(my_val)
print my_number
There are many introductory guides to Python, and I would suggest you go through one first before tackling implementing a problem like this. If you already know how to program in another language you can just skim a guide to Python's syntax.
Don't forget to choose this answer if it helped!
from math import sqrt, floor
def A063655(n):
for i in range(floor(sqrt(n)), 0, -1):
j = floor(n / i)
if i * j == n:
return i + j
if __name__ == '__main__':
my_value = int(input("Enter a value: "))
my_number = A063655(my_value)
print(my_number)
USAGE
> python3 test.py
Enter a value: 10
7
> python3 test.py
Enter a value: 350000
1185
>