Multiplication Python Script giving wrong output - python-3.x

The Code below gives an answer for almost any number I have tested with, even a 64 digits *64 digits. But when tried with
a = 123456
b = 123456
The final answer is negative.
Up until
a = 12345
b = 12345
The answer is correct.
Not sure where this is going wrong. I am relatively new to python so is there something I am missing out?
import numpy as np
a = int(input("Enter Number 1: "))
b = int(input("Enter Number 2: "))
c = 1
pos_nums = []
while b != 0:
z = b % 10
pos_nums.append(z *c)
b = b // 10
c = c*10
pos_num = np.array([pos_nums])
multiply = pos_num *a
add = np.sum(multiply)
print(add)

I don't know why numpy is playing up, but something like this appears to work, and does the same thing.
All I've done is removed the conversion to a numpy array. Now when you multiply pos_num it essentially makes a copies of it into one list. sum counts the total value of the list, which has a amounts of b stored in it.
Hope this works for you :)
a = int(input("Enter Number 1: "))
b = int(input("Enter Number 2: "))
c = 1
pos_nums = []
while b != 0:
z = b % 10
pos_nums.append(z *c)
b = b // 10
c = c*10
#pos_num = np.array(pos_nums)
pos_num = pos_nums
multiply = pos_num *a
add = sum(multiply)
print(add)
Output:
Enter Number 1: 123456
Enter Number 2: 123456
15241383936

numpy can't guess your next move!
you see when you define a numpy array it will assume a type for the array (like np.int16) and its not will not change unless you multiply it into something with other formats
what happend here?
you have multiplied a dtype=np.int32 array into an int in line:
multiply = pos_num *a
the result will be another np.int32 array (you can see that with print(multiply.dtype))
numpy can not guess that you intend to extend the array into for example np.float64
(not like regular python code, because there is a great performace hit to that)
what to do?
just simply define the type for it! (it a good practice to do this in other codes)
pos_num = np.array(pos_nums, dtype=np.float64)

Related

Number of Occurences

I am new to Python and trying to use it for competitive programming.
This is the question:
You are given an unsorted array of characters 'n' and a character 'x'. You have to find the number of times x occurs in character array
Input format:
First line contains an integer T, number of test cases. Then follows T test cases. Each test case consists of two lines. First line contains N, length of the array. Second lines contains N space separated characters. Example
Input
2
4
a b c d
5
a b x c d
Output
0
1
In c++ I know we start like this:
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
...
How do we do the same in python?
This is my code:
t = int(input())
while t:
n = int(input())
arr = [x for x in raw_input().split()]
res = 0
for i in arr:
if i == 'x':
res += 1
t -=1
print(res)
Getting runtime error for this
I think the issue is with how I'm taking inputs to run test cases but not sure
#juanpa arrivillaga answered your question, but it may help you understand that answer better to see an actual implementation.
Example:
from io import StringIO
io_buffer = """2
4
abcd
5
abxcd
"""
with StringIO(io_buffer) as buffer:
num_test_cases = int(buffer.readline())
for _ in range(num_test_cases):
num_chars = int(buffer.readline())
char_line = buffer.readline().strip()
# This is the important part - everything else is overhead
x_count = char_line.count("x")
print(f"character string: {char_line:>5}, length: {num_chars}, x count: {x_count}")
Output:
character string: abcd, length: 4, x count: 0
character string: abxcd, length: 5, x count: 1

Issue with ASCii in Python3

