Multiply a value of a list with the previous value - python

Here's the code that i'm using:
pie = []
start = 102
stop = 1
step = 1
for i in range(stop,start):
result = (i - step) / 100
pie.append(result)
print(pie)
for i in pie:
result = pie[i] * pie[i-1]
pie.append(result)
print(pie)
and here's the error that i'm getting:
TypeError: list indices must be integers or slices, not float

You have added float numbers in pie list:
result = (i - step) / 100
pie.append(result) # [0.0, 0.01, 0.02, ...]
Then you used those numbers here as index:
for i in pie:
result = pie[1] * pie[i - 1]
pie.append(result)
Error is also saying same thing: list indices must be integers or slices, not float

Related

Confused on float and integers, how to make the output exactly as it is, not round up or unnecessary ".0"

I'm trying to make a code to find the gradient of a straight line for my assignment.
It went well but unfortunately it didn't pass 3 test case because the output has decimals so it rounds up the decimals to make it a whole number.
This the code;
Ax, Ay = input ().split()
Bx, By = input ().split()
Ax=int (Ax)
Ay=int (Ay)
Bx=int (Bx)
By=int (By)
M=(By-Ay)//(Bx-Ax)
print (M)
input(stdln)
-10, 7,
2, 4,
your output
-2
expected output
-1.75
but when I make it a float it'll add unnecessary ".0" to whole numbers which will fail test case
Ax, Ay = input ().split()
Bx, By = input ().split()
Ax=float (Ax)
Ay=float (Ay)
Bx=float (Bx)
By=float (By)
M=(By-Ay)/(Bx-Ax)
print (M)
input(stdln)
-4, 0,
0, 20,
your output
5.0
expected output
5
you could do a little check before printing. if the result is equal to the integer of result, then it is an integer, else float.
Ax, Ay = input().split()
Bx, By = input().split()
Ax = float(Ax)
Ay = float(Ay)
Bx = float(Bx)
By = float(By)
M = (By-Ay)/(Bx-Ax)
M = int(M) if M==int(M) else float(M)
print(M)
When you make arithmetic operations on a float in python, your result will also be a float type.
If you want to remove the decimals on your result and make it an integer, simply use the int() function.
M=int((By-Ay)/(Bx-Ax))
This converts your result to an integer type and gets rid of the decimals.

cannot unpack non-iterable float object

Whenever I run my code I keep getting the error of "cannot unpack non-iterable float object", I'm confused on where the error is coming from, do I have to use the iterating variable in some way?
def DEADBEEF(n):
count = 0
for i in range(n):
x ,y = np.random.uniform(0,1)
if (np.sqrt(x**2 + y**2)<=1):
count = count + 1
answer = count/100
return answer
holder = DEADBEEF(100)
np.random.uniform returns a single float as long as you don't pass the size parameter.
If you want to use x, y = ..., you must supply at least two values on the right side of the assignment.
If you want to assign a float to both x and y using np.random.uniform, try using the size parameter:
x, y = np.random.uniform(0, 1, size=2)

Unpack error in a function that converts float to binary

I am trying to make a Python function that takes a float number, and converts it to a string with its binary (considering the fractional part too, separated by a dot), but for some values ​-such as 0.5, 0.25, 0.10, 0.05 , 0.05, ...- it gives the following error:
line 7, in floatToBinary integerPart, fractionalPart = str((convertDecimal(fractional))*2).split(".")
ValueError: Not enough values ​​to unpack (expected 2, got 1)
Functions:
def floatToBinary(floatNumber, decimalPlaces):
    integerPart, fractionalPart = str(floatNumber).split(".")
    integerPart = int(integerPart)
    fractionalPart = int(fractionalPart)
    result = bin(integerPart).lstrip("0b") + "."
    for i in range(decimalPlaces):
        integerPart, fractionalPart = str((convertDecimal(fractionalPart))*2).split(".")
        fractionalPart = int(fractionalPart)
        result += integerPart
    return result
def convertDecimal(n):
    while n > 1:
        n /= 10
    return n
Hope you can help me.
The function convertDecimal returns 0 when n = 0. So there is no '.' to split.
You can fix that by casting the return value as float
def convertDecimal(n):
while n > 1:
n /= 10
return float(n)

Split a Decimal number into a random array where the sum of the numbers equals the split number

