Could you explain the solution to front_back google python exercise [closed] - python

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am looking for an explanation to the solution to the front_back google python exercise. Specifically, I do not understand why the % symbol (placeholder?) is used. I also do not understand why the length of the strings are divided by 2. Especially since 2 does not equal 1 (2==1??)
The problem/solution is as follows:
# F. front_back
# Consider dividing a string into two halves.
# If the length is even, the front and back halves are the same length.
# If the length is odd, we'll say that the extra char goes in the front half.
# e.g. 'abcde', the front half is 'abc', the back half 'de'.
# Given 2 strings, a and b, return a string of the form
# a-front + b-front + a-back + b-back
def front_back(a, b):
# +++your code here+++
# LAB(begin solution)
# Figure out the middle position of each string.
a_middle = len(a) / 2
b_middle = len(b) / 2
if len(a) % 2 == 1: # add 1 if length is odd
a_middle = a_middle + 1
if len(b) % 2 == 1:
b_middle = b_middle + 1
return a[:a_middle] + b[:b_middle] + a[a_middle:] + b[b_middle:]
# LAB(replace solution)
# return
# LAB(end solution)
THANK YOU!

It seems the statement you're most confused about is if len(a) % 2 == 1:. The % sign in this case means division with remainder (modulo). So if the length of the string were odd then dividing the length by 2 has a remainder 1 and if the length were even the remainder is 0. The if statement checks if the remainder is 1 and therefore if the length is odd.
Earlier the length strings are divided by 2 to find the middle position of the strings. However, since len(string) and 2 are both integers, python performs integer division and rounds the result down to an integer, which is why you need to add back the extra spacing unit with if statement if the length were odd.
The final statement of the code then uses the slice syntax to concatenate the string halves based on the positions found previously.

Related

How can I repeatedly divide a number by the elements of a list? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
divisors = []
def check_for_prime(x):
divisors = [x / d for d in list(range(x)) if x != any([0, 1, x])]
if isinstance(divisors, float):
yield x
When I try to run this code, it shows an error: 'list object cannot be interpreted as an integer'. How can I fix this so the loop can successfully divide everything?
It seems like you are trying to check if a given number is prime through list comprehension. There are a good bunch of things wrong with your logic-
divisors = [x / d for d in list(range(x)) if x != any([0, 1, x])]
I believe you're trying to find a list of divisors for x here. This makes no sense though, even if I assume that you thought x != any([0, 1, x]) means "if x is either 0, 1, or x" (that's not actually what this code means). Wouldn't that statement always be true? I mean x has got to be x (unless it's nan, but that's a different topic).
If you wanted to express "if x is either 0, 1 or x" in python, you'd use if x in [0, 1, x] (you shouldn't want to though since that makes 0 sense as explained above). Not any. Read what any does.
To get a list of divisors for x, you should instead do-
divisors = [d for d in range(2, math.floor(x/2) + 1) if x % d == 0]
Essentially, you start from 2 (not 0 because that's impossible, and not 1 because we want to avoid that for prime checking), and stop at half the given number (because after that point, you can't divide the given number and get an integral result). Throughout this range, you only add those d for which x % d is 0. I.E, the result is integral. Notice, 6 % 3 is 0, because 3 is indeed a divisor of 6.
I have 0 clue what the hell you're trying to do here though-
if isinstance(divisors, float):
yield x
You're checking whether or not divisors is a float? why? you already know it's a list, you made it in the previous line.
I think you want to know if the given number is a prime or not. In that case, you can just check if the length of divisors is more than 0.
return len(divisors) > 0
Edit: As #RiccardoBucco mentioned below. If you don't want the list of divisors at all, you can simply return as soon as you find a divisor. A simple loop will suffice for that.
for d in range(2, math.floor(x/2) + 1):
if x % d == 0:
# x is not prime
return False
# x is prime
return True
However, DO NOT forget to factor in the exceptional case when x = 1, 1 is not a prime number. Should be factored in both the for loop and the list comprehension method.
You are passing your list as the input argument to range, which expects an integer. Don't do that. Say for i in list.
This will always fail because you're creating a new list by using the comprehension in line 3. Line 4 will always evaluate to False because a list is obviously not a float.

