Python - AttributeError: 'int' object has no attribute 'randint' - random

As part of a python course I am doing one of the tasks is to generate a random number between 1 and 10 100,000 times and count how many times each number occurs. Here is the code I have written for this task:
import random
one = 0
two = 0
three = 0
four = 0
five = 0
six = 0
seven = 0
eight = 0
nine = 0
ten = 0
count = 0
while count < 100000:
random = random.randint(1, 10)
if random == 1:
one += 1
elif random == 2:
two += 1
elif random == 3:
three += 1
elif random == 4:
four += 1
elif random == 5:
five += 1
elif random == 6:
six += 1
elif random == 7:
seven += 1
elif random == 8:
eight += 1
elif random == 9:
nine += 1
else:
ten += 1
count += 1
print("1 occured " + str(one) + " times")
print("2 occured " + str(two) + " times")
print("3 occured " + str(three) + " times")
print("4 occured " + str(four) + " times")
print("5 occured " + str(five) + " times")
print("6 occured " + str(six) + " times")
print("7 occured " + str(seven) + " times")
print("8 occured " + str(eight) + " times")
print("9 occured " + str(nine) + " times")
print("10 occured " + str(ten) + " times")
However I get an AttributeError saying:
Traceback (most recent call last):
File "J:/Python/Extension Task - Random Numbers.py", line 19, in <module>
random = random.randint(1, 10)
AttributeError: 'int' object has no attribute 'randint'
I've tried changing the title so that it doesn't include the word random and it still doesn't work, I've spent much longer than is healthy looking for solution to no avail.

You have named one of your variables random, which is shadowing the name of the module you're trying to use:
random = random.randint(1, 10)
After this line, random is your random number, not the random module. Use a different name for this variable!

Related

How would i add a leaderboard to this code?

a picture of my task
Im a GCSE student whose trying to learn python. Im confused to how i would add a leaderboard to this code, i've tried a number of time but it isn't working. I've included a picture of the task i'm supposed to do. Heres the code. I've never made a leaderboard before so i don't know how to start it.
from random import randint
import time
count = 0
num = 0
integer = 0
score = 0
print("Welcome to the Multiplication Test")
first_name = input("Please enter your first name: ")
second_name = input("Please enter your surname: ")
Username = first_name[0:3].lower() + second_name[0:3].upper()
print("Your username is: " + Username)
print("Please write in capital letters either: -EASY- -STANDARD- -HARD-")
difficalty = input("")
if (difficalty == "EASY"):
print("Easy mode has been selected")
print("There will be 10 questions for you to answer")
start = input("Press enter to start the game")
print("the timer has started")
begin = time.time()
while count < 10:
x = randint (1, 10)
y = randint (1, 10)
print ("The multiplication problem is ",x, "*", y)
a = int (input ("What is your guess?"))
count = count + 1
if a == x*y:
print ("That is correct.")
end = time.time()
score = score + 1
else:
print ("That is not correct. The correct answer is",x*y)
elapsed = end - begin
elapsed = int(elapsed)
print("You got " + str(score) + " out of 10 and it took you " + str(elapsed) + " seconds")
elif (difficalty == "STANDARD"):
print("Standard mode has been selected")
print("There will be 10 questions for you to answer")
start = input("Press enter to start the game")
print("the timer has started")
begin = time.time()
while num < 10:
x = randint (2, 12)
y = randint (2, 12)
print ("The multiplication problem is ",x, "*", y)
b = int (input ("What is your guess?"))
num = num + 1
if b == x*y:
print ("That is correct.")
end = time.time()
score = score + 1
else:
print ("That is not correct. The correct answer is",x*y)
elapsed = end - begin
elapsed = int(elapsed)
print("You got " + str(score) + " out of 10 and it took you " + str(elapsed) + " seconds")
elif (difficalty == "HARD"):
print("Hard mode has been selected")
print("There will be 10 questions for you to answer")
start = input("Press enter to start the game")
print("the timer has started")
begin = time.time()
while integer < 10:
x = randint (3, 15)
y = randint (3, 15)
print ("The multiplication problem is ",x, "*", y)
c = int (input ("What is your guess?"))
integer = integer + 1
if c == x*y:
print ("That is correct.")
end = time.time()
score = score + 1
else:
print ("That is not correct. The correct answer is",x*y)
elapsed = end - begin
elapsed = int(elapsed)
print("You got " + str(score) + " out of 10 and you took " + str(elapsed) + " seconds")
You could make a leaderboard as a list of username, score tuples:
# start of program
easy_leaderboard = []
# when printing the scores
easy_leaderboard.append((username, score))
# to print the leaderboard
for username, score in sorted(easy_leaderboard, key=lambda t: -t[0]):
print(f"{username): {score}")
Incidentally, rather than writing out the same code three times, you could abstract it:
def run_game(difficulty_name, range_min, range_max, username, leaderboard):
print(f"{difficulty_name.title()} mode has been selected")
print("There will be 10 questions for you to answer")
start = input("Press enter to start the game")
print("the timer has started")
begin = time.time()
while count < 10:
x = randint (range_min, range_max)
y = randint (range_min, range_max)
print ("The multiplication problem is ",x, "*", y)
a = int (input ("What is your guess?"))
count = count + 1
if a == x*y:
print ("That is correct.")
end = time.time()
score = score + 1
else:
print ("That is not correct. The correct answer is",x*y)
elapsed = end - begin
elapsed = int(elapsed)
print("You got " + str(score) + " out of 10 and it took you " + str(elapsed) + " seconds")
leaderboard.append((username, score))

