Python List Problem

Python list problem

This is by design. When you use multiplication on elements of a list, you are reproducing the references.

See the section "List creation shortcuts" on the Python Programming/Lists wikibook which goes into detail on the issues with list references to mutable objects.

Their recommended workaround is a list comprehension:

>>> s = [[0]*3 for i in range(2)]
>>> s
[[0, 0, 0], [0, 0, 0]]
>>> s[0][1] = 1
>>> s
[[0, 1, 0], [0, 0, 0]]

Python list problem : want to get the data only and remove the title of the field

Try print(int(list1[0]["a"]))

Python problem with list - removing duplicates

Try this. Let me know if this works

names = ['Bob','Kenny','Amanda','Bob','Kenny']
unique_names = list(set(names))

print(unique_names)

It took me 45 minutes to answer this python list question. What is a simpler method?

You just need to do this step by step. Grab the input:

num = input()

Split it into words and convert them all to floats:

vals = [float(k) for k in num.split()]

Now we have a list of floats. Find the largest:

maxval = max(vals)

Divide them all by that value:

for i in range(len(vals)):
vals[i] /= maxval

Print them:

for i in vals:
print( "{:.2f}".format(i), end=' ')
print()

Problem in creating a 2D list with n rows in python

[] * n duplicates the elements present inside the list. Since your list is empty, [] * n evaluates to [].

Additionally, [[]] * n will yield [[],[],[],[],[] for n = 5, but attempting to append an element to any of the inner lists will cause all the lists to contain the same element.

>>> L = [[]]* 5
>>> L[0].append(1)
>>> L
[[1], [1], [1], [1], [1]]

This is due to the fact that each element of the outer list is essentially a reference to the same inner list.

Therefore, the idiomatic way to create such a list of lists is

L = [[] for _ in range(n)]

Trouble with list slicing and inserting an item in a specific position on a list

this will flatten your list of list. hope it helps.

l = ['_T', 'T_', ['__T', '_T_'], ['_T_', 'T__']]

flat_l = []
for item in l:
if isinstance(item, str):
flat_l.append(item)
else:
for j in item:
flat_l.append(j)


print(flat_l)
#['_T', 'T_', '__T', '_T_', '_T_', 'T__']

Subset sum problem for a possible closest value to the target sum in Python for a really big list

You can use integer linear programming where each variable is a binary that corresponds to a number and represents whether that number is included in the result. It solves two problems, the first approaching the target value from below and the second from above and then takes the best solution. The following is an example implementation using PuLP:

import numpy as np
from pulp import LpMaximize, LpMinimize, LpProblem, lpSum, LpVariable

rng = np.random.default_rng(seed=0)
numbers = rng.integers(1, 10**6, size=10**4)
target = int(numbers.mean() * rng.normal(loc=1, scale=0.1))

indices = range(len(numbers))
variables = LpVariable.dicts("Choice", indices, cat="Binary")

leq_prob = LpProblem('leq', LpMaximize)
geq_prob = LpProblem('geq', LpMinimize)

leq_prob += lpSum([variables[i]*numbers[i] for i in indices]) <= target
leq_prob += lpSum([variables[i]*numbers[i] for i in indices])

geq_prob += lpSum([variables[i]*numbers[i] for i in indices]) >= target
geq_prob += lpSum([variables[i]*numbers[i] for i in indices])

leq_prob.solve()
leq_choices = [numbers[i] for i in indices if variables[i].value() == 1]

if sum(leq_choices) == target:
solution = leq_choices
else:
geq_prob.solve()
geq_choices = [numbers[i] for i in indices if variables[i].value() == 1]

solution = (
leq_choices
if target-sum(leq_choices) <= sum(geq_choices)-target
else geq_choices
)

print(f'Solution: {solution}')
print(f'Sum: {sum(solution)} (target: {target})')

two sum leetcode question in python using list comprehension

The nums in your code will be list[list] like [[0, 1]]. So what they want is list like [0, 1]

nums = [2, 7, 11, 15]
target = 9
nums = [[i,j] for i in range(len(nums)) for j in range(i, len(nums)) if nums[i]+nums[j] == target and i != j][0]
print(nums)


Related Topics



Leave a reply



Submit