Does (n%2==1) always convey that n is a odd number? - python-3.x

I had recently had a problem with (n%2==1).
The problem was to calculate the number of even and odd numbers in an array. When I tried the above mentioned condition in my code it resulted in a wrong answer. But when I changed it to (n%2==0) it was accepted. Can anyone help me on this?
The code in Python:
n = int(input())
ct = 0
a = [int(i) for i in input().split()]
for i in a:
if((i%2)==1):
ct+=1
ct1 = n-ct
print(ct,ct1)

In your current code, you are printing the output as
oddNumberCount evenNumberCount
But the problem wants you to print it as
evenNumberCount oddNumberCount
So when you switch it to n%2==0, i.e, check for even numbers, it gets accepted because that is the format the problem wants you to print the numbers in.

Related

Function keeps looping same two numbers

So i'm trying to follow along in the Automate The Boring Stuff with Python book. There's a question that asks me to make the collatz sequence. One function collatz() will be processing the actual math, while the second function get_collatz() will be the one taking user input and running it through the collatz function until the returned number == 1. I apologize if this is a simple mistake, I may have had a little to drink as well as being new to the site and fairly new to coding also. Would appreciate it if someone could help to point me in the right direction. I don't want a straight up answer because I want to learn myself, would just like an idea of what could be going wrong here. Here is my code.
def collatz(number):
if number % 2 == 0:
number //= 2
print(number)
return number
else:
number = 3 * number + 1
print(number)
return number
def get_collatz():
number = int(input('Put in a number please!: '))
while number != 1:
print(number)
collatz(number)
get_collatz()
Asking only for a hint is not really how stackoverflow questions are meant to be. But if a hint you want, a hint you get :)
def get_collatz():
number = int(input('Put in a number please!: '))
while number != 1:
print(number)
collatz(number)
Your variable, number, is a simple integer. It changes its value only when you use an operation like
number = <something>
number += 2
Hint: You don't seem to use any of these operation inside your implementation of get_collatz(). Not other than the initial input, at least :).

Execution timed out (12000ms) kata Generate Numbers from Digits #2 on Code Wars (Python)

Could you give me a hint where the time consuming part of this code is?
It's my temporary solutions for the kata Generate Numbers from Digits #2 from codewars.com.
Thanks!
from collections import Counter
from itertools import permutations
def proc_arrII(arr):
length = Counter(arr).most_common()[-1][1]
b = [''.join(x) for x in list(set(permutations(arr,length)))]
max_count = [max(Counter(x).values()) for x in b]
total = 0
total_rep = 0
maximum_pandigit = 0
for i in range(len(b)):
total+=1
if max_count[i] > 1:
total_rep+=1
elif int(b[i]) > maximum_pandigit:
maximum_pandigit = int(b[i])
if maximum_pandigit == 0:
return([total])
else:
return([total,total_rep,maximum_pandigit])
When posting this,
it would have been helpful to offer example input,
or link to the original question,
or include some python -m cProfile output.
Here is a minor item, it inflates the running time very very slightly.
In the expression [''.join(x) for x in list(set(permutations(arr, length)))]
there's no need to call list( ... ).
The join just needs an iterable, and a set works fine for that.
Here is a bigger item.
permutations already makes the promise that
"if the input elements are unique, there will be no repeat values in each permutation."
Seems like you want to dedup (with set( ... )) on the way in,
rather than on the way out,
for an algorithmic win -- reduced complexity.
The rest looks nice enough.
You might try benching without the elif clause,
using the expression max(map(int, b)) instead.
If there's any gain it would only be minor,
turning O(n) into O(n) with slightly smaller coefficient.
Similarly, you should just assign total = len(b) and be done with it,
no need to increment it that many times.

In PyCharm works fine when typing numbers in one by one, but won't work on code lab

Write a loop that reads positive integers from standard input and that terminates when it reads an integer that is not positive. After the loop terminates, it prints out, on a line by itself, the sum of all the even integers read.
number =int(input())
even_number = 0
while number >= 0:
if number % 2 == 0:
even_number += number
print(even_number)
number = int(input())
it says:
Exception occurred(, EOFError('EOF when reading a line',), )
Exception occurred(, EOFError('EOF when reading a line',), )
The value of _stdout is incorrect.
We think you might want to consider using: >
We think you might want to consider using: sum
We think you might want to consider using: +
Solutions with your approach don't usually use: +=
After the loop terminates, it prints out, on a line by itself, the sum of all the even integers read.
You seem to be printing each time the sum is updated, instead of just once at the end of the loop. Try moving the print to after the while block.

How to give a Subclip a new name in Python using PyAutoGUI?