Why does % work and / does not in filtering out even numbers? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Compare these two blocks, there's only an operator difference;
for i in range(0, 10):
if i / 2 == 0:
continue
print(i)
and
for i in range(0, 10):
if i % 2 == 0:
continue
print(i)
Why does the second block of code work in successfully filtering out even numbers while the first block does not? I can't wrap the logic around my head. Intuitively any even number should be divisible by 2, so why does the first block not work and prints every number in the range?
Becasuse % takes the reminder of the division (ref, ref), and / gives you the result of the divison (ref).
i / 2 == 0 is only True if i=0.
i % 2 == 0 is only True if i is divisible by 2 (ie you can divide it without getting a remainder, ie it is even).
Because modulo (%) checks divisibility, while division (/) doesn't. This is more of a math question than programming.
If a number N is divisible by another number M, N mod M will be 0. Meanwhile, N divided by M will be K, where K times M equals N, and K will be a whole number since N is divisible by M.
So if you wanted to check divisibility using division, you could check if K is a whole number:
for i in range(0, 10):
k = i / 2
if k == int(k):
continue
print(i)
But don't do this. Modulo is much simpler.
References
Tutorial: Numbers
Binary arithmetic operations
If you want to use division as operation then that's the solution.
for i in range(0, 10):
if (i // 2) * 2 != i:
continue
print(i)
The difference is that by using % you will be getting the modulo % 2 gives you 1 or 0 depending if the number is even or odd. /2 will give you the number divided by 2.

How to determine the existence of a d-redigit multiple of N? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have the following problem:
I am given 2 natural positive numbers: d and N.
I need to find the length of the minimum d-redigit that is a multiple of N.
A natural number x is a d-redigit if x is a sequence of d's.
Example: 111111 is a 1-redigit.
There may be no d-redigit multiple of N.
I know how to solve the problem when I know that a d-redigit that is multiple of N exists. However, my question is: How can I determine if this d-redigit, multiple of N, exists?
Note: The programming language for this implementation doesn't really matter, it can be pseudo code, GCL preferably.
I have tried the following implementation in Python:
def proyect_a(n:int, d:int):
if n == 0 or d == 0:
return ''
i = 1
red = d
while i < 11 and red%n != 0:
red = 10*red + d
i+=1
if i < 11:
return len(str(red))
else:
return '*'
The previous algorithm is a brute-force partial solution, since it can't really tell the length of the minimum d-redigit for all cases. As you can see, the cycle repeats 10 times max, given that I really don't know how to check if a d-redigit multiple of N exists.
First of all, since you're only concerned about divisibility by n, there's no need to use huge integers. Just compute the value of repdigit modulo n at each step. For any value of repdigit, there are only n possible values of repdigit % n, so if you don't find a multiple of n after n iterations, you can be sure that no solution exists.
But you can do a lot better by looking for repeating cycles in the calculated values. The simplest approach would be to store each successive value of repdigit. If a value occurs twice, then that means you've entered a repeating cycle and there is no solution. But there's no need to store every value of repdigit. Each iteration of the loop is equivalent to calculating the next output of a linear congruential generator with a=10, c=d, and m=n. If you start with an initial value of zero, the output sequence will settle into a repeating cycle after at most 3 iterations.
With a bit of mathematical reasoning, you could speed up the calculations even more. What you're essentially calculating is the number of iterations that it takes for an LCG seeded with a value of zero to output zero a second time (using parameters a,c,m = 10,d,n).
For example, this LCG will produce a maximal length sequence when n and d are coprime and n is a power of 3, in which case min_repdigit_multiple(n,d) will be equal to n. There are probably other short cuts you could take.
def min_repdigit_multiple(n:int, d:int):
#
# Returns the length of the smallest repdigit number divisible by n
# i.e. the smallest value of x such that ((10**x-1)*d//9) % n == 0
# If no solution exists, returns -1 instead
#
assert 0 < d <= 9, "d must be a single non-zero digit"
#
# Check for a maximal length LCG sequence
from math import gcd
if gcd(n,d) == 1:
n0 = n
while n0 % 3 == 0:
n0 //= 3
if n0 == 1:
return n
#
i = 1
repdigit = 0
seen = set()
while i <= n:
repdigit = (10 * repdigit + d) % n
if repdigit in seen:
# We've been here before, so there is no solution
return -1
if repdigit == 0:
# Success: repdigit is divisible by n
return i
# There's no point in storing more
# than the first few values of repdigit
if i < 4:
seen.add(repdigit)
i += 1
return -1 # Searched all possible values without finding a solution

Double Slash Assignment division in Python [duplicate]

This question already has answers here:
What exactly does += do?
(17 answers)
Closed 3 years ago.
I am new to Python and found a function that checks to see if an array of arguments can be made equal by only multiplying the number by 2. However, there is some notation that I do not understand.
Function:
def isEqual(a,n): # a is an arrary, n is the length of array
for i in range(0,n):
while a[i]%2==0:
a[i]//=2 # this is the part I do not understand
print(a[i])
if a[i] != a[0]:
return print("False")
# Otherwise, all elements equal, return true
return print("True")
When I step through the function I see that it replaces the a[i] number by a[i]//2, but I do not understand why you would write // equals to number
I understand the // is "floor" division, but not why someone would write a[i]//=2. I would have thought to write it as a[i]=a[i]//2. I can only assume these are the same things, I just never saw it written this way.
Test code:
a = [50, 4, 2]
n = len(a)
isEqual(a, n)
You might have came across operations that also assign value. Think
a += 1 # same as: a = a + 1
This is exactly the same. It integer divides and assigns the value. Probably better understood with proper spacing:
a //= 2 # same as: a = a // 2

Python factorization program [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm new to programming and I am trying to write a program that takes a positive integer n from input, and then outputs all factorizations of n.
For example if n=10 the program would output
1 times 10 equals 10
2 times 5 equals 10
5 times 2 equals 10
10 times 1 equals 10
I believe the easiest way to do it is to use an if statement nested within for loops. Can anybody provide me with any guidance to help create this? So far I have...
n = int(input())
a = 0
b = n
for a in range(0, n):
if a * b !=n:
continue
if a * b ==n:
print (a+ "times" +b+ "equals" +n)
a=a+1
b=n-1
But for some reason it isn't working. I think I have the right general idea but my code is obviously incorrect.
There are a few issues with your code, but also with your logic. You are increasing a twice (with for and addition), b becomes n-1 the first time through the loop and stays that way, but even if it didn't (eg b = b - 1), it wouldn't work, because if you are increasing a and decreasing b simultaneously, you won't find the correct values unless they happen to match by chance.
Other than that, it's unnecessary to check for a * b != n, you need to call str on the integers to add them to strings and the 0 in your range call is redundant.
whncode's answer is an elegant solution (except for a couple of errors I tried to correct), but to use your logic, you might do this:
for a in range(1, n+1):
for b in range(1, n+1):
if a * b == n:
print str(a) + " times " + str(b) + " equals " + str(n)
n = 10
for divisor in range(n, 0, -1): # reverse range
if (n%divisor == 0): # if modulo is 0
print("%d times %d equals %d", (n/divisor, divisor, n)

Categories