Python function for sums of integers - python

Wrote a python program that added up numbers from 1 to a given number using the Gauss equation. It worked for 100 and 10 but when I do 3 it says the sum is 4 instead of 6. The equation works out in my head, did I mess up the code?
def numberSum(num):
nim = int(num)
num = (nim/2)*(nim+1)
return num
print numberSum(raw_input())

from __future__ import division
def number_sum(num):
"""
Return sum of 1 .. num
"""
return num * (num + 1) // 2
num = int(raw_input(": "))
print(number_sum(num))
Things I changed:
number_sum should not be responsible for type-casting input; if it expects a number, you should give it some kind of number, not a string.
if num is an int, then either num or num + 1 is even, ie dividing num * (num + 1) by 2 will result in an int. This is not necessarily true of num; therefore you should divide the product by 2, not num, if you want an integer result.
in Python 2.6+, from __future__ import division makes / always return a float result and // always return an int result, consistent with Python 3.x

I suppose you are working with python2, cause by default it applies integer division like other languages. Besides, you can notice this feature in this post Integer division in python 2 and python 3.
To solve your problem you can follow the next approach:
def numberSum(num):
nim = int(num)
return ((nim * 1.0) / 2) * (nim + 1)
print numberSum(raw_input())

Related

Display the middle elements of a string