Complete beginner here making my first program with PyAutoGui as I cannot get access to the software's API. My issues are currently being that I am unable to come up with a solution to name each subclip with a different appended letter on the end. The naming convention should go like so, MI899001~AA, MI899001~AB, MI899001~AC, MI899001~AD. The only thing that changes is the last letter.
Below is the relevant code I'm currently using for the program I am writing;
def naming_promo():
x = string.ascii_uppercase
pyautogui.typewrite('DNH~P336007A' + x[0][0])
for i in range(7):
if i == 0:
sub_clip_clean()
else:
if i >= 1:
pyautogui.typewrite('567890qwe', 0.2)
sub_clip_package()
naming_promo() # See above Fn for method
pyautogui.moveTo(646, 404, duration=0.50)
pyautogui.click()
move_clips()
The naming_promo() takes the ascii_uppercase and types the first letter. I however can't figure out how to iterate through each character in the string as the For Loop repeats. I've googled many solutions, but I guess I can't get my head around how to do a loop in a loop and increment the x value used each time.
This is my first post so apologies for any etiquette I break. Any help and explanation would be greatly appreciated.
This is my first answer so apologies for any etiquette I break.
I'm not sure I understand everything here, since there's a few functions in the code that I don't know about. However, are you just looking for something like:
def naming_promo(n):
x = string.ascii_uppercase
pyautogui.typewrite('DNH~P336007A' + x[0][n])
and further down in your code, simply create a variable and increment it up one after use:
m = 0
for i in range(7):
if i == 0:
sub_clip_clean()
else:
if i >= 1:
pyautogui.typewrite('567890qwe', 0.2)
sub_clip_package()
naming_promo(m) # See above Fn for method
m += 1
pyautogui.moveTo(646, 404, duration=0.50)
pyautogui.click()
move_clips()

make a function that take an integer and reduces it down to an odd number

I'm working on my final for a class I'm taking(Python 3) im stuck at this part.
he gave us a file with numbers inside of it. we opened it and add those numbers to a list.
"Create a function called makeOdd() that returns an integer value. This function should take in any integer and reduce it down to an odd number by dividing it in half until it becomes an odd number.
o For example 10 would be cut in half to 5.
o 9 is already odd, so it would stay 9.
o But 12 would be cut in half to 6, and then cut in half again to 3.
o While 16 would be cut to 8 which gets cut to 4 which gets cut to 2 which gets cut to 1.
 Apply this function to every number in the array. "
I have tried to search the internet but i have not clue where to even begin with this one. any help would be nice.
Here my whole final so far:
#imports needed to run this code.
from Final_Functions import *
#Defines empty list
myList = []
sumthing = 0
sortList = []
oddList = []
count = 0
#Starts the Final Project with my name,class, and quarter
intro()
print("***************************************************************",'\n')
#Opens the data file and reads it then places the intrager into a list we can use later.
with open('FinalData.Data', 'r') as f:
myList = [line.strip() for line in f]
print("File Read Complete",'\n')
#Finds the Sum and Adverage of this list from FinalData.Data
print("*******************sum and avg*********************************")
for oneLine in myList:
tempNum = int(oneLine)
sumthing = sumthing + tempNum
avg = sumthing /1111
print("The Sum of the List is:",sumthing)
print("The Adverage of the List is:",avg,'\n')
print("***************************************************************",'\n')
#finds and prints off the first Ten and the last ten numbers in the list
firstTen(myList)
lastTen(myList)
print("***************************************************************",'\n')
#Lest sort the list then find the first and last ten numbers in this list
sortList = myList
sortList.sort()
firstTen(sortList)
lastTen(sortList)
print("****************************************************************",'\n')
Language:Python 3
I don't want to give you the answer outright, so I'm going to talk you through the process and let you generate your own code.
You can't solve this problem in a single step. You need to divide repeatedly and check the value every time to see if it's odd.
Broadly speaking, when you need to repeat a process there are two ways to proceed; looping and recursion. (Ok, there are lots, but those are the most common)
When looping, you'd check if the current number x is odd. If not, halve it and check again. Once the loop has completed, x will be your result.
If using recursion, have a function that takes x. If it's odd, simply return x, otherwise call the function again, passing in x/2.
Either of those methods will solve your problem and both are fundamental concepts.
adding to what #Basic said, never do import * is a bad practice and is a potential source of problem later on...
looks like you are still confuse in this simple matter, you want to given a number X reduce it to a odd number by dividing it by 2, right? then ask yourself how I do this by hand? the answer is what #Basic said you first ask "X is a even number?" if the answer is No then I and done reducing this number, but if the answer is Yes then the next step dividing it by 2 and save the result in X, then repeat this process until you get to the desire result. Hint: use a while
to answer your question about
for num in myList:
if num != 0:
num = float(num)
num / 2
the problem here is that you don't save the result of the division, to do that is as simple as this
for num in myList:
if num != 0:
num = float(num)
num = num / 2

Resources