How do i convert all the variables into an int straightaway - python-3.x

a,b,c = input(a,b,c).split()
would need a way to immediately convert a,b,c into int without having to do something like
a = int(a)
b = int(b)
c = int(c)
please help :)

l = input().split(',')
l = [ int(i) for i in l ]
a, b, c = *l
Run the code and enter 3 integers separated by ',' then a b and c will contain the 3 integers

Related

Count number of occurences of each string using regex

Given a pattern like this
pattern = re.compile(r'\b(A|B|C)\b')
And a huge_string I would like to replace every substring matching the pattern with a string D and find the number of occurences for each string A, B and C. What is the most feasible approach?
One way is to split the pattern to 3 patterns for each string and then use subn
pattern_a = re.compile(r'\bA\b')
pattern_b = re.compile(r'\bB\b')
pattern_c = re.compile(r'\bC\b')
huge_string, no_a = re.subn(pattern_a, D, huge_string)
huge_string, no_b = re.subn(pattern_b, D, huge_string)
huge_string, no_c = re.subn(pattern_c, D, huge_string)
But it requires 3 passes through the huge_string. Is there a better way?
You may pass a callable as the replacement argument to re.sub and collect the necessary counting details during a single replacement pass:
import re
counter = {}
def repl(m):
if m.group() in counter:
counter[m.group()] += 1
else:
counter[m.group()] = 1
return 'd'
text = "a;b o a;c a l l e d;a;c a b"
rx = re.compile(r'\b(a|b|c)\b')
result = rx.sub(repl, text)
print(counter, result, sep="\n")
See the Python demo online, output;
{'a': 5, 'b': 2, 'c': 2}
d;d o d;d d l l e d;d;d d d
you could do it in 2 passes, the first just counting then the second doing the sub. this will mean if your search space grows like a|b|c|d|e etc you will still only do 2 passes, your number of passes will not be based on your number of possible matches.
import re
from collections import Counter
string = " a j h s j a b c "
pattern = re.compile(r'\b(a|b|c)\b')
counts = Counter(pattern.findall(string))
string_update = pattern.sub('d', string)
print(counts, string, string_update, sep="\n")
OUTPUT
Counter({'a': 2, 'b': 1, 'c': 1})
a j h s j a b c
d j h s j d d d

Multiplication Python Script giving wrong output

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)

Shortest path program Python

I've written the following program, and there are 2 'mistakes' which I don't know how to fix. Inputs b1, c1, d1, and e1 correspond to points and adjacent nodes.
For instance, if I give the input: A B C, this means that from point A you can travel to B and C. The input f1 corresponds to the starting and endpoint. For instance, if I give the input: A D, this means that you start at point A and want to finish at point D.
b1 = input()
c1 = input()
d1 = input()
e1 = input()
f1 = input()
b = b1.split()
c = c1.split()
d = d1.split()
e = e1.split()
f = f1.split()
b_node = b[1:]
c_node = c[1:]
d_code = d[1:]
e_node = e[1:]
f_node = f[1:]
G = {b[0]:b_node, c[0]:c_node, d[0]:d_node, e[0]:e_node}
def find_path(graph, start, end, path = []):
path = path + [start]
newpath = []
if start == end:
return path
shortest = None
for node in graph[start]:
if node not in path:
newpath = find_path(graph, node, end, path)
if newpath:
if not shortest or len(newpath)<len(shortest):
shortest = newpath
return shortest
print(find_path(G, f[0], f[1]))
I give my program the following input
A B C
B A C
C B D
D
A D
My questions are the following:
1. My program gives an error because d_node = [] (empty). However, this is
supposed to be so since from point D, you can't travel to any point! How can I make it run correctly?
2. Is there a way to let my program ask for a number 'N' points, and then give me N lines to give for those points all the adjacent info? I tried something of the form
input_list = []
x = int(input())
for i in range(x):
input_list.append(input())
But couldn't make it work.. Any ideas?
1:
You have a typo for 'd_node' as you have written 'd_code'.
2:
Try with a while-loop; continue if you enter a blank line (which will indicate that you are done entering points). Something like:
while True:
i = input()
if not i:
break

How to make the limit of the readlines to the first number in the file?

so this program predicts the first winning move of the famous Game of Nim. I just need a little help figuring out this problem in the code. The input file reads something like this.
3
13 4 5
29 5 1
34 4 50
The first number would represent the number of lines following the first line that the program has to read. So if the case was
2
**13 4 5
29 5 1**
34 4 50
it would only read the next two lines following it.
So far this has been the progress of my code
def main ():
nim_file = open('nim.txt', 'r')
first_line = nim_file.readline()
counter = 1
n = int (first_line)
for line in nim_file:
for j in range(1, n):
a, b, c = [int(i) for i in line.split()]
nim_sum = a ^ b ^ c
if nim_sum == 0:
print ("Heaps:", a, b, c, ": " "You Lose!")
else:
p = a ^ nim_sum
q = b ^ nim_sum
r = c ^ nim_sum
if p < a:
stack1 = a - p
print ("Heaps:", a, b, c, ": " "remove", stack1, "from Heap 1")
elif q < b:
stack2 = b - q
print ("Heaps:", a, b, c, ": " "remove", stack2, "from Heap 2")
elif r < c:
stack3 = c - r
print ("Heaps:", a, b, c, ": " "remove", stack3, "from Heap 3")
else:
print ("Error")
nim_file.close()
main()
I converted the first line number to an int and tried to set a while loop at first with a counter to see that the counter wouldn't go above the value of n but that didn't work. So any thoughts?
If the file is small, just load the whole thing:
lines = open('nim.txt').readlines()
interesting_lines = lines[1:int(lines[0])+1]
and continue from there.
Yo have two nested for statement, the second of which doesn't make much sence. You need to leave just one, like this:
for _ in range(n):
a, b, c = [int(i) for i in nim_file.readline()]
and remove for line in nim_file. Also check out this question and consider using the with statement to handle the file opening/closing.

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