Ways to Create a Number with Sum of Ones and Twos

I am wondering if there is a way to count the possible ways to sum a number using only ones and twos
For example:
We have the number 10. The number 10 can be summed by:
1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1
1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 2
2 + 2 + 2 + 2 + 2
etc...
Thank you all in advance!
If the order of elements does not matter, as the comments explain (i.e. 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 2 is identical to 2 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1), this is simply choosing the number of elements in the summation, which can be anywhere between 5 to 10. Once the number of elements is chosen, you know exactly how many of them have to be 1s and how many of them have to be 2s: For x elements, there are 10-x 2s, and the rest are 1s.
Since there are 6 numbers to choose from, this is the number of ways to create 10.
Rather than going into complex mathematical formulas, I would recommend DP approach.
int arr[N+1]; // Represents no. of ways to produce a number at index 1
// Like arr[5] is no. of ways to produce number 5
for(int i=0;i<=N;i++) {
arr[i] = 1; // As all 1s
}
for(int i=2;i<=N;i++) {
// if we add 2 now, check for no. of ways i-2 can be made,
// add it to current arr[i] value.
arr[i] += arr[i-2];
}
cout<< (arr[N]); // print
Number of ways to create a number using only ones = 1
Number of ways to create a number using at least one two = floor(n/2)
Total = 1 + floor(n/2)
See javascript code snippet below:
let numWays = n => 1 + Math.floor(n/2);
for (let i=1; i<=20; i++)
console.log("Number of ways to create " + i + " is: " + numWays(i));

Analyzing a recursive algorithm

I'm trying to figure out this algorithm that accepts an input of an int and should return an output of the sum of each element in the int.
# Input -> 4321
# output -> 10 (4+3+2+1)
def sum_func(n):
# Base case
if len(str(n)) == 1:
return n
# Recursion
else:
return n%10 + sum_func(n/10)
When Trying to break apart this algorithm this is what I come up with
1st loop -> 1 + 432 = 433
2nd loop -> 2 + 43 = 45
3rd loop -> 3 + 4 = 7
4th loop -> 4 + 4 = 8
How was it able to come up with the result of 10?
Unwinding, it would look like this:
sum_func(4321)
= 1 + sum_func(432)
= 1 + 2 + sum_func(43)
= 1 + 2 + 3 + sum_func(4)
= 1 + 2 + 3 + 4
When trying to understand recursion you'll have to clearly understand what is returned.
In this case function sum_func(n) returns the sum of the digits in it's argument n.
For concrete n task is divided into last_digit_of_n + sum_func(n_without_last_digit).
For example,
sum_func(4321) =
sum_func(432) + 1 =
sum_func(43) + 2 + 1 =
sum_func(4) + 3 + 2 + 1 =
4 + 3 + 2 + 1
Hope this helps.
(As a side note, checking if n has more than one digit using str is a bad idea. Better just to check if n <= 9)
You must reach the base case before the summation occurs:
Iteration 1: 1 + sum_func(432)
Iteration 2: 1 + 2 + sum_func(43)
Iteration 3: 1 + 2 + 3 + sum_func(4) = 1 + 2 + 3 + 4 = 10

Ruby not incrementing number

