#!/bin/python3
b = []
def rotate(d,a):
if d == 0:
return a
b = []
for i in range(len(a)):
b.insert(i-1,a[i])
a = b
rotate(d-1,b)
if __name__ == '__main__':
d = 4
a = ['1','2','3','4','5']
print(rotate(d,a))
I don't know why but when i return 'a' it it prints none. Can anyone help me with this
your issue is the missing return statement when rotate is called recursively:
def rotate(d,a):
if d == 0:
return a
#....
rotate(d-1,b) # <---- here
if you call rotate(d, a) with d > 0, you enter the recursion rotate(d-1,b)...but you throw away the result and python instead returns None. this is because in python any method call that doesn't explicitly return a value, always returns None...and your initial call to rotate(d, a) with d > 0 never passed by a return statement (only the recursive call with d = 0 does, but you throw away that result)...so it returns None.
this should fix your problem:
def rotate(d,a):
if d == 0:
return a
#....
return rotate(d-1,b) # propagate the calculated value back up
see also: Why does my recursive function return None?
Related
i'm having a rough time trying to do a loop with the while function.
Basicly i want the code to show me all prime numbers from 0 to the number i wrote in input.
Then, to ask a question if i want to do it one more time (if yes to repeat the code from the start) or if not to exit.
How i got it now is just to repeat the last results infinitely.
All results i found online with the while loop don't really explain how to repeat a certain part of the code.
I'm by no means even a little bit educated when it comes to this stuff so if its a stupid question, please forgive me.
# Python program to print all primes smaller than or equal to
# n using Sieve of Eratosthenes
def start(welcome):
print ("welcome to my calculation.")
value = input("number?:\n")
print(f'you have chosen: {value}')
value = int(value)
def SieveOfEratosthenes(n):
prime = [True for i in range(n + 1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p ** 2, n + 1, p):
prime[i] = False
p += 1
prime[0] = False
prime[1] = False
print("Primary numbers are:")
for p in range(n + 1):
if prime[p]: print(p)
# driver program
if __name__ == '__main__':
n = value
SieveOfEratosthenes(n)
pitanje = input("do you want to continue(yes/no)?")
while pitanje == ("yes"):
start: SieveOfEratosthenes(n)
print("continuing")
if pitanje == ("no"):
print("goodbye")
strong text
Firstly you should remove
value = input("number?:\n")
print(f'you have chosen: {value}')
value = int(value)
from the top of your code, everything must be inside your __main__ program.
Basically what you need to do is create a main While loop where your program is gonna run, it will keeps looping until the response is not "yes".
For each iteration, you ask a new number at the beggining and if it has to keep looping at the end.
Something like this:
# driver program
if __name__ == '__main__':
# starts as "yes" for first iteration
pitanje = "yes"
while pitanje == "yes":
# asks number
value = input("number?:\n")
print(f'you have chosen: {value}')
value = int(value)
# show results
start: SieveOfEratosthenes(value)
# asks for restart
pitanje = input("do you want to continue(yes/no)?")
#if it's in here the response wasn't "yes"
print("goodbye")
I would like to use nimbioseq and iterate two files with the same number of sequences (using the readSeq()iterator), as:
for seq1, seq2 in readSeq(file1), readSeq(file2):
echo seq1.id, "\t", seq2.id
For this scenario I suppose I need some sort of "zipping" operator, which I couldn't understand how to use [ found this: https://hookrace.net/nim-iterutils/iterutils.html#zip.i,,Iterable[S] ].
or alternatively understand how to get a single "iteration" outside a for loop (if possible):
for seq1 in readSeq(file1):
let seq2 = readSeq(file2);
echo seq1.id, "\t", seq2.id
Thanks for you help!
toClosure from iterutils is limited, but you can:
import iterutils
template initClosure(id,iter:untyped) =
let id = iterator():auto{.closure.} =
for x in iter:
yield x
initClosure(f1,readSeq(file1))
#creates a new closure iterator, 'f1'
initClosure(f2,readSeq(file2))
#creates a new closure iterator, 'f2'
for seq1,seq2 in zip(f1,f2):
echo seq1.id,"\t",seq2.id
Edit: thanks to #pietropeter for pointing out the bug, here's their example rewritten using this template:
import iterutils
template initClosure(id:untyped,iter:untyped) =
let id = iterator():auto {.closure.} =
for x in iter:
yield x
iterator letters: auto =
for c in 'a' .. 'z':
yield c
# Now requires a parameter
iterator numbers(s: int): int =
var n = s
while true:
yield n
inc n
initClosure(cletter,letters())
initClosure(numbers8,numbers(8))
for (c, n) in zip(cletter, numbers8):
echo c, n
I'm going to use this iterators code from Manual, and insert your problem in it. I'm sure it has room for improvement:
type
Task = iterator (r: var int)
iterator f1(r: var int){.closure.} =
for n in [1, 3, 5]:
r = n
yield
iterator f2(r: var int){.closure.} =
for n in [2, 4, 6]:
r = n
yield
proc runTasks(t: varargs[Task]) =
var ticker = 0
var r: int
while true:
var x = t[ticker mod t.len]
x(r)
echo r
if finished(x): break
inc ticker
runTasks(f1, f2)
You'll see in the output 1,2,3,4,5,6,6 (finished is prone to error, as stated in the manual, and returns the last item twice). You have to update the code, replacing r: var int with whatever type returns readSeq(file) (r: var Record, I think), and replace the iterators for n in [1, 2, 3] with for s in readSeq(file).
If the type of behaviour you want is that of zip, the one from iterutils seems to work fine. The only caveat is that it requires closure iterators (see manual for the difference between inline and closure iterators). Example (https://play.nim-lang.org/#ix=2yXV):
import iterutils
iterator letters: char {.closure.} =
for c in 'a' .. 'z':
yield c
iterator numbers: int {.closure.}=
var n = 1
while true:
yield n
inc n
for (c, n) in zip(letters, numbers):
echo c, n
I see that readseq in nimbioseq is not closure but probably something like this could work (edit: its should not, see below):
iterator closureReadSeqs(filename: string): Record {.closure.} =
for rec in readSeqs(filename):
yield rec
Edit
For the case of iterator with a parameter in the comments, the fix is to have a proc that returns an iterator (which will be a closure iterator by default in this case). Updated example (https://play.nim-lang.org/#ix=2z0e):
import iterutils
iterator letters: char {.closure.} =
for c in 'a' .. 'z':
yield c
# Now requires a parameter
proc numbers(s: int): iterator(): int =
return iterator(): int =
var n = s
while true:
yield n
inc n
let numbers8 = numbers(8)
for (c, n) in zip(letters, numbers8):
echo c, n
Now my best guess on how to make this work for nimbioseq is:
proc closureReadSeqs(filename: string): iterator(): Record =
return iterator(): Record =
for rec in readSeqs(filename):
yield rec
I have this little guessing game code. In order to deal with the string input, I used try/catch blocks. Try works perfectly, but catch-block is outside of the loop and I can't seem to make it work inside. So the program stops after catching an exception. What should I do so that my loop continues after catching an exception?
fun main(args: Array<String>) {
val rand = java.util.Random()
val n = 1 + rand.nextInt(100)
var guess: Int
var numberOfTries = 0
println("I guessed a number from 1 до 100. What is it?\n")
try {
do {
guess = readLine()!!.toInt()
var x = Math.abs(n - guess)
numberOfTries++
when (x) {
in 1..3 -> println("А-а-аh! It's burning!")
in 4..7 -> println("Really hot!")
in 8..15 -> println("Warm")
in 16..31 -> println("A bit warm!")
in 32..63 -> println("Pretty cold")
in 64..99 -> println("It's freezing!")
}
} while (guess != n)
} catch (e: NumberFormatException) {
println("Use digits, please!") }
println("Wow! You only used $numberOfTries tries!")
}
As MFazio23 mentioned, you use the try inside the while loop. Otherwise, it will exit the loop if an exception is thrown.
If an exception is thrown, anything inside is halted, which includes further code. if you have a method that throws an exception, no code after it will be executed. The try-catch creates an entry-point for the exception; your code will continue inside the relevant catch block (or exit the program if there is none), which means the loop inside the try-catch will stop.
However, you actually don't need the try-catch at all. Kotlin has a nice extension function called toIntOrNull, which does exactly what you'd expect; it attempts to convert the input to an int, and returns the number, or null if it failed. So, you can do this:
fun main(args: Array<String>) {
val rand = java.util.Random()
val n = 1 + rand.nextInt(100)
var guess: Int?
var numberOfTries = 0
println("I guessed a number from 1 до 100. What is it?\n")
do {
guess = readLine()?.toIntOrNull() // Note that this now uses ?. instead of !!. This is to make the null check useful If it throws an NPE, it kinda defeats the point. If the line is null, it now prints the same message as an invalid number
// numberOfTries++ // move this up here if you want to count invalid guesses as a guess
if(guess == null){
System.out.println("Only use numbers")
continue;
}
val x = Math.abs(n - guess)// I also changed this to a val; it's immutable, so it doesn't need to be a var
numberOfTries++
when (x) {
in 1..3 -> println("А-а-аh! It's burning!")
in 4..7 -> println("Really hot!")
in 8..15 -> println("Warm")
in 16..31 -> println("A bit warm!")
in 32..63 -> println("Pretty cold")
in 64..99 -> println("It's freezing!")
}
} while (guess != n)
println("Wow! You only used $numberOfTries tries!")
}
You can also optimize it further, but using an extension function/variable (I'm not sure what it is, it's a variable declared as an extension function, but since there's a getter too, I'm not sure what to call it) called absoluteValue.
You could also use if-statements, but it is slightly more boilerplate than using this. You cannot call Math.abs with null, because it uses primitives. Primitives in Java can never be null.
Which means anything you pass you the method cannot be null, which in Kotlin means for an instance Int. If it's nullable, it's an Int?, but the method requires non-null from Kotlin. You can't pass Int? to Int (you can do it the other way around, but that's not relevant here).
Under the hood, .absoluteValue calls Math.abs(n), but since it's a call, you can use the null-safe operator (?.)
guess = readLine()?.toIntOrNull()
val x = guess?.absoluteValue
numberOfTries++
when (x) {
in 1..3 -> println("А-а-аh! It's burning!")
in 4..7 -> println("Really hot!")
in 8..15 -> println("Warm")
in 16..31 -> println("A bit warm!")
in 32..63 -> println("Pretty cold")
in 64..99 -> println("It's freezing!")
null -> println("Please only use numbers")
}
And now that x is nullable, you can add null to the when statement (in response to your comment).
Also, if you only want numberOfTries to increment on valid numbers, add an if(x != null) before you call it.
You should be able to add the try...catch block right in your do...while. The only other change needed would be to initialize guess with a value (since it's not guaranteed to be set before the while block is hit):
val rand = java.util.Random()
val n = 1 + rand.nextInt(100)
var guess = 0
var numberOfTries = 0
println("I guessed a number from 1 до 100. What is it?\n")
do {
try {
guess = readLine()!!.toInt()
val x = Math.abs(n - guess)
numberOfTries++
when (x) {
in 1..3 -> println("А-а-аh! It's burning!")
in 4..7 -> println("Really hot!")
in 8..15 -> println("Warm")
in 16..31 -> println("A bit warm!")
in 32..63 -> println("Pretty cold")
in 64..99 -> println("It's freezing!")
}
} catch (e: NumberFormatException) {
println("Use digits, please!")
}
} while (guess != n)
println("Wow! You only used $numberOfTries tries!")
I'm new to Scala and I was playing around with the Array.tabulate method. I am getting a StackOverFlowError when executing this simplified piece of code snippet (originally a dp problem).
import Lazy._
class Lazy[A](x: => A) {
lazy val value = x
}
object Lazy {
def apply[A](x: => A) = new Lazy(x)
implicit def fromLazy[A](z: Lazy[A]): A = z.value
implicit def toLazy[A](x: => A): Lazy[A] = Lazy(x)
}
def tabulatePlay(): Int = {
lazy val arr: Array[Array[Lazy[Int]]] = Array.tabulate(10, 10) { (i, j) =>
if (i == 0 && j == 0)
0 // some number
else
arr(0)(0)
}
arr(0)(0)
}
Debugging, I noticed that since arr is lazy and when it reaches the arr(0)(0) expression it tries to evaluate it by calling the Array.tabulate method again -- infinitely over and over.
What am i doing wrong? (I updated the code snippet since I was basing it off the solution given in Dynamic programming in the functional paradigm in particular Antal S-Z's answer )
You have effectively caused an infinite recursion. You simply can't reference a lazy val from within its own initialization code. You need to compute arr(0)(0) separately.
I'm not sure why you are trying to access arr before it's built, tabulate seems to be used to fill the array with a function - calling arr would always result in infinite recursion.
See Rex's example here (and a vote for him), perhaps that will help.
In a multidimensional sequence created with tabulate, is the innermost seq the 1. dimension?
I was able to solve this by wrapping arr(0)(0) in Lazy so it is evaluated as a call-by-name parameter, thereby not evaluating arr in the tabulate method. The code that I referenced was automatically converting it using implicits (the binary + operator), so it wasn't clear cut.
def tabulatePlay(): Int = {
lazy val arr: Array[Array[Lazy[Int]]] = Array.tabulate(10, 10) { (i, j) =>
if (i == 0 && j == 0)
1 // some number
else
new Lazy(arr(0)(0))
}
arr(0)(0)
}
Thanks all.
I have fiddled with this problem for a while and can't seem to find the solution. I'm working on some code another guy originally wrote, my job is to get it to work since he didn't get the possibility to finish it.
I have created an EDT called MpasMthSalesIndex with array elements containing all the months, Jan - Dec.
I make a call to the method (which is in the MpasItemSales datasource) below from a form to get the array returned like this:
[MpasMthSalesIndex] = MpasItemSales.MthSales(Year(today())-2);
giving me the error: "operand types are not compatible with the operator"
it doesn't work. this was what the original code was, and i have tried everything i can come up with to get this array returned. Anyone know how i can do this?
HERE'S THE METHOD I CALL:
What i do is initializing the MpasMthSalesIndex Ret, and fill it with values and try to return it, no errors here, but I get errors when i try to assign it to MpasMthSalesIndex from the form where i need it...
MpasMthSalesIndex MthSales(Yr _yr)
{
int i;
int m;
date d = SystemDateGet();
date e;
Qty YrSales[366];
MpasMthSalesIndex ret;
;
switch(_yr)
{
case(Year(d)) : [YrSales] = this.MpasSalesCurYr;
d = dateStartYr(d);
break;
case(Year(PrevYr(d))) : [YrSales] = this.MpasSalesPrevYr;
d = dateStartYr(PrevYr(d));
break;
case(Year(PrevYr(PrevYr(d)))) : [YrSales] = this.MpasSalesPrev2Yr;
d = dateStartYr(PrevYr(PrevYr(d)));
break;
case(Year(PrevYr(PrevYr(PrevYr(d))))) : [YrSales] = this.MpasSalesPrev3Yr;
d = dateStartYr(PrevYr(PrevYr(PrevYr(d))));
break;
}
e = dateEndYr(d);
while (d<e)
{
i = DayOfYr(d);
m = MthOfYr(d);
ret[m] += YrSales[i];
d++;
}
return ret;
}
The call
[MpasMthSalesIndex] = MpasItemSales.MthSales(Year(today())-2);
is expecting a container as return value, as in:
int a, b, c;
[a, b, c] = [1, 2, 3]
Try to edit the method to return a container:
return [ret];