I want to split a decimal number into a random table where the sum of the elements in the array equals the original number
# Call a function which receives a decimal number
from decimal import Decimal
from something import split_random_decimal
split_decimal = split_random_decimal(Decimal('10.00'))
print(split_decimal)
# Output: [1.3, 0.7, 1.2, 0.8, 1.0, 1.5, 0.5, 1.9, 0.1, 1.0]
print(sum(split_decimal))
# Output: Decimal('10.00') - The original decimal value
Has anyone an idea how I could do this in pure Python without using a library?
Solved!
Thks for all who have help me, the final beautiful code who saved my life is this:
import random
def random_by_number(number, min_random, max_random, spaces=1, precision=2):
if spaces <= 0:
return number
random_numbers = [random.uniform(min_random, max_random) for i in range(0, spaces)]
increment_number = (number - sum(random_numbers)) / spaces
return [round(n + increment_number, precision) for n in random_numbers]
number = 2500.50
spaces = 30
max_random = number / spaces
min_random = max_random * 0.6
random_numbers = random_by_number(number, min_random, max_random, spaces=spaces, precision=2)
print(random_numbers)
print(len(random_numbers))
print(sum(random_numbers))
You could start with something like:
numberLeft = 10.0
decList = list()
while numberLeft > 0:
cur = random.uniform(0, numberLeft)
decList.append(cur)
numberLeft -= cur
This implementation would choose higher random numbers at first which wouldn't be that hard to logically change.
numberLeft will never hit exactly 0 so you could do something with rounding. You could also wait for numberLeft to get low enough and that would be your last random number in the list.
The problem is a little under defined: into how many pieces should it be split and how large may any piece be? Should the values only be positive? An approximate solution from what you've said would be to pick a random number of pieces (defaulting to 10) and making the values be distributed normally about the average size of the pieces with a standard deviation of 1/10 of the average:
from decimal import Decimal
def split_random_decimal(x, n=10):
assert n > 0
if n == 1:
return [x]
from random import gauss
mu = float(x)/n
s = mu/10
if '.' in str(x):
p = len(str(x)) - str(x).find('.') - 1
else:
p = 0
rv = [Decimal(str(round(gauss(mu, s), p))) for i in range(n-1)]
rv.append(x - sum(rv))
return rv
>>> splited_decimal = split_random_decimal(Decimal('10.00'))
>>> print(splited_decimal)
[Decimal('0.84'), Decimal('1.08'), Decimal('0.85'), Decimal('1.04'),
Decimal('0.96'), Decimal('1.2'), Decimal('0.9'), Decimal('1.09'),
Decimal('1.08'), Decimal('0.96')]
I think this is what you're looking for:
import random as r
def random_sum_to(n, num_terms = None):
n = n*100
num_terms = (num_terms or r.randint(2, n)) - 1
a = r.sample(range(1, n), num_terms) + [0, n]
list.sort(a)
return [(a[i+1] - a[i])/100.00 for i in range(len(a) - 1)]
print(random_sum_to(20, 3)) # [8.11, 3.21, 8.68] example
print(random_sum_to(20, 5)) # [5.21, 7.57, 0.43, 3.83, 2.96] example
print(random_sum_to(20)) # [1 ,2 ,1 ,4, 4, 2, 2, 1, 3] example
n is the number in which you are summing to, and num_terms is the length of the string you would like as a result. Also if you look at the last example you can see that if you don't want to specify a "num_terms" you don't have to and it will do that for you!

Pandas:Aggregate by numerical column name and give error when substitution

In order to eliminate variations at the time of measurement, I want to compile in a specific range.
For example, I want to sum the column name in the range of ± 0.1 of the integer and assign it to an integer column. However, I can not substitute because of a shape error.
I think that it is caused by converting the type of the column, but what should I do about it?
Thank you.
import pandas as pd
import numpy as np
df = pd.DataFrame(data= np.arange(0,10000,1).reshape(100,100))
df.columns = np.arange(0,10,0.1)
print(df.head())
df.columns = df.columns.astype(float)
temp = df.columns.values
for n in np.arange(1, 9, 1):
l = n - 0.1
m = n + 0.1
calc_n = temp[np.where((temp >= l) & (temp <= m))]
calc = np.sum(df[df.columns.intersection(calc_n)], axis=1)
n_position = temp[np.where(temp == n)]
df[n_position] = calc.values
ValueError: shape mismatch: value array of shape (100,) could not be broadcast to indexing result of shape (1,100)
The ValueError is because n_position is an array. So df[n_position] gives you a dataframe instead of a column.
It is usually not a good idea to use floats as indexes. And you should be careful when comparing floats. This line calc_n = temp[np.where((temp >= l) & (temp <= m))] won't always give accurate results.
For starter, try:
for n in np.arange(1, 9, 1):
margin = 0.101 # set your own margin
calc_n = np.where(np.abs(temp-n) < margin)
df[n] = df.iloc[:,calc_n[0]].sum(axis=1)

Categories

Resources