This is a really basic question for dictionaries from one of the exercises. The question is :
Write a Python script to generate and print a dictionary that contains a number (between 1 and n) in the form (x, x*x).
This here is my code:
import random
def dict_generate():
n = int(input("Please enter an integer:"))
dic = {}
for x in range(n):
num = random.randrange(1,n)
key = num
value = num*num
dic[key] = value
print(dic)
dict_generate()
However, when I run it, it seems to skip over a few iterations, so the end result is that I get a dictionary with lesser values in it that the number I entered. For example, I entered 5, but instead of 5 sets of keys and values, my output was this:
{3: 9, 1: 1, 2: 4}
Running this code through python tutor, the problem seems to be that the values are not being inserted into the dictionary. I can't seem to understand why. If someone could explain it would be really helpful thanks.
(I am aware that there are many other ways to complete this question but I'm trying to understand where I went wrong.)
num = random.randrange(1,n)
key = num
Since you use the key as a random number it may come again and again the same number for the key so your dictionary has less than 5 keys.
Related
class Solution:
def firstRepeated(self,A, n):
#arr : given array
#n : size of the array
D={}
for i in range(n):
if A[i] not in D:
D[A[i]]=[i]
else:
D[A[i]].append(i)
c=0
for i in D:
if(len(D[i])>1):
c+=1
return (D[i][0]+1)
if(c==0): return -1
A=[1 ,5 ,3, 4, 3, 5, 6]
n=len(A)
M=Solution()
print(M.firstRepeated(A,n))
this is a problem from geeks for geeks.
" Given an array arr[] of size n, find the first repeating element. The element should occurs more than once and the index of its first occurrence should be the smallest"
the index positions(returned) are assumed to start from 1. If there is no
such element that has frequency more than 1 , we gotta return -1
This code is actually working correctly in VS code, but whenever I use
it in GFG IDE, it's failing(shows 3 as output instead of 2)
Kindly help, as I have no idea what's wrong here.
Your code is returning the index of the repeating element based on the order that keys are stored in the dictionary. After having collected all values in a dictionary keyed by number, your code iterates that dictionary like this:
for i in D:
The order in which this loop will visit the dictionary keys (indexes), depends on the Python version. See Are dictionaries ordered in Python 3.6+?.
At the time of writing Geeks for Geeks uses version 3.5.2, and so the order the keys are visited is undefined, which means that sometimes your function will not return the expected answer on their web site, while on your own environment it will always be correct (if you have a more recent version).
Correction
You can change your code so it does not rely on the order of the dictionary. Instead, during insertion, check which is the dictionary key with the least value. Here is your code corrected just with that change in mind:
class Solution:
def firstRepeated(self,A, n):
D = {}
c = len(A)
for i in range(n):
if A[i] not in D:
D[A[i]] = i # No need to maintain a list
elif D[A[i]] < c: # When the dupe's first index is earlier...
c = D[A[i]]
if c == len(A):
return -1
return c + 1
This will do the trick.
I checked in https://www.onlinegdb.com/online_python_compiler and works correctly.
it works also in https://ide.geeksforgeeks.org/
Let's say I wanted to add all items in a list. One of the issues is, this list can go on forever. Here's an example:
a = 0
lst = [int(0)]
ItemsInList = int(input("How many items do you want in this list? "))
while a != ItemsInList:
a + 1
Item = int(input("What should item", a, "be? "))
lst.append(Item)
Now I want to add all those together. I cannot do print(lst[0] + lst[1] + lst[2] + lst[3] etc etc.. because if I were to do that and the list were to have more items then 3 I wouldn't have added the whole list. If I were to just do that again and again and again until it reached lst[500] I would get an error because that item probably wont exist most of the time. I'm thinking of making a while command inside the print() but I can't figure out if that is possible or not. Any ideas of simplifying that code or just helping me with the actual issue would be much appreciated. This is to make a mean average calculator by the way.
To add all the items in a list, just use the sum method, like this:
lst = [1,2,3]
print(sum(lst))
Output:
6
But instead of appending all the inputs to a list, you can have a running total, like this:
total = 0
for a in range(ItemsInList):
Item = int(input("What should item", a, "be? "))
total += Item
This would work faster than the code that you're using currently.
Apart from that, there are many flaws in your code, like:
a+1. You did not assign the resulting value to a, so the loop would be infinite. It should instead be a += 1 or a = a+1
Using a while loop when you know how many times you want to execute the loop.
lst = [int(0)]. This isn't wrong, but this isn't the right way either to initialize a list. You can do it like this: lst = []
Make sure that you don't repeat these mistakes! Hope that this helps!
That's my first question, I'm new at programming, sorry about any inconvinience !
I need to finish an exercise that consists in create a fuction to find the higher number and another function to find the lower number on a List, but when I print the results, it keeps giving me a wrong answer.
Here is my code:
lista_numeros = [1593, 200, 72, 8, 423, 2, 39, 293, 20120]
def menor_numero(arg1):
colector1 = arg1[0]
print(coletor1) # - Checking value added to COLECTOR1
for a in range(len(arg1)):
print(arg1[a]) # - Checking if the A argument is running through the list.
if colector1 < arg1[a]:
colector1 = arg1[a]
return colector1
resultado2 = menor_numero(lista_numeros)
print("menor ", str(resultado2)) # Result is the last position of the list, must be the 6th position.
Thank you very much.
Fist of all indentation is very important in python to tell it the order to execute your code and also to define where code sits within a loop etc.
Now you say you want to make a function that finds the smallest and largest number from the output of another function, for this I will assume this output is a list.
Please see code below with comments.
Mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9] #assume this is output from other funtion
def func(alist): #define function
collector1 = 100 #keeping your collector idea
for i in alist: #iterate through input
if i < collector1: #check if the item you are currently looking at is smaller than the item currently stored in collector
collector1 = i #if is smaller overwitre colletor with new item
print(collector1) #after iterating through all items in input print final value of colletor
func(Mylist) #call function with input
This outputs,
1
Simply change this,
if i > collector1:
And it will now find the largest in input, so output is now.
9
Edit: if you are looking for the smallest number start collector1 at a large number, if you are looking for the largest start collector1 at = 1.
assuming your input is a list and not a string or some sort you can just use the min()/max() methods:
myList = [1,2,3,4,5]
print(max(myList)) >> 5
print(min(myList)) >> 1
you can find more info here :
https://www.tutorialspoint.com/python3/list_max.htm
https://www.tutorialspoint.com/python3/list_min.htm
Your function is finding the maximum instead of the minimum value. Changing the < to > should do what you want.
Python also has builtin methods min() and max() which should do what you want.
#! python3
import random
numbers = []
max = 1000
min = 0
for i in range(40):
numbers.append(random.randint(min,max))
maxNum = min
minNum = max
for num in numbers:
if num > maxNum:
maxNum = num
elif num < minNum:
minNum = num
print(maxNum, minNum)
This is my code, I use the random library in python to generate a random list of numbers, then I set max to equal the maximum number in that list.
The following for loop generates 40 random numbers and appends them to my list.
I then set maxNum to equal zero, so everything will be greater than it, thereby the initial value will not influence the outcome, and then I set minNum to equal max, so every number will be less than it.
The last block of code loops through the numbers list, and compares every number with the current maxNum and minNum variables to see whether that number is greater than the max or less than the min. If it is, the maxNum (or minNum) number will be updated and the code will move on to the next number.
The last statement prints or minimum and maximum values.
I don't know what course you are taking, but I would advise you to familiarize yourself with this code and understand what it is doing, as it's pretty basic and the stuff you encounter in the future will be much harder.
I have a program that returns a set of ages inside of an array and I want to count them and put them inside of a dictionary, I have tried the following but no results. Please help!
let's say I have an array as follows:
ages = [20,20,11,12,10,11,15]
# count ages inside of array, I tried this
for i in set(ages):
if i in ages:
print (ages.count(i))
# result returns the following
1
2
1
1
2
this makes perfect sense as if we look at the set(ages) it equals = {10,11,12,15,20}
so the returning count actually equals to the count of each value in ages
When I try to put in a variable though, it only appends the first number or it says it is not iterable!
How can I store it into a list, even better how can I make dictionary containing the set(ages) and the count for each of the set(ages)
Thank you
try this!
ages = [20,20,11,12,10,11,15]
dic = {x:ages.count(x) for x in ages}
print dic
There are a lot of different ways to achieve this. The first, and likely easiest, is to import the Counter class from collections.
from collections import Counter
ages = [20,20,11,12,10,11,15]
counts = Counter(ages)
# Counter({10: 1, 11: 2, 12: 1, 15: 1, 20: 2})
# if you want to strictly be a dictionary you can do the following
counts = dict(Counter(ages))
The other way is to do it in a loop:
counts = {}
for a in ages:
# if the age is already in the dicitonary, increment it,
# otherwise, set it to 1 (first time we are seeing it)
counts[a] = counts[a] + 1 if a in counts else 1
And finally, dict comprehension. It has really no advantage over the loop other than the fact that it's a single line. You still end up iterating over each variable in the list:
counts = {a:ages.count(a) for a in ages}
Since you asked more about the ternary operator, that loop is equivalent to saying:
counts = {}
for a in ages:
# if the age is already in the dicitonary, increment it,
# otherwise, set it to 1 (first time we are seeing the number)
if a in counts:
counts[a] = counts[a] + 1
print("Already seen", a, " -- ", counts[a])
else:
counts[a] = 1
print("First time seeing", a, " -- ", counts[a])
The ternary operator allows us to complete this pattern in a single line. Lots of languages have it:
C/C++/C#
JavaScript
If you need to store counts, better you use Python dicts.
ages = [20,20,11,12,10,11,15]
age_counts={} #define dict
for i in ages:
#if age_counts does not have i, set its count to 1
#increment otherwise
if not age_counts.has_key(i):
age_counts[i]=1
else:
age_counts[i]+=1
#you can now have counts stored
for i in age_counts:
print i, age_counts[i]
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
What is a method, in python, that can be used to read the largest number in a list? My attempt is below:
list = [a, b, c, d, e, f, g, h, i, j]
print max(list)
EDIT (Solution): Use a for loop.
userInput = []
for i in range(10):
userInput.append(int(input("Enter a number")))
print(max(userInput))
You can use a loop if you want to do something repeatedly. You want to have an empty list, and then get a number from the user 10 times, so you put all of the requests for a number from the user in a loop. input gives you a string, so you need to convert it to an int.
user_inputs = []
for i in range(10):
user_inputs.append(int(input("Enter a number")))
print(max(user_inputs))
If you don't understand loops, you should look into learning about them.
I think along with JHobern, you could probably do something like
print(max([int(raw_input("Enter a number: ")) for x in range(10)]))
That should do it!
To explain, you know what print and max should do.
raw_input asks the user for an input and stores it.
max() returns the maximum value in a list of things.
[ ______ for x in range(10)] is a list comprehension where it does something 10 times. Doesn't necessarily use the variable x in this case though.
So basically, I'm using list comprehension to create a list of 10 integers that is provided y the user and then prints out the maximum all in one line :)
You can use a while loop to achieve this:
This code will prompt the user 10 times to input numbers. Each time the number will be appended to the list nums. Also, each time the highest number in nums will be printed.
nums = []
while len(nums) < 10:
nums.append(int(input('Enter a number: ')))
print (max(nums))
If you only want to print the highest number at the end, one time, after the 10th input, then you can do this:
nums = []
while len(nums) < 10:
nums.append(int(input('Enter a value: ')))
print (max(nums))
You shouldn't use list as a variable because list is a built in function