This code works but it's not what I need
lst = range(1,17)
It uses from 1 to 16 to do some calculations but in fact I want to specify the values, when I type them inside the code it works:
lst = (14, 1, 6, 8)
but what I want is the user who must choose which values to be in the list by inputting them
I have tried this but it does not works
lst = (a1, a2, a3)
a1 = int(input("number 1: "))
a2 = int(input("number 2: "))
a3 = int(input("number 3: "))
You have to switch the order of your lines of code:
a1 = int(input("number 1: "))
a2 = int(input("number 2: "))
a3 = int(input("number 3: "))
lst = (a1, a2, a3)
Python will execute your example code line-by-line in top-down order, so if you want to create list/tuple from inputed values the creation has to be as last one.
Related
I tried writing a program that would give me the i,j and k components of a vector of a specified magnitude.
import random
import math
while True:
a = random.uniform(0,1000)
b = random.uniform(0,1000)
c = random.uniform(0,1000)
d = 69.420
if math.sqrt(a**2 + b**2 + c**2) == d:
print(a,b,c)
break
But it seems that this program might take literally forever to give me an output.
What would faster or possible solution be?
#Update
import random
import math
while True:
a2 = random.uniform(1,1000)
b2 = random.uniform(1,1000)
c2 = random.uniform(1,1000)
d = 69.420
d2 = a2 + b2 + c2
a2 *= d/d2
b2 *= d/d2
c2 *= d/d2
a = math.sqrt(a2)
b = math.sqrt(b2)
c = math.sqrt(c2)
if math.sqrt(a**2 + b**2 + c**2) == d:
print(a,b,c)
break
As per suggested, but still taking a very long time to compute
Get three random numbers a2, b2, and c2. Those are your random squares. Add them up to get d2. You want the sum of the squares to be d squared, so multiply a2, b2, and c2 by d*d/d2. These are your new squares that add up to d squared. Now assign the square roots of a2, b2, and c2 to a, b, and c. Does that make sense?
Avoid dividing by zero. If d2 happens to be zero, just start over.
for i in range(N):
k1,k2,k3,k4 = input().split(' ')
k2 = float(k2)
k3 = float(k3)
k4 = float(k4)
score = (k2+k3+k4)/3
a = {print(k1) : score}
The input has 4 values: string, int, int, int.
I want to set the value of k1 as key and the score as value.
When I tried the above code, this was the output:
1
You first need to initialise the dictionary and then you can insert items into it with dictionary[key] = value
# Initialise a dictionary where we can store values to
a = {}
# How many times we will ask for values
n = int(input('number of values: '))
for i in range(n):
k1,k2,k3,k4 = input('give input: ').split(' ')
k2 = float(k2)
k3 = float(k3)
k4 = float(k4)
score = (k2+k3+k4)/3
# Store the score value to k1 key
a[k1] = score
# Print the dictionary after the loop has been completed
print(a)
This will do the following:
number of values: 3
give input: first 1 2 3
give input: second 4 5 6
give input: third 10 20 30
{'first': 2.0, 'second': 5.0, 'third': 20.0}
Here's the code that work (very small modification from your original code)
for i in range(4):
k1, k2, k3, k4 = input().split(" ")
k2 = float(k2)
k3 = float(k3)
k4 = float(k4)
score = (k2 + k3 + k4) / 3
print({k1: score})
If you run it with the value of 1 10 20 30 the script returns:
{'1': 20.0}
The following code creates a list with entered values:
def locateLargest():
matrix = []
numberOfRows = int(input("Enter the number of rows: "))
numberOfColumns = 2
for row in range(0, numberOfRows):
matrix.append([])
for column in range(0, numberOfColumns):
value = int(input("Enter a value: "))
matrix[row].append(value)
max_value = None
for value in matrix:
if not max_value:
max_value = value
elif value > max_value:
max_value = value
print(max_value)
locateLargest()
The issue I am running into is that it is asking for each value individual in the row, and is returning the maximum pair of values in the row, not the maximum value's index.
The sample run of what I should be getting is:
Enter the number of rows in the list: 3
Enter a row: 23.5 35 2 10
Enter a row: 4.5 3 45 3.5
Enter a row: 35 44 5.5 11.6
The location of the largest element is at (1,2)
Any ideas?
My current output is:
Enter the number of rows: 2
Enter the number of columns: 6
Enter a value: 2
Enter a value: 2
Enter a value: 2
Enter a value: 2
Enter a value: 2
Enter a value: 2
Enter a value: 7
Enter a value: 6
Enter a value: 4
Enter a value: 3
Enter a value: 6
Enter a value: 2
[7, 6, 4, 3, 6, 2]
This is not very 'pythonic' but will help you achieve your end goal and hopefully understand the process. As Ćukasz mentioned, you need to do an iteration for each row, and for each column in each row:
First declare the variable to store your location:
maxPoint = [0,0]
Then enumerate your matrix such that you can get the list from each row, but also retrieve the index of the currently active row:
for idx, row in enumerate(matrix):
Find the max value in the current list of values, ie: [10, 20, 30]
maxRowValue = max(row)
Find which column this maximum value lives in, ie: [0, 1, 2, ...]
maxRowIndex = row.index(maxRowValue)
Determine if max row value is in fact greater than any other previously located points, if it is less discard it:
if maxRowValue <= matrix[maxPoint[0]][maxPoint[1]]:
continue
If the value is greater, save it to the maxPoint variable:
maxPoint = [idx, maxRowIndex]
EDIT
For the sake of completeness, here is the complete code sample with AChampion's performance improvements added:
def locateLargest():
matrix = []
numberOfRows = int(input("Enter the number of rows: "))
numberOfColumns = 2
for row in range(0, numberOfRows):
matrix.append([])
for column in range(0, numberOfColumns):
value = int(input("Enter a value: "))
matrix[row].append(value)
maxPoint = [0,0]
for rIndex, row in enumerate(matrix):
cIndex, maxRowValue = max(enumerate(row), key=lambda x: x[1])
if maxRowValue <= matrix[maxPoint[0]][maxPoint[1]]:
continue
maxPoint = [rIndex, cIndex]
print(maxPoint)
locateLargest()
EDIT 2
Here is the same algorithm without using enumerate:
currentRow = 0
for row in matrix:
maxRowValue = max(row)
maxRowIndex = row.index(maxRowValue)
if maxRowValue > matrix[maxPoint[0]][maxPoint[1]]:
maxPoint = [currentRow, maxRowIndex]
currentRow += 1
Using enumerate() and some generator expressions, you can reduce this code quite a bit:
Generate the rows
Generate the maximum for each row
Find the maximum across all rows
More complex perhaps than some would like:
numberOfRows = int(input("Enter the number of rows: "))
# Generate the rows
rows = (map(int, input("Enter a row: ").split()) for _ in range(numberOfRows))
# Generate the maximum for each row
max_row = (max(enumerate(data), key=lambda x: x[1]) for data in rows)
# Find the maximum across all rows
i, (j, v) = max(enumerate(max_row), key=lambda x: x[1][1])
print("The location of the largest element is at {} [{}]".format((i, j), v))
Input / Output:
Enter the number of rows: 3
Enter a row: 1 2 3
Enter a row: 3 6 3
Enter a row: 1 2 3
'The location of the largest element is at (1, 1) [6]'
If you want to see what is going on change the generators to list comprehensions:
>>> rows = [list(map(int, input("Enter a row: ").split())) for _ in range(numberOfRows)]
Enter a row: 1 2 3
Enter a row: 3 6 3
Enter a row: 1 2 3
>>> rows
[[1, 2, 3], [3, 6, 3], [1, 2, 3]]
>>> max_row = [max(enumerate(data), key=lambda x: x[1]) for data in rows]
>>> max_row
[(2, 3), (1, 6), (2, 3)]
>>> list(enumerate(max_row))
[(0, (2, 3), (1, (1, 6)), (2, (2, 3))]
^^^^^^^^^
i, (j, v)
import math
def roundup(x):
return int(math.ceil(x / 10.0)) * 10
w=0
while w == 5:
print("Would you like to *work out* a missing letter in a GTIN-8 code, or *check* a code?")
response = input(":")
if response == 'work out':
print("Input a 7 digit GTIN-8 code and I'll work out the 8th")
c1 = int(input("Enter FIRST number: "))
c2 = int(input("Enter SECOND number: "))
c3 = int(input("Enter THIRD number: "))
c4 = int(input("Enter FOURTH number: "))
c5 = int(input("Enter FIFTH number: "))
c6 = int(input("Enter SIXTH number: "))
c7 = int(input("Enter SEVENTH number: "))
y = (c1*3+c2+c3*3+c4+c5*3+c6+c7*3)
ru2=roundup(y)
GTIN8 = ru2-y
print("Your GTIN8 Code would be: "+str(c1)+str(c2)+str(c3)+str(c4)+str(c5)+str(c6)+str(c7)+str(GTIN8))
print("Wanna work out another?")
if response == 'check':
print("Input a 8 digit GTIN-8 code and I'll check if it's correct")
c1 = int(input("Enter FIRST number: "))
c2 = int(input("Enter SECOND number: "))
c3 = int(input("Enter THIRD number: "))
c4 = int(input("Enter FOURTH number: "))
c5 = int(input("Enter FIFTH number: "))
c6 = int(input("Enter SIXTH number: "))
c7 = int(input("Enter SEVENTH number: "))
c8 = int(input("Enter EIGTH number: "))
y = (c1*3+c2+c3*3+c4+c5*3+c6+c7*3)
ru2=roundup(y)
GTIN8 = ru2-y
if GTIN8 != c8:
print("Nope that product code is incorrect!")
reply=input("Want to know the correct answer to your code? Type yes if so: ")
if reply == 'yes':
print("The correct answer would have been: "+str(GTIN8))
if GTIN8 == c8:
print("That code is correct!")
The problem is that I have tried time and time again, to make this code smaller.
Even by inputting 'response' as a string, to allow the user to type the code in one go.
If you couldn't already tell, this is a code for a GTIN-8 product code and I know there are various other GTIN-8 codes out there but I just couldn't do it, let alone copy.
To get you started, here is one simple way of reducing the number of lines
c = [int(x) for x in input("Input a 8 digit GTIN-8 code and I'll check if it's correct").split("")]
Now you can access each character with c[n].
How do obtain the totals for each of the column (in total 100) in the data frame. My data is a qualitative type.
For example
ID1 ID2 ID3 ID4 ID5 ID100
Y N
Y Y
N N
N Y
And I want to find the total of columns (how many Ys and Ns) in ID1, ID2 and etc....
i have tried typing the following code
colSums(mydata[,[1:ncol(mydata)]
thanks in advance
If you had information about which package you're using for the array I could be more specific. Here's a general solution that assumes your array is a 'list of lists' where each column is a list item within a larger list.
def sum_array(array):
""" Returns the number of Y, N for each column """
for column in array:
y_count = 0
n_count = 0
for cell in column:
if cell == "Y":
y_count += 1
elif cell == "N":
n_count += 1
else:
raise TypeError("bad entry")
# print out count for each column
print "column ", column, " has Y: ", y_count, " and N: ", n_count, " entries."
If you can provide more information, I'll try to help you with a more specific solution.