how to create a program on python that can input a number from a user and classify it as either prime or composite - numbers

I'm stuck at a point where the computer has to check for all remainders of the number which has been given by the user. Am I supposed to use a For loop for this if yes then how?
Thank you.

yes, you need to use for loop, below function will give you how you can use for loop to check whether number is prime or not.
def prime(n):
flag = 0
for i in range(2,(n/2)+2):
if n%i==0:
flag = 1
return "composite"
if flag==0:
return "prime"

def prime_or_composite(num):
div = 2
while True:
if num == div:
print("It is a prime number!")
break
elif num % div = 0:
print("It is a composite number!")
break
else:
div += 1
This works if the input number is an integer bigger than 2.

Related

Extremely basic loop question telling whether number is even/odd

var currentnum: Int = 1
for currentnum in 1...100{
if (currentnum % 2) != 0 {
print("Odd number")
}
else{
print("Even number")
}
currentnum += 1
}
Hello. I'm trying to "create a loop that iterates from 1 to 100 that prints out whether the current number in the iteration is even or odd." When I run the above code, I receive "error: expected expression after operator." What is wrong with my code (I'm new to programming). Thanks!
You don't need to declare var currentnum: Int = 1 in your code and increment through currentnum += 1. for-in loop does it for you. In Swift for-in syntax can be used to loop over both ranges of numbers, collections and even strings. All with the same syntax!
It should be as follows,
for currentnum in 1...100{
if (currentnum % 2) != 0 {
print("Odd number")
}
else{
print("Even number")
}
}
Good luck!
You should get rid of this expression currentnum += 1.
Because you are using the In .. Range operator there is no need to increment the counter. The In .. Range Operator will take care of this. This is different to the basic for loop from Java or C++ where you need to increment your counter variable.
Additionally the first declared variable currentnum is never used. This variable could be removed too.
The rest of your algorithm looks good and should work!
Hope this helps!
Unlike some languages you do not need to define the index variable before entering the for-in loop, nor do you need to manually increment the index.
You can also use the new swift function isMultiple(of:) rather than modulus
If you want to loop through a set range you can do:
for num in 1...100 {
if num.isMultiple(of: 2) {
print("\(num) is an even number")
} else {
print("\(num) is an odd number")
}
}
If you have a set of values in an array you can do this:
let numbers = [1,5,12,23,25,27,30,32,35]
for num in numbers {
if num.isMultiple(of: 2) {
print("\(num) is an even number")
} else {
print("\(num) is an odd number")
}
}
One liner without a for loop per the request in the comments
Array(1...100).map{$0 % 2 == 0 ? print("\($0) is even") : print("\($0) is odd") }
#BeginnerCoderGirl i have changed your code please check just remove currentnum += 1 from code and run

How many breaks does it take to divide a chocolate completely?

CodeWars challenges again. Today I have a problem with this one:
"Your task is to split the chocolate bar of given dimension n x m into small squares. Each square is of size 1x1 and unbreakable. Implement a function that will return a minimum number of breaks needed.
For example, if you are given a chocolate bar of size 2 x 1 you can split it to single squares in just one break, but for size 3 x 1 you must do two breaks.
If input data is invalid you should return 0 (as in no breaks are needed if we do not have any chocolate to split). Input will always be a non-negative integer."
For some reason, the output is constantly 0 no matter what sides of the chocolate bar I provide.
What I've already tried:
object breakChocolate {
var result = 0
def breakChocolate(n: Int, m: Int) = {
var t = n*m
var i =0
def breaking(y:Int): Unit ={
if (t ==0 || t ==1)
result = i
else {
breaking(t%2)
i +=1
}
}
result
}
}
Here are the tests:
Test Results:
TestCases
breakChocolate(5, 5) should return 24
Test Failed
0 was not equal to 24
Stack Trace
Completed in 38ms
breakChocolate(7, 4) should return 27
Test Failed
0 was not equal to 27
Stack Trace
Completed in 1ms
Completed in 76ms
To solve this problem you don't need recursion at all. Consider the special case of chocolate plate: (1 x n). To divide this plate completely you need (n-1) breaks. Now you have plate m x n. To divide it into m pieces of form (1 x n) you need (m-1) breaks. So the total number of breaks is
(m-1) + m*(n-1) ~
m - 1 + m*n - m ~
m*n - 1
If I'm reading the Scala correctly, you've got the basic algorithm wrong.
This is actually a very simply problem, something similar to the old puzzle: if you have 55 teams playing in a single-elimination tournament, obviously some of them have to get byes in the first round, so there won't be a perfect even bracket. So how many total games will be played?
The answer: 54. Regardless of how the bracket is made, it's a single-elimination tourney. Every game reduces the number of remaining teams by one. So to get 55 participants down to one winner, 54 games will have to be played.
There is a similar argument to be made for your chocolate bar. At some point, you have p pieces of chocolate in front of you. Whichever one you select to break, you have taken 1 from the pile and put back 2, which means that the pile now has p + 1 pieces. So for every split you add one piece to the pile. This should lead directly to an answer...
...which may actually be wrong because of the need to return 0 in some cases, but it should be easy to special-case that.
You get 0 because you are not running breaking.
If you want to use recursion, one option could be to use a tail recursive function.
First decrement a checking it is greater than 1 to get the number of "horizontal" breaks to get the slices. Add 1 to the accumulator while looping.
Then decrement b checking it is greater than 1 to get the number of "vertical" breaks. This time add the starting "horizonal" value because that is the number of times you actually have to break the slices.
object breakChocolate {
def breakChocolate(n: Int, m: Int): Int = {
def breaking(a: Int, b: Int, acc: Int = 0): Int = {
if (a > 1) breaking(a - 1, b, acc + 1)
else if (b > 1) breaking(a, b - 1, acc + n)
else acc
}
breaking(n, m)
}
}
Scala demo
You can use this code instead:
function breakChocolate(n,m) {
if(n > 0 && m > 0) {
return n * m - 1;
} else {
return 0;
}
}