I am trying to convert a string of varchar to ascii. Then i'm trying to make it so any number that's not 3 digits has a 0 in front of it. then i'm trying to add a 1 to the very beginning of the string and then i'm trying to make it a large number that I can apply math to it.
I've tried a lot of different coding techniques. The closest I've gotten is below:
s = 'Ak'
for c in s:
mgk = (''.join(str(ord(c)) for c in s))
num = [mgk]
var = 1
num.insert(0, var)
mgc = lambda num: int(''.join(str(i) for i in num))
num = mgc(num)
print(num)
With this code I get the output: 165107
It's almost doing exactly what I need to do but it's taking out the 0 from the ord(A) which is 65. I want it to be 165. everything else seems to be working great. I'm using '%03d'% to insert the 0.
How I want it to work is:
Get the ord() value from a string of numbers and letters.
if the ord() value is less than 100 (ex: A = 65, add a 0 to make it a 3 digit number)
take the ord() values and combine them into 1 number. 0 needs to stay in from of 65. then add a one to the list. so basically the output will look like:
1065107
I want to make sure I can take that number and apply math to it.
I have this code too:
s = 'Ak'
for c in s:
s = ord(c)
s = '%03d'%s
mgk = (''.join(str(s)))
s = [mgk]
var = 1
s.insert(0, var)
mgc = lambda s: int(''.join(str(i) for i in s))
s = mgc(s)
print(s)
but then it counts each letter as its own element and it will not combine them and I only want the one in front of the very first number.
When the number is converted to an integer, it
Is this what you want? I am kinda confused:
a = 'Ak'
result = '1' + ''.join(str(f'{ord(char):03d}') for char in a)
print(result) # 1065107
# to make it a number just do:
my_int = int(result)

Check if number has a digit multiple times

I've come across a puzzling challenge. I have to check if a number contains the same digit multiple times ex. 11, 424, 66 and so on. at first this seems easy enough but i'm having trouble coming up with a logic to check for this. any ideas?
This is what I've got so far. the function takes in a list. (updated)
arr = [[1,20],[1,10]]
for i in arr:
l = list(range(i[0],i[1]))
for num in l:
if num < 11: continue
for c in str(num):
if str(num).count(c) > 1:
# dont know why code is popping off 12 and 13
print(l.pop(num))
If your ultimate goal is simply detecting if there's a double, this function may help:
def has_doubles(n):
return len(set(str(n))) < len(str(n))
The best way I can think about is converting the number to a string and doing a Counter on it
from collections import Counter
a = 98
c = Counter(str(a))
if any(value > 1 for value in c.values()):
print "The number has repeating digits"
#Two-BitAlchemist thanks for the suggestion
looks like you wanted to create your own algorithm probably researching or a student practice well you just have to understand the properties of numbers divided by 10 where 1/10 = 0.1 10/10 = 1 13/10 = 1 reminder 3 13013/10 = 1301 rem 3 hence we can create a function that stores the reminders in an array an check them against the reminder of next number here is the algorithm in python using recursion, you can achieve the same via loops
def countNumber(foundDigits,number):
next_number = int(number/10);
reminder = number % 10;
if(next_number < 1):
for num in foundDigits:
if(num == number or num == reminder):
return True
return False;
foundDigits.append(reminder);
return countNumber(foundDigits,next_number)
example in interpreter could be
digitsFound = list()
countNumber(digitsFound, 435229)
Solved this! I didn't know pop executes based on position not value! remove is a better fit here.
arr = [[1,40],[1,10]]
for i in arr:
l = list(range(i[0],i[1]))
for num in l:
if num < 11: continue
for char in str(num):
if str(num).count(char) < 2: continue
l.remove(num)
break
print(l)
Here is my solution, its simple and works for 2 digit numbers.
nums = list(input().rstrip().split())
def has_doubles(nums):
for number in nums:
if number[0] == number[1]:
print(number)
else:
continue
has_doubles(nums)

Matlab, order cells of strings according to the first one