I wrote code to find how many operations a number required under the Collatz Conjecture. However, my operations variable doesn't seem to be incrementing.
My code is:
puts "Please input a number"
number = gets.chomp
number = number.to_i
operations = 0
modulo = number % 2
while number =! 1
if modulo == 0
number = number / 2
operations = operations + 1
elsif modulo =! 0 && number =! 1
number = number * 3
number = number += 1
operations = operations + 2
else
puts "Uh oh, something went wrong."
end
end
puts "It took #{operations} operations!"
I am running this code on https://www.repl.it.
First of all, it's elsif; not elseif (I edited that in your question). And unequal sign is !=; not =!. But that has a somewhat different meaning. (i.e.: number =! 1 means number = !1)
In the 12th line, what is number = number += 1? I think you meant number += 1 or number = number + 1.
Now, the code works. :)
Here's the final version.
puts "Please input a number"
number = gets.chomp
number = number.to_i
operations = 0
modulo = number % 2
while number != 1
if modulo == 0
number = number / 2
operations = operations + 1
elsif modulo != 0 && number != 1
number = number * 3
number = number + 1
operations = operations + 2
else
puts "Uh oh, something went wrong."
end
end
puts "It took #{operations} operations!"
Usage:
Please input a number
256
It took 8 operations!
An optimal solution using functions:
def collatz(n)
if n % 2 == 0
return n / 2
else
return 3*n + 1
end
end
def chainLength(num)
count = 1
while num > 1
count += 1
num = collatz(num)
end
return count
end
puts "Please input a number"
number = gets.chomp
number = number.to_i
operations = chainLength(number)
puts "It took #{operations} operations!"
If you need more performance, read about dynamic programming and memoization techniques.

Total probability of a given answer of a given number of additions [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm doing C++, and I want to find out the simplest way to find the total probability of a given answer of a given number of additions.
For example, the given answer is 5, and the given number of additions is 4 (x+x+x+x). The total probability that I want to find is 4:
1) 1 + 1 + 1 + 2 = 5
2) 1 + 1 + 2 + 1 = 5
3) 1 + 2 + 1 + 1 = 5
4) 2 + 1 + 1 + 1 = 5
Another example, the given answer is 6, and the given number of additions is 4 (x+x+x+x). The total probability is 10:
1) 1 + 1 + 1 + 3 = 6
2) 1 + 1 + 3 + 1 = 6
3) 1 + 3 + 1 + 1 = 6
4) 3 + 1 + 1 + 1 = 6
5) 1 + 1 + 2 + 2 = 6
6) 1 + 2 + 2 + 1 = 6
7) 2 + 2 + 1 + 1 = 6
8) 2 + 1 + 1 + 2 = 6
9) 2 + 1 + 2 + 1 = 6
10) 1 + 2 + 1 + 2 = 6
I have absolutely no idea where to start
Here's a start for you.
Have a look at this table
1 2 3 4 5
+------------------
1 | 1 0 0 0 0
2 | 1 1 0 0 0
3 | 1 2 1 0 0
4 | 1 3 3 1 0
5 | 1 4 6 4 1
The number of summands is increasing from left to right, the total increases in rows, so e.g. there are 3 ways to sum 3 integers (greater than 0) for a total of 4 (namely 1+1+2, 1+2+1, 2+1+1).
With 4 additions and a result Y, if all numbers will be positive and nonzero and small enough (<100) you can easily at least bruteforce this... just cycle trough all numbers with 4x for cycles and if they sum up to Y increment number of permutations. Disadvantage is the complexity O(N^4) which will be very slow.
#include <iostream>
using namespace std;
int main()
{
int y = 6;
int perm = 0;
for(int a = 1; a < y; a++)
for(int b = 1; b < y; b++)
for(int c = 1; c < y; c++)
for(int d = 1; d < y; d++)
{
if((a+b+c+d)==y)
{
cout << a << " + " << b << " + " << c << " + " << d << " = " << y << endl;
perm++;
}
}
cout << "number of permutations: " << perm << endl;
}
This is not probability what you are trying to find, it's number of comibnations.
Looking at your examples, I assume that the number of numbers you are adding is fixed (i.e. 4), so every number is greater or equal to 1. We can do simple math here then - let's substract this number from both sides of the equation:
Original: 1) 1 + 1 + 1 + 2 = 5
Result of substracting: 1) 0 + 0 + 0 + 1 = 1
When the substraction is done, your problem is the combination with repetition problem.
The formulas you can find in the link I provided are quite simple. The problem can be solved using following code:
#include <iostream>
unsigned factorial(int n)
{
if (n == 1) return 1;
return n * factorial(n-1);
}
unsigned combinationsWithRepetition(int n, int k)
{
return factorial(n + k - 1) / (factorial(k) * factorial(n - 1));
}
unsigned yourProblem(unsigned numberOfNumbers, unsigned result)
{
return combinationsWithRepetition(numberOfNumbers, result - numberOfNumbers);
}
int main()
{
std::cout << yourProblem(4, 5) << std::endl;
std::cout << yourProblem(4, 6) << std::endl;
return 0;
}
Also, you can check this code out in online compiler.
Note that this code covers only the problem solving and could be improved if you choose to use it (i.e. it is not protected against invalid values).

Resources