Scala - conditionally sum elements in list

I am trying to solve a beginner problem with lists but can't find an example to help me get it work. I am given a list of positive and negative integers (AccountHistory) and I need to check if the negative integers in this list have ever exceeded -1000. I expected my code to work with a freshly introduced helper function like this:
def checkAccount(account: AccountHistory): Boolean = {
def helper(i: AccountHistory): Int = {
var total = 0
i.collect{case x if x < 0 => Math.abs(x) + total}
return total
}
if (helper(account) >1000) true else false
}
But it doesn't work. Please help me find my mistake or problem in wrong approach.
Edit: The pre-given tests include
assert(checkAccount(List(10,-5,20)))
assert(!checkAccount(List(-1000,-1)))
So if assert expects true then my approach is wrong to solve it like this.
By 'exceeded' I mean <-1000, for any or all elements in a list (like exceeding a credit amount in given period).
i.collect{case x if x < 0 => Math.abs(x) + total}
In the above code snippet, not assign back to total, maybe you need:
val total = i.filter(_ < 0).map(Math.abs).sum
I think this is what you're supposed to do:
def checkAccount(account: AccountHistory): Boolean =
account.forall(_ > -1000)

define the prompted number is prime or not

i want a code to define the prompted number by user is prime or not . since it's an assignment
i'm not allowed to use ' isprime ' predefined code .
the following approach was not useful :
N = input( 'please enter a positive enteger value = ' ) ;
Quotient = floor(N - (mod(N,2)./2)) ;
for i = 1 : Quotient
if mod(N,i ) == 0
fprintf(' your prompted number is not prime ' ) ;
if mod(N,i) ~= 0
fprintf(' your prompted number is prime ' ) ;
end
end
end
for example if i enter a prime number like 13 it results in this :
your prompted number is prime
but if i enter a Non-prime num like 12 it repeats the ' your prompted number is prime ' message for 10 times .
for i = 1 : Quotient
if mod(N,i ) == 0
That will give you every number since x mod 1 is always zero. In other words, the remainder (when you divide any positive integer by one) is zero, since all of them divide perfectly.
You need to start at 2 rather than 1.
In addition, once you've found out the number is not prime, you should stop the loop since there's no possibility of it becoming prime again after that :-) And, for efficiency, you only need to go up to the square root of the number since, if it has a factor above that, you would have already found the equivalent factor below that.
The pseudo-code for such a beast would be:
set isprime to true
set chkval to 2
while chkval * chkval <= number:
if number mod chkval is zero:
set isprime to false
exit while
end if
increment chkval
end while
if isprime:
say number, " is prime"
else:
say number, " is composite"
Try to find factors and as soon as you find one you know it's not prime:
prime = true
for f = 2:ceil(sqrt(N)) %// Start from 2 as prime numbers DO have 1 as a factor. Anything larger than sqrt(N) will have to have a corresponding factor smaller than this so there is no point checking them
if mod(N,f) == 0
prime = false;
break;
end
end
There are 2 problems with your code. First, as already explained by paxdiablo, you need to start your loop from 2. Secondly you have nested your if statements, and since they are mutually exclusive conditions, the inner condition will never trigger.

pygtk - spinbutton: output-signal

I use a spinbutton in my application to let the user choose a number between -1 and 100. In my application -1 means Infinity. So I want to show the text "Infinity", if the user selects the value -1. This is my code:
def spin_output(spin):
digits = int(spin.props.digits)
value = spin.props.value
if value < 0:
spin.props.text = "Infinity" # u"\u221E"
else:
spin.props.text = '{0:.{1}f}'.format(value, digits)
return True
self.my_spin.connect('output', spin_output)
When the "Infinity"-value is selected and the user presses the "up"-button the value changes to 100 instead of 0.
When i replace "Infinity" with u"\u221E" and the user presses the "up"-button while it is selected, the value changes to 1.
What I want is, that the user can select the values in that order: Infinity, 0, 1, ...
What is my mistake?
I thought that only the underlying adjustment is changed when the user changes the value and my function is only used to show the current value.
What's happening is that the spin button is interpreting the string "infinity" as a string entered by the user, and trying to parse it as a value. The gtk.Scale widgets offer a signal called format-value which is used to display custom values just like you're trying to do, but I don't see a similar signal for the spin button.
Here is something using a scale that might do what you want:
#!/usr/bin/env python
import gtk
def scale_output(scale, value):
if value < 0:
return "Infinity" # u"\u221E"
return "{0}".format(int(value))
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
adjustment = gtk.Adjustment(-1, -1, 100, 1, 1)
scale = gtk.HScale(adjustment)
window.set_default_size(300, 100)
window.add(scale)
scale.connect('format-value', scale_output)
window.connect('destroy', gtk.main_quit)
window.show_all()
gtk.main()
Ok, i found a solution. I wrote the counterpart for the output-signal-handler ... the input-signal-handler :-)
def parallel_spin_input(spin, new_value):
text = spin.get_text()
if text == u"\u221E":
value = -1
else:
try:
value = float(text)
except ValueError:
return -1
p = ctypes.c_double.from_address(hash(new_value))
p.value = value
return True
self.parallel_spin.connect('input', parallel_spin_input)
This seems to work well ;-)