I have 2 cell of strings and I would like to order them according to the first one.
A = {'a';'b';'c'}
B = {'b';'a';'c'}
idx = [2,1,3] % TO FIND
B=B(idx);
I would like to find a way to find idx...
Use the second output of ismember. ismember tells you whether or not values in the first set are anywhere in the second set. The second output tells you where these values are located if we find anything. As such:
A = {'a';'b';'c'}
B = {'b';'a';'c'}
[~,idx] = ismember(A, B);
Note that there is a minor typo when you declared your cell arrays. You have a colon in between b and c for A and a and c for B. I placed a semi-colon there for both for correctness.
Therefore, we get:
idx =
2
1
3
Benchmarking
We have three very good algorithms here. As such, let's see how this performs by doing a benchmarking test. What I'm going to do is generate a 10000 x 1 random character array of lower case letters. This will then be encapsulated into a 10000 x 1 cell array, where each cell is a single character array. I construct A this way, and B is a random permutation of the elements in A. This is the code that I wrote to do this for us:
letters = char(97 + (0:25));
rng(123); %// Set seed for reproducibility
ind = randi(26, [10000, 1]);
lettersMat = letters(ind);
A = mat2cell(lettersMat, ones(10000,1), 1);
B = A(randperm(10000));
Now... here comes the testing code:
clear all;
close all;
letters = char(97 + (0:25));
rng(123); %// Set seed for reproducibility
ind = randi(26, [10000, 1]);
lettersMat = letters(ind);
A = mat2cell(lettersMat, 1, ones(10000,1));
B = A(randperm(10000));
tic;
[~,idx] = ismember(A,B);
t = toc;
fprintf('ismember: %f\n', t);
clear idx; %// Make sure test is unbiased
tic;
[~,idx] = max(bsxfun(#eq,char(A),char(B)'));
t = toc;
fprintf('bsxfun: %f\n', t);
clear idx; %// Make sure test is unbiased
tic;
[~, indA] = sort(A);
[~, indB] = sort(B);
idx = indB(indA);
t = toc;
fprintf('sort: %f\n', t);
This is what I get for timing:
ismember: 0.058947
bsxfun: 0.110809
sort: 0.006054
Luis Mendo's approach is the fastest, followed by ismember, and then finally bsxfun. For code compactness, ismember is preferred but for performance, sort is better. Personally, I think bsxfun should win because it's such a nice function to use ;).
This seems to be significantly faster than using ismember (although admittedly less clear than #rayryeng's answer). With thanks to #Divakar for his correction on this answer.
[~, indA] = sort(A);
[~, indB] = sort(B);
idx = indA(indB);
I had to jump in as it seems runtime performance could be a criteria here :)
Assuming that you are dealing with scalar strings(one character in each cell), here's my take that works even when you have not-commmon elements between A and B and uses the very powerful bsxfun and as such I am really hoping this would be runtime-efficient -
[v,idx] = max(bsxfun(#eq,char(A),char(B)'));
idx = v.*idx
Example -
A =
'a' 'b' 'c' 'd'
B =
'b' 'a' 'c' 'e'
idx =
2 1 3 0
For a specific case when you have no not-common elements between A and B, it becomes a one-liner -
[~,idx] = max(bsxfun(#eq,char(A),char(B)'))
Example -
A =
'a' 'b' 'c'
B =
'b' 'a' 'c'
idx =
2 1 3

Fibonacci Sequence logic in Python [duplicate]

This question already has answers here:
How to write the Fibonacci Sequence?
(67 answers)
Closed 9 years ago.
A tutorial I am going through had the following program
# This program calculates the Fibonacci sequence
a = 0
b = 1
count = 0
max_count = 20
while count < max_count:
count = count + 1
old_a = a # we need to keep track of a since we change it
print(old_a,end=" ") # Notice the magic end=" " in the print function arguments that
# keeps it from creating a new line
a = b
b = old_a + b
print() # gets a new (empty) line
The code is perfect. However, I am not able to figure out how the sequence is calculated.
How are the values changed to create the sequence?
It'll make more sense if you remove all of that extraneous code:
while count < max_count:
old_a = a
a = b
b = old_a + b
The old_a is probably confusing you. It's the long way of writing this:
a, b = b, a + b
Which swaps a with b and (at the same time), b with a + b. Note that it isn't the same as writing:
a = b
b = a + b
Because by the time you re-define b, a already holds its new value, which is equal to b.
I'd also run through the code manually by writing it out on paper.
This code works fine:
a, b = 0, 1
for _ in range(20):
print a
a, b = b, a+b

Resources