Recently i tried learning to program and after finishing my first tutorial I am trying tackling some problems from codewars.com.
"You are going to be given a word. Your job is to return the middle character of the word. If the word's length is odd, return the middle character. If the word's length is even, return the middle 2 characters."
Here is my solution:
def get_middle(n):
if len(n) % 2 == 0:
return n[(len(n)/2) - 1] and n[(len(n)/2)]
else:
return n[(len(n)/2) + 0.5]
Unfortunately when executing the function with for example "abc" I always get:
Traceback (most recent call last) <ipython-input-24-46429b2608e5> in <module>
----> 1 print(get_middle("abc"))
<ipython-input-23-56ccbf5e17f7> in get_middle(n)
3 return n[(len(n)/2) - 1] and n[(len(n)/2)]
4 else:
----> 5 return n[(len(n)/2) + 1]
TypeError: string indices must be integers
I don't understand why I always get the this kind of error. Aren't all my string indices integers?
I know there are are a lot of different solutions out there, but I really would like to know why mine isn't working the way I intended it to.
Thanks in advance!
In Python, there are two kinds of division: integer division and float division.
print(4 / 2)
---> 2.0
print(4 // 2)
---> 2
in Python 2, dividing one integer to an another integer,it comes an integer.
Since Python doesn't declare data types in advance, The interpreter automatically detects the type so you never know when you want to use integers and when you want to use a float.
Since floats lose precision, it's not advised to use them in integral calculations
To solve this problem, future Python modules included a new type of division called integer division given by the operator //
Now, / performs - float division, and
// performs - integer division.
def get_middle(n):
if len(n) % 2 == 0:
return n[(len(n)//2) - 1] and n[(int(len(n)/2))]
else:
return n[int(len(n)/2+ 0.5)]
The issue with our code is that division casts integer to float type automatically and Python starts complaining about it. Simple solution would be to add second / symbol to division or in else case cast it to integer:
def get_middle(n):
if len(n) % 2 == 0:
return n[(len(n)//2) - 1] and n[(len(n)//2)]
else:
return n[int((len(n)/2) + 0.5)]
Try math.floor:
import math
def get_middle(value):
length = len(value)
if length % 2 == 0:
# even length, pick the middle 2 characters
start = length // 2 - 1
end = length // 2 + 1
else:
# odd length, pick the middle character
start = math.floor(length // 2)
end = start + 1
return value[start:end]
A suggestion if you are learning programming, try to break down your steps rather than doing it all in one line, it helps a lot when trying to understand the error messages.
If you divide an odd integer by 2 with the /operator, you get a float. This float should be explicitly converted to an integer when it is used as an indice.

Converting a base 10 number to any base without strings

I'm trying to make a function that takes in a number in base 10 and can be changed to any base from 2 though 9. I'm trying to only use the math module and just some simple math.
My code involves strings and I would like to eliminate them, and instead have the function do some math instead of using the numbers in a string. Also I'm trying to make the output integers.
def conver(n,b):
digits = ('0123456789')
ans = ""
while n > 0:
ans = digits[n%b] + ans
n //= b
return ans
For example the user could in put in the values (14,2) and get the output 1110
a simple implementation which can "convert" up to base 9 is as follows:
def conver(n,b):
a = 0
i = 0
while n:
n,r = divmod(n,b)
a += 10**i * r
i += 1
return a
note that n,r = divmod(n,b) could be r = n % b; n //= b
Note that the number you're getting is an integer all right (as a type), but it makes no sense using it as such because the base is wrong: Ex: 1110 is not really 1110. So it's not really different than a string...
Well, that's just for the sake of the exercise.

Finding if n! + 1 is a perfect square

I'm trying to write a program to look for a number, n, between 0 and 100 such that n! + 1 is a perfect square. I'm trying to do this because I know there are only three so it was meant as a test of my Python ability.
Refer to Brocard's problem.
math.sqrt always returns a float, even if that float happens to be, say, 4.0. As the docs say, "Except when explicitly noted otherwise, all return values are floats."
So, your test for type(math.sqrt(x)) == int will never be true.
You could try to work around that by checking whether the float represents an integer, like this:
sx = math.sqrt(x)
if round(sx) == sx:
There's even a built-in method that does this as well as possible:
if sx.is_integer():
But keep in mind that float values are not a perfect representation of real numbers, and there are always rounding issues. For example, for a too-large number, the sqrt might round to an integer, even though it really wasn't a perfect square. For example, if math.sqrt(10000000000**2 + 1).is_integer() is True, even though obviously the number is not a perfect square.
I could tell you whether this is safe within your range of values, but can you convince yourself? If not, you shouldn't just assume that it is.
So, is there a way we can check that isn't affected by float roading issues? Sure, we can use integer arithmetic to check:
sx = int(round(math.sqrt(x)))
if sx*sx == x:
But, as Stefan Pochmann points out, even if this check is safe, does that mean the whole algorithm is? No; sqrt itself could have already been rounded to the point where you've lost integer precision.
So, you need an exact sqrt. You could do this by using decimal.Decimal with a huge configured precision. This will take a bit of work, and a lot of memory, but it's doable. Like this:
decimal.getcontext().prec = ENOUGH_DIGITS
sx = decimal.Decimal(x).sqrt()
But how many digits is ENOUGH_DIGITS? Well, how many digits do you need to represent 100!+1 exactly?
So:
decimal.getcontext().prec = 156
while n <= 100:
x = math.factorial(n) + 1
sx = decimal.Decimal(x).sqrt()
if int(sx) ** 2 == x:
print(sx)
n = n + 1
If you think about it, there's a way to reduce the needed precision to 79 digits, but I'll leave that as an exercise for the reader.
The way you're presumably supposed to solve this is by using purely integer math. For example, you can find out whether an integer is a square in logarithmic time just by using Newton's method until your approximation error is small enough to just check the two bordering integers.
For very large numbers it's better to avoid using floating point square roots altogether because you will run into too many precision issues and you can't even guarantee that you will be within 1 integer value of the correct answer. Fortunately Python natively supports integers of arbitrary size, so you can write an integer square root checking function, like this:
def isSquare(x):
if x == 1:
return True
low = 0
high = x // 2
root = high
while root * root != x:
root = (low + high) // 2
if low + 1 >= high:
return False
if root * root > x:
high = root
else:
low = root
return True
Then you can run through the integers from 0 to 100 like this:
n = 0
while n <= 100:
x = math.factorial(n) + 1
if isSquare(x):
print n
n = n + 1
Here's another version working only with integers, computing the square root by adding decreasing powers of 2, for example intsqrt(24680) will be computed as 128+16+8+4+1.
def intsqrt(n):
pow2 = 1
while pow2 < n:
pow2 *= 2
sqrt = 0
while pow2:
if (sqrt + pow2) ** 2 <= n:
sqrt += pow2
pow2 //= 2
return sqrt
factorial = 1
for n in range(1, 101):
factorial *= n
if intsqrt(factorial + 1) ** 2 == factorial + 1:
print(n)
The number math.sqrt returns is never an int, even if it's an integer.How to check if a float value is a whole number

Recursion function to find sum of digits in integers using python

def sumdigits(number):
if number==0:
return 0
if number!=0:
return (number%10) + (number//10)
this is the function that I have. However its only give the proper sum of 2 digit numbers. How can i get the sum of any number.
Also would my function count as recursion
def main():
number=int(input("Enter a number :"))
print(sumdigits(number))
main()
No, it is not recursive as you are not calling your function from inside your function.
Try:
def sumdigits(number):
if number == 0:
return 0
else:
return (number%10) + sumdigits(number//10)
Recursion is a way of programming or coding a problem, in which a function calls itself one or more times in its body.
Usually, it is returning the return value of this function call. If a function definition fulfils the condition of recursion, we call this function a recursive function.
A recursive function has to terminate to be used in a program.
Usually, it terminates, if with every recursive call the solution of the problem is downsized and moves towards a base case.
A base case is a case, where the problem can be solved without further recursion. (a recursion can lead to an infinite loop, if the base case is not met in the calls).
For this problem, the "base case" is:
if number == 0:
return 0
A simple recursive function for sum all the digits of a number is:
def sum_digits(number):
""" Return the sum of digits of a number.
number: non-negative integer
"""
# Base Case
if number == 0:
return 0
else:
# Mod (%) by 10 gives you the rightmost digit (227 % 10 == 7),
# while doing integer division by 10 removes the rightmost
# digit (227 // 10 is 22)
return (number % 10) + sumdigits(number // 10)
If we run the code we have:
>>>print sum_digits(57) # (5 + 7) = 12
12
>>>print sum_digits(5728) # (5 + 7 + 2 + 8) = 22
22
For a function to be recursive, it must call itself within itself. Furthermore, since your current one does not do this, it is not recursive.
Here is a simple recursive function that does what you want:
>>> def sumdigits(n):
... return n and n%10 + sumdigits(n//10)
...
>>> sumdigits(457)
16
>>> sumdigits(45)
9
>>> sumdigits(1234)
10
>>>
You don't make a recursive step (calling sumdigits() inside)!
I believe this is what you are looking for:
def sum_digits(n):
if n < 10:
return n
else:
all_but_last, last = n // 10, n % 10
return sum_digits(all_but_last) + last
While recursion is a clever way to go, I'd generally stay away from it for performance and logic reasons (it can get complex pretty quick). I know it's not the answer you are looking for but I'd personally stick to something like this or some kind of loop:
def sumdigits(number):
return sum(map(int, str(number)))
Good luck!
I was working on this recently hope it will help someone in future
def digit(n):
p=0
for i in str(n):
p += int(i)
return p
def superDigit(n):
if n==0:
return 0
return digit(digit(digit(digit(n))))
Here's a solution to summing a series of integer digits that uses ternary operators with recursion and some parameter checking that only happens the first time through the function. Some python coders may consider this less pythonic (using ternary expressions), however, it demonstrates how to use recursion, answering the original question, while introducing ternary operators to combine a few multi-line if/else statements into simple math.
Note that:
int * True = int, whereas int * False = 0
float * True = Float, whereas float * False = 0
"Text" * True = "Text", but "Text" * False = ""; but also
"Text" * 0 = "", whereas "Text" * 3 = "TextTextText"
"Text" * float = Error; whereas "Text" * int = Error
The one-line if/else statement reads as follows:
Expression_if_True if Condition_to_Check else Expression_if_False
def digitSum2(n = 0, first = True):
if first:
first = False
if type(n) != int or n < 0:
return "Only positive integers accepted."
return (n * (n < 10) + (n % 10 + digitSum2(n // 10, first)) * (n >= 10)) if (n > 0) else 0

Generate and Enter Value for OEIS Sequence in Python?

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
>

Categories