Adding numbers in defined set and printing it in Python - python

I am trying to input the 5 numbers in defined length set and try to print out those numbers but it's giving "TypeError: 'int' object is not iterable" this error.
print("enter 5 numbers")
a=set(5)
for i in range(0,5):
a.append(int(input("enter a number")))
for i in range(0,5):
print("numbers in array are",a[i])

I think there is some confusion on what set actually does. I assume you want to make a predefined set of length 5. When doing:
set(5)
you get:
TypeError: 'int' object is not iterable
because you're trying to make a set containing only the integer 5. If you want to make a set from that, you would have to include an iterable, maybe like so:
set((5,))
Out: {5}
But what I would recommend you to do is declare
a = [] # create an empty list
and then run your code. At the end then, I would make a set by typing
a = set(a)
Hopefully that was helpful for you! Have fun coding! :)

You cannot fix the size of set while creating.
a = set(5) is the source of your error.
Also, sets do not have append method. You should use a.add("data") for adding elements to the set.
To ensure that the size of set does not exceed a particular length, you can try something like this
fixed_length = 3
a=set()
for i in range(0,5):
if len(a) == fixed_length:
break
else:
a.add(int(input("enter a number")))
for index, element in enumerate(a):
print("numbers in array are", element)

Related

Pick a random choice from a list in Python without repeating

I have a list lets say x = [8,6,4,1] I want to pick a random element from this list in Python but each time picking this item shouldn't be the same item picked previously. So I don't want a repetition
How can I do this ?
Use random package
import random
x = [8,6,4,1]
random.shuffle(x)
for number in x:
print(number)
One note here: shuffle doesn't return anything (well, None actually). Instead of returning a new list, it mutates it. That means that you're unable to use it into a loop declaration
for number in random.shuffle(x): # TypeError: 'NoneType' object is not iterable
print(number)
If you are using randrange to generate a random index, use a range smaller by 1, because there is one forbidden index. To convert the output of randrange to the needed range (with one number removed), conditionally add 1 to the number.
def random_choice_without_repetition(list x, int forbidden_index):
index = random.randrange(len(list) - 1)
if index >= forbidden_index:
index += 1
return index
This code returns an index instead of the element itself, because it wants to receive the forbidden index. You might want to adapt it to your use case to make it more convenient.
You can do this by just shuffling the list and picking the first item until list length > 0.
import random
x = [8,6,4,1]
y = range(len(x))
random.shuffle(y)
Now each time you want to pick a random element do:
print(x[y.pop()])

Create a new list with changes of value of a previous list

