This is my script. How do i add so the loop ends if it has to run 500 times or more?
x=0
while x<=500:
def collatz(number):
if number % 2 == 0:
print(number // 2)
return number // 2
elif number % 2 == 1:
result = 3 * number + 1
print(result)
return result
n = input("Give me a number: ")
while n != 1:
n = collatz(int(n))
x=x+1
else:
print('Loop ended)
break
This is the collatz equation but it is not always sure that it ends up on 1. So I need to rewrite my program so that the loop ends if the number series will be longer than 500 numbers.
Related
Without using an array, I am trying to do this. what is wrong with my code?
n is the number of elements,a is the first element(assumed to be maximum initially), b stores new element every time and sec variable stores the second-largest element. Numbers are all positive. This is from an online contest.
#include<stdio.h>
int main() {
int i,a,b,max,n,sec;
scanf("%d",&n);
scanf("%d",&a);
max=a;
while(n-1!=0) {
scanf("%d",&b);
if(b>max) {
sec=max;
max=b;
}
else if(b<max && b>sec)
sec=b;
else{}
n--;
}
printf("%d",sec);
return 0;
}
getting wrong answers in some test cases( i don't know )
Consider sequence 2, 12, 10 (leaving out surrounding code):
int sec; // unitialised!!!
max = a; // 12
if(b > max) // b got 10, so false!
{
sec = max; // this code is not hit! (b remains uninitalised)
max = b;
}
else if(b < max && b > sec)
// ^ comparing against uninitialised
// -> UNDEFINED BEHAVIOUR
You need to initialise sec appropriately, e. g. with INT_MIN (defined in <limits.h>); this is the minimal allowed value, with 32-bit int that would be a value of -232 - 1, i. e. -2 147 483 648. Pretty unlikely anybody would enter that value, so you could use it as sentinel.
You even could initialise max with that value, then you woudn't need special handling for the first value:
int sec = INT_MIN, max = INT_MIN;
int n;
scanf("%d", &n); // you should check the return value, which is number of
// successfully scanned values, i. e. 1 in given case,
// to catch invalid user input!
// you might check value of n for being out of valid range, at very least < 0
while(n--) // you can do the decrement inside loop header already...
{
// keep scope of variables as local as possible:
int a;
// scanf and comparisons as you had already
// again don't forget to check scanf's return value
}
if(sec == INT_MAX)
{
// likely hasn't been modified -> error, no second largest element
}
else
{
// ...
}
Now what if you do expect user to give you the value of INT_MIN as input?
You could have a separate counter, initialised to 0, you increment in both of the two if branches inside the loop; if this counter is < 2 after the loop, you didn't get at least two distinct numbers...
Lets look at the input
2 4 3
Two is the number of inputs.
4 ends up in max.
3 ends up in b.
b is not greater than max, the if does not do anything.
b is less than max, but b is not necessarily greater than sec,
because sec at this point can be anything - whatever currently is inside that non-initialised variable. sec at this point is for example not guaranteed to be 0. So the else if does not trigger and we end up in else {}.
So we end up executing the printf() at the end of the program with a still uninitialised sec. And that is unlikely to satisfy the judge.
To solve the problem, you need to initialise sec. Initialising to 0 might work, but actually you need to use the lowest possible input value.
Since you chose int, instead of unsigned int, I assume that 0 is NOT the lowest possible value. But you would have to quote the assignment/challenge to allow determining the lowest possible value. So you need to find that out yourself in order to make a solution code.
Alernatively, you can analyse the first input values to initialise max and sec (need to watch them coming in until you get two distinct values; credits to Aconcagua).
Usually it is however easier to determine the lowest possible value from requirements or the lowest possible int value from your environment.
At some level of nitpicking, you need to know the lowest possible value anyway, in order to select the correct data type for your implementation. I.e. even with analysing the first two values, you might fail for selecting the most narrow data type.
In case you "successfully" (as judged by the challenge) use 0 to initialise sec, try the input 2 1 -1.
It should fail.
Then try to find in your challenge/assignment description a reason why using 0 is allowed. It should be there, otherwise find a different challenge site to improve your coding skills.
I liked how OP initialized max with the first input value.
This brought me to the idea that the same can be done for sec.
(The value of max is a nice indicator that sec could not be determined whatever max contains. In regular case, max and sec can never be equal.)
Hence, one possibility is to initialize max and sec with the first input
and use max != sec as indicator whether sec has been written afterwards at all.
Demo:
#include <stdio.h>
int main()
{
/* read number of inputs */
int n;
if (scanf("%d", &n) != 1 || n < 1) {
fprintf(stderr, "ERROR!\n");
return -1;
}
/* read 1st input */
int max;
if (scanf("%d", &max) != 1) {
fprintf(stderr, "ERROR!\n");
return -1;
}
--n;
int sec = max;
/* read other input */
while (n--) {
int a;
if (scanf("%d", &a) != 1) {
fprintf(stderr, "ERROR!\n");
return -1;
}
if (max < a) { sec = max; max = a; }
else if (sec == max || (sec < a && a < max)) sec = a;
}
/* evaluate result */
if (sec == max) {
puts("No second largest value occurred!\n");
} else printf("%d\n", sec);
/* done */
return 0;
}
Output:
$ gcc -std=c11 -O2 -Wall -pedantic main.c
$ echo -e "3 3 4 5" | ./a.out
4
$ echo -e "3 3 5 4" | ./a.out
4
$ echo -e "3 4 3 5" | ./a.out
4
$ echo -e "3 4 5 3" | ./a.out
4
$ echo -e "3 5 3 4" | ./a.out
4
$ echo -e "3 5 4 3" | ./a.out
4
$ # edge case:
$ echo -e "2 3 3" | ./a.out
No second largest value occurred!
Live Demo on coliru
I'm solving a factorial problem where the function takes a number and returns the factorial of that number.
The problem I'm running into is that the code works but I don't know why. There are no loops to call it back after the code is executed and I'm not even sure where the current value is being stored.If I am correct the I assume the function is re-running every time it hit the return and it is running with a value of n-1 so one number less than the previous time it ran, however, I still do not see how the value is getting stored to multiple each number by the current value. Even if I log the current value of n after every run all I get is the numbers 10 down to one. I would think the current value would change to the multiplied value.
Again this code works perfectly I just need to understand why.
function factorial(n) {
if (n === 0) {
return 1;
}
console.log(n);
return n * factorial(n - 1);
}
factorial(10);
What you have here is a recursive function - a function which calls itself. You also need to keep in mind the "scope" of the variables in the function.
The scope of the parameter "n" is local to the function. Every time the function is called, the new variable is created. The scope of each variable is the function execution.
1: function factorial(n) {
2: if (n === 0) {
3: return 1;
4: }
5: console.log(n);
6: return n * factorial(n - 1);
7: }
Example:
Parameter Value = 0
Hence, n = 0
Execute factorial(0)
1. line 1: variable n = 0
2. line 2: check if n = 0
3. line 3: return 1
Example:
Parameter Value = 2
Hence, n = 2
Execute factorial(2)
1. line 1: variable n = 2 (scope = execution #A)
2. line 5: console log n = 2
3. line 6: return 2 * factorial(2-1) // Function calls itself
4. line 1: variable n = 1 (scope = execution #B)
5. line 5: console log n = 1
6. line 6: return 1 * factorial(1-1) // Function calls itself
7. line 1: variable n = 0 (scope = execution #C)
8. line 3: return 1 // #C returns 1
9. return 1 * 1 // #B returns 1 * 1 (from #C)
10. return 2 * 1 // #A returns 2 * 1 (from #B)
Can anyone tell me the reason of getting 0 1 2 0 as output of below program?
#include <stdio.h>
main() {
e(3);
}
void e(int n) {
if(n>0) {
e(--n);
printf("%d",n);
e(--n);
}
}
Output is 0 1 2 0
Here' the flow of execution after e(3) is called from main.
e(3)
e(2)
e(1)
e(0) ... return
n is now 0
print n. results in output 0
e(-1) ... return
n is now 1
print n. results in output 1
e(0) ... return
n is now 2
print n. results in output 2
e(1)
e(0) ... return
n is now 0
print n. results in output 0
e(-1) ... return
return
And you see the output
0 1 2 0
I'm assuming the following is what you want:
#include <stdio.h>
void e(int);
int main()
{
e(3);
return 0;
}
void e(int n)
{
if(n > 0) {
e(--n);
printf("%d", n);
e(--n);
}
}
This is an example of a recursive function - a function calling itself. Here, at each call the parameter is decremented and the function is again called until the condition n > 0 is not met. Then, the printf("%d", 0) happens. Now the second e(--n) will have no effect until n is at least 2, since the if condition cannot be passed with a value of n less than 1. Further printf()s happen in the reverse order of the call as the function calls are removed from the stack. When the value gets to 2, the second e(--n) gets a chance to make an effect thus printing 0.
You need to learn about recursion (if you still haven't) and then you can get a good picture of how things happen. Also, it will help you if learn more about how the stack is set up when a function is called, and later returned.
The 'flow' goes as follows:
main -> e(3)
e(3) -> IF(3>0)
{
// n is pre-decremented to 2
e(2) -> IF(2>0)
{
// n is pre-decremented to 1
e(1) -> IF(1>0)
{
// n is pre-decremented to 0
e(0) -> 0 is not > 0 so this call does nothing.
// n is still 0 in this function call so...
printf(0) <-- The first '0' in the output
// n is pre-decremented to -1
e(-1) -> -1 is not > 0) so this call does nothing.
}
// n is still 1 in this function call so...
printf(1) <-- The '1' in the output
// n is pre-decremented to 0
e(0) -> 0 is not > 0 so this call does nothing
}
// n is still 2 in this function call so...
printf(2) <-- The '2' in the output
// n is pre-decremented to 1
e(1) -> (1 is > 0)
{
// n is pre-decremented to 0
e(0) -> 0 is not > 0 so this call does nothing
// n is still 0 in this function call so...
printf(0) <-- The second '0' in the output
// n is pre-decremented to -1
e(-1) -> -1 is not > 0 so this call does nothing
}
}
It helps if you set the code out more clearly:
#include<stdio.h>
main()
{
e(3);
}
void e(int n)
{
if(n>0)
{
e(--n); // First recursion here, but with n=n-1 on entry to the call.
printf("%d",n); // outputs (original value of n) - 1.
e(--n); // Second recursion here, now with n=n-2 on entry to the call.
}
}
After denesting the code the reason for the results can be deduced in a single run in a debugger.
e() is recursive and called once before the print and once after. So before you hit your print statement you'll have to go through e again, and again, and again till it finally hits 0.
After that things start unlooping and you'll see prints popping up but it's still a big recursive mess because of the second call to e(n) in which n dips into the negative. I was rather grateful n was signed because if it was unsigned it would loop round to 2^32 and the program would get stuck in, pretty much, an infinite loop.
So yeah, TL;DR: run it through a debugger and learn from the FUBAR a recursion like this can cause.
i'm new to postscript. What is a format for a function that calls itself recursively. lets say I have a function called squares that prints out a square.
5 square // prints out 5 squares
I think 5 will be a the top of the stack. Each repititon will decrease that number until 0 is met. If there is an easier way to do this, let me know.
%!PS-
%
% int myfunction -
% Executes recursively 'int' times
%
/myfunction {
dup == % Print out the current 'int' just to show we're doing something
1 sub % decrement 'int' by 1
dup 0 gt % copy 'int' and test to see if its 0
{ % not 0, so recurse, the copy on the stack is the new 'int'
myfunction % execute recursion
} {
pop % The copy of 'int' was 0,so remove the copy from the stack
} ifelse
} bind def
5 myfunction
Or you could just use loop to execute a code block 5 times.
/go
{
/cnt { 1 add dup == } def
0
{ cnt } loop
} def
% start by calling go
go
a simple infinite counter that should you get started
#This program generates random number
#user enters guess
#progam tells user higher, lower or correct based on user input.
import random
def main():
# Get a random number.
number = random.randint(1, 101)
user_guess = int(input("Pick a number between 1 and 100: "))
userguess = guess(user_guess, number)
print(userguess)
def guess(num1, num2):
if num1 > num2:
return("Lower")
elif num1 < num2:
return("Higher")
else:
return("Correct")
main()
I can get the program to generate a random number, then display higher or lower, but not as again. It is supposed to ask again until it hits the random and then displays 'correct'
You need a loop to keep prompting until the correct answer is guessed, while(True) keeps going until a break; is reached. Try something like this.
def guess(num):
while(True):
user_guess = int(input("Pick a number between 1 and 100: "))
if user_guess > num:
print("Lower\n")
elif user_guess < num:
print("Higher\n")
else:
print("Correct")
break;
This will repeatedly ask user for numbers untill they are correct replace your main method with the following
def main():
# Get a random number.
number = random.randint(1, 101)
guess(number)
Edit: replaced true with True