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
Related
records = [["chi", 20.0],["beta", 50.0],["alpha", 50.0]]
a = len(records)
i = 0
b = []
while i < a:
print(records[i][1])
b.append(records[i][1])
i = i + 1
print(b)
c = len(b)
#from previous question
unique_list = []
for el in b:
if el not in unique_list:
unique_list.append(el)
else:
print ("Element already in the list")
print(unique_list)
second_lowest_score = unique_list[1]
print(second_lowest_score)
names_list = []
g = 0
while g < a:
if records[g][1] == second_lowest_score:
names_list.append(records[g][0])
g = g + 1
print(names_list)
What I want to do is to append the names of records which have the second lowest score (50) to the names_list. However, the while loop gives me no result. There is no syntax error so I am not sure why my code is wrong. However, when I use the previous while loop for appending the numbers, it seems to work fine. Is it not possible to use an if statement in a while loop?
This is a pretty simple problem. The g variable is not getting incremented if the if statement does not run, so the loop will endlessly continue on the same value of g.
The fix for this is to move the increment of g outside of the if statement (but still in the while loop). That way it will continue past values even if they do not match the if condition.
if records[g][1] == second_lowest_score:
names_list.append(records[g][0])
g = g + 1
I have a problem with task.
Write a program that will replace the given position for the given string (also given by the user). The function has 3 parameters, string for analysis, position that should be replaced and the character that has services to be changed.
I tried it that way but it doesn't work.
At the end there is the same string as at the beginning
a =input("enter string\n")
print(len(a))
for i in enumerate(a):
print("individual indexes:",([i]))
b = input("enter the index number you want to replace\n")
b = str([a,i])
c = input("what do you want to change ?\n")
a1 = a.replace(b,c)
print(a1)
b = int(b)
a1 = a[:b] + 'c' + a[b:]
a =input("enter string\n")
print(len(a))
for i in enumerate(a):
print("individual indexes:",([i]))
b = int(input("enter the index number you want to replace\n"))
c = input("what do you want to change ?\n")
a1 = a[:b] + 'c' + a[b:]
print(a1)
First, a side note. Avoid using variable names such as: a, b...names should be meaningful.
For example:
a --> input_str
b --> idx_to_change
c --> new_char
a1 --> final_str
A full working example:
input_str =input("enter string\n")
print(len(input_str))
for i in enumerate(input_str):
print("individual indexes:",([i]))
idx_to_change = input("enter the index number you want to replace\n")
idx_to_change = input_str [int(idx_to_change)]
new_char = input("what do you want to change ?\n")
final_str = input_str.replace(idx_to_change, new_char)
print(final_str)
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)
I'm really tired, so I'm probably just forgetting something, but here it is. It's been a long time since I've even touched quadratics. The answers are totally off, for example:
2x**2 – 4x – 3 = 0 should result in x = –0.58, x = 2.58. Instead, I get x=10, x=-2. I'm sure I'm doing something super basic wrong here.
import math
import sys
a = float(input('a ='))
b = float(input('b ='))
c = float(input('c ='))
cont = float(input('Continue? (1/0)'))
a1 = int((-b + math.sqrt(b**(2)-4*a*c))/2*a)
a2 = int((-b - math.sqrt(b**(2)-4*a*c))/2*a)
if cont == 1:
print(a)
print(b)
print(c)
print(cont)
print('x1 =',a1)
print('x2 =', a2)
elif cont == 0:
sys.exit
Add parenthesis to your equation around (2*a):
a1 = (-b + math.sqrt(b**(2)-4*a*c))/(2*a)
a2 = (-b - math.sqrt(b**(2)-4*a*c))/(2*a)
Also, do you mean to convert to integer?
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