I have a list with floats, for example
numbers = [1000.45,1002.98,1005.099,1007.987]
I want to create a new list containing the deltas of the value in numbers - i.e. I want the difference between numbers[0],[numbers[1] to be the first value in a new list. So the first number in my new list should be 2.53, the second should be 2.119, and so forth.
I tried list comprehension
newnumbers= [i[-1] - i[-2] for i in numbers]
but it gives a TypeError
TypeError: 'float' object is not subscriptable
I tried converting the list to integers, but then it gives the same type of error.
How can I create my desired list?
It's easy with Pandas, use diff():
import pandas as pd
pd.Series(numbers).diff()
0 NaN
1 2.530
2 2.119
3 2.888
dtype: float64
You've got the right idea, but just haven't quite got the syntax right. You should use:
newnumbers = [(numbers[i] - numbers[i-1]) for i in range(1, len(numbers))]
In your version you're trying to index a number, but you need to index your list instead.
newnumbers = []
for i in range(1,len(numbers)-1):
newnumbers.append(numbers[i]-numbers[i-1])
for i in numbers i is equal to 1000.45 in the first loop, then 1002.98 etc. So i[-1] = 1000.45[-1] which means nothing, you cannot subscriptable a float
numbers = [1000.45,1002.98,1005.099,1007.987]
newnumbers= [numbers[i+1]-numbers[i] for i in range(len(numbers)-1)]
print(newnumbers)
#[2.5299999999999727, 2.119000000000028, 2.88799999999992]
If you want 2 decimal points
newnumbers= [float("%0.2f"%(numbers[i+1]-numbers[i])) for i in range(len(numbers)-1)]
#[2.53, 2.12, 2.89]
Note how you access your elements directly, instead of using list indices;
The correct way to do the latter in Python would be
for index in range(len(numbers)):
What you are using is essentially the numbers themselves. Also, note that you would have to exclude the first index of your list, since you only want the differences (otherwise, the first call would look at the last index again, according to Python's behavior of calling mylist[-1]), which is why you can restrict your range to range(1,len(numbers)). In the form of a list comprehension, it would now work like this:
newnumbers = [numbers[i] - numbers[i-1] for i in range(1,len(numbers))]
Here is a method that doesn't require importing any modules:
numbers = [1000.45,1002.98,1005.099,1007.987]
sliced = numbers[1:]
answer = list(map((lambda x,y: y - x),sliced,numbers))
This gives:
[-2.5299999999999727, -2.119000000000028, -2.88799999999992]
You can then do:
final_answer = [round(x,2) for x in answer]
which gives:
[-2.53, -2.12, -2.89]
>>> numbers = [1000.45,1002.98,1005.099,1007.987]
>>> [round((y-x),2) for x,y in zip(numbers, numbers[1:])]
[2.53, 2.12, 2.89]

The TypeError in python

I'm trying to make a challenge for one of the courses I'm following. I'm new to programming, but I'm eager to learn.
Can you tell me in detail why this error occurs to me and how do solve it.
default_names =['Justin', 'john','Emilee', 'jim','Ron','Sandra','veronica','Wiskley']
i=0
for i in default_names:
default_names[i]=default_names[i][0].upper()
i+=1
if i==len(default_names):
break
print default_names
the error: TypeError: list indices must be integers, not str
default_names =['Justin', 'john','Emilee', 'jim','Ron','Sandra','veronica','Wiskley']
for i in range(len(default_names)):
default_names[i]=default_names[i].upper()
print default_names
What you are looking for is :
for i,s in enumerate(default_names):
or simple:
for i in range(len(default_names)):
The mistake you are doing is that when you say for i in default_names: notice that i value is a string, not int as you are trying to use.
for i in default_names:
print(i)
Will give :
OUT: Justin
john
Emilee
jim
Ron
Sandra
veronica
Wiskley
So the actual code should be, assuming you are trying to convert each string in list to Upper case :
for i in range(len(default_names)):
default_names[i]=default_names[i].upper()
EDIT : The OP wants only First char to be Upper case, and since string are immutable, change of code to :
for i in range(len(default_names)):
default_names[i]=default_names[i][0].upper() + default_names[i][1:]
As you can see in your error: TypeError: list indices must be integers, not str. It's because to access the elements of a list, you have to use the index, which is an integer. Basing on the structure of your code, you might have come from a different language. Python's for loop is different from the other languages. It doesn't increment the variable you made over the loop, but rather it iterates over the elements and passes the value to the variable. I think it would be more suitable to use a while loop with the code you made since you have initialized your i to 0. E.g.
default_names =['Justin', 'john','Emilee', 'jim','Ron','Sandra','veronica','Wiskley']
i=0
while i < len(default_names):
default_names[i]=default_names[i].upper() #removed the [0] here
i+=1
#removed the other codes here
print default_names
As you become better in python, you can find more efficient ways to do these kinds of things. The result you wanted could be simply made through
default_names = [name.upper() for name in default_names]
which simply iterates all of the names, makes it upper case and saves it back to default_names

how to loop through and get the last value

Hi i have the following code:
m= list()
for i in range (1,6):
set = base.Getentity(constants.ABAQUS,"SET",i)
m.append(set)
print(set)
and my result is
<Entity:0*17a:id:1>
<Entity:0*14g:id:2>
<Entity:0*14f:id:3>
<Entity:0*14a:id:4>
None
None
Here i have four elemnts in my set named set. Even though my code is written in ansa python, my question is very General
I would like to write a code which goes through the set and prints the last elemnt in my case
'<Entity:0*17a:id:4>'.
and aslo i dont want to use the range function so pls help me with writing the code.
I suggest you look at Iterators, that will help you loop through the list
If you don't want to use the range function, you can use xrange. It returns an xrange object, which is kind of like an iterator and generates the numbers on demand.
You are getting None as the last two values because there are no 'set' with the id 5 and 6 in your model
Use a filter before appending to the list m
m= list()
for i in range (1,6)
set = base.Getentity(constants.ABAQUS,"SET",i)
if set!=None:
m.append(set)
Now you can just call m[-1] for the last entity
hope this helps

I have two very simple beginner questions for Python

import random
wordlist = {'Candy', 'Monkey'}
level = 0
while level == 0:
number = random.randint(1, 2)
if number == 1:
print 'Candy'
secword = 'Candy'
level = 2
elif number == 2:
print 'Monkey'
secword = 'Monkey'
level = 2
for i in secword:
print i
I have a couple of questions about the code I just randomly wrote (I'm a beginner)
1) How do I assign a word in a list to a variable?
ex. assign the word 'Candy' into a variable because I always get the error (List is not callable)
2) How do I assign the variable i (in the for loop) to a separate variable for each letter?
Thanks! Tell me if it's not specific enough.
It should be pointed out that wordlist is not actually a list, but a set. The difference is that a set does not allow duplicate values, whereas a list does. A list is created using hard-brackets: [], and a set is created using curly-brackets: {}.
This is important because you can't index a set. In other words, you can't get an element using wordlist[0]. It will give you a 'set does not support indexing' error. So, before you try to get an element out of wordlist, make sure you actually declare it as a list:
wordlist = ['Candy', 'Monkey']
I'm not sure what you're asking in your second question. Can you elaborate?
You are getting List is not callable because you are probably using small brackets (). If you use small brackets, and do wordlist(0), you actually make interpreter feel like wordlist is a method and 0 is it's argument.
s = worldlist[0] # to assign "Candy" to s.

Categories