I'm still extremely new to python, and currently stuck on this problem. Basically, I take a list of numbers and add them to each other, starting at zero. The code writes out each line into a new array. If in this new array I find two of the same numbers, it stops and returns that number. The original list of values repeats itself if no duplicate is found.
Here's what I have so far:
file = open("list.txt", "r")
array1 = file.readlines()
total = 0
finalValue = 0
for i in range(0,len(array1)):
array1[i] = int(array1[i])
array2 = []
i = 0
counter = 0
while finalValue == 0:
total += array1[i]
array2.append(total)
print(array2)
for c in range(0,len(array2)):
if (total == array2[c]):
counter += 1
if counter == 2:
finalValue = total
break
if (i == len(array1)-1):
i = 0
else:
i += 1
counter = 0
print(finalValue)
I think the counter is working, but it never finds a duplicate, i.e. it never hits the second counter.
There are plenty of ways to make your code simpler in Python, but first of all, your problem is that the condition total == array2[c] compares elements of the array with your total, not with each other. For example, if your array is [1,3,3], the second 3 would be compared to 4, not to 3.
If I understand your code, I think you want to change total == array2[c] to array1[i] == array2[c] - but that's just an immediate fix, you can use python's list techniques to make this code much simpler.
Related
I was given a question with a random string such as
example = ‘asdkfkebansmvajandnrnndklqjjsustjwnwn’
and was asked to find the number of a’s in this string with a while and with a for loop
So simply using the count() function like this is not allowed:
print('# of a:’, example.count(‘a’))
We were given one example: (and were told to find a different way)
counter = 0
for letter in example:
if letter == ‘a’:
counter = counter + 1
print(counter)
I’m very new to python and I really can’t find a way. I thought of converting this string into a list that contains every character as a different object like this:
example_list = list(example)
but then I still couldn't find a way.
We were given two starting points, so the end code has to be in a somewhat similar format and we're not really allowed to use more advanced functions (simple string or list functions and if-statements are allowed as far as I know).
For while-loop:
counter = 0
while counter < 4:
print(example_list[counter])
counter += 1
And for for-loop:
for counter in range(0, len(example_list)):
print(counter, example[counter])
I either end up printing every single character with its position, or I end up printing the number without actually using the loop.
I think the advises tell you that you have to iterate through array using a counter.
Here is the example for while loop:
example = 'asdkfkebansmvajandnrnndklqjjsustjwnwn'
counter = 0
a_count = 0
while counter < len(example):
if example[counter] == 'a':
a_count += 1
counter += 1
print(a_count)
And for for-loop it might look like this:
for counter in range(len(example)):
if example[counter] == 'a':
a_count += 1
Note that converting to a list isn't necessary, since you can iterate over a string exactly the same way that you'd iterate over a string that's been converted into a list.
For your first starting point, I think the idea is to iterate by index:
index = 0
counter = 0
while index < len(example):
if example[index] == 'a':
counter += 1
index += 1
And the for-loop version would be:
counter = 0
for index in range(len(example)):
if example[index] == 'a':
counter += 1
Note: iterating by index like this is actually considered bad practice in Python (because it's basically just adding unnecessary work), and the preferred method is to iterate by value, as in the example you were given and then told not to use.
Two functions, while_count and for_count, to achieve what you need:
def while_count(s):
counter, i = 0, 0
while i < len(s):
if s[i] == "a":
counter += 1
i += 1
return counter
def for_count(s):
counter = 0
for i in range(len(s)):
if s[i] == "a":
counter += 1
return counter
You can make the for case much simpler using a list comprehension:
def for_count2(s):
return sum([x=="a" for x in s])
Here is the solution for your question
1.Using for loop
example = 'asdkfkebansmvajandnrnndklqjjsustjwnwn'
count=0
for i in example:
if i.lower()=='a':
count+=1
print(count)
2. Using While loop:
example = 'asdkfkebansmvajandnrnndklqjjsustjwnwn'
loop_count=0
a_counter=0
lis=list(example)
while loop_count<len(example):
if lis[loop_count]=='a':
a_counter+=1
loop_count+=1
print(a_counter)
Might it help if it does vote my ans up
I'm trying to make a program that finds the perfect number.(Perfect number=The sum of its divisors except itself is a number equal to itself.)And I want to add one more thing. Firstly I want to define an empty list and put the perfect numbers in it.But When I run the programm I didn't take the right throughput.How can I solve this problem.
My cods
def perfect(number):
total = 0
for i in range(1,number):
if number % i == 0:
total += i
return total
perfect_number_set = []
for i in range(1,1001)
if perfect(i):
perfect_number_set += [perfect(i)]
print(perfect_number_set)
print(i)
The output of the codes I wrote
[True]
6
[True,True]
28
[True,True,True]
You have following issues in your code:
Your implementation of perfect method is incorrect. You need to return True/False if a number is perfect. You are returning the total which is not correct.
Missing colon : in the for loop
def perfect(number):
total = 0
for i in range(1,number):
if number % i == 0:
total += i
return total == number
perfect_number_list = []
for i in range(1,1001):
if perfect(i):
print(i)
perfect_number_list.append(i)
print(perfect_number_list)
There is a difference between set and a list in python. You have used a list.
Set contains only unique entries.
Best practice tip:
defining a list use :
list_name = list()
Better way of adding items to as list by using it's method
list_name.append(list_item_to_add)
Another thing is that returning a number and checking it in if without any condition is not readable. Change it to:
if perfect(i) != 0:
(Altho Yours implementation work, because python if treats 0 like False and any other value as True)
I am writing a code on python for the platform Coding Games . The code is about Van Eck's sequence and i pass 66% of the "tests".
Everything is working as expected , the problem is that the process runs out of the time allowed.
Yes , the code is slow.
I am not a python writer and I would like to ask you if you could do any optimization on the piece of code and if your method is complex ( Complex,meaning if you will be using something along vectorized data ) and not just swap an if (because that is easily understandable) to give a good explanation for your choice .
Here is my code for the problem
import sys
import math
def LastSeen(array):
startingIndex = 0
lastIndex = len(array) - 1
closestNum = 0
for startingIndex in range(len(array)-1,-1,-1):
if array[lastIndex] == array[startingIndex] and startingIndex != lastIndex :
closestNum = abs(startingIndex - lastIndex)
break
array.append(closestNum)
return closestNum
def calculateEck(elementFirst,numSeq):
number = numSeq
first = elementFirst
result = 0
sequence.append(first)
sequence.append(0)
number -= 2
while number != 0 :
result = LastSeen(sequence)
number -= 1
print(result)
firstElement = int(input())
numSequence = int(input())
sequence = []
calculateEck(firstElement,numSequence)
so here is my code without dictionaries. van_eck contains the sequence in the end. Usually I would use a dict to track the last position of each element to save runtime. Otherwise you would need to iterate over the list to find the last occurence which can take very long.
Instead of a dict, I simply initialized an array of sufficient size and use it like a dict. To determine its size keep in mind that all numbers in the van-eck sequence are either 0 or tell you how far away the last occurrence is. So the first n numbers of the sequence can never be greater than n. Hence, you can just give the array a length equal to the size of the sequence you want to have in the end.
-1 means the element was not there before.
DIGITS = 100
van_eck = [0]
last_pos = [0] + [-1] * DIGITS
for i in range(DIGITS):
current_element = van_eck[i]
if last_pos[current_element] == -1:
van_eck.append(0)
else:
van_eck.append(i - last_pos[current_element])
last_pos[current_element] = i
I am able to solve this problem up the the 'even' part but I'm getting stuck in the odd part.
You will be given an array of n numbers. Your task is to first reverse the array (first number becomes last, 2nd number becomes 2nd from the last and so on) and then print the sum of the numbers at even indices and print the product of the numbers at odd indices.
Input
First line contains single integer N: number of elements
followed by N different integers separated by spaces
Output
Two space separated integers representing sum of the numbers at even places and the product of the numbers at odd places.
My code so far:
n = int(input())
arr = [int(x) for x in input().split()]
arr.reverse()
for ele in arr:
print(ele, end=" ")
print()
sum = 0
count = 1
while count <= n:
if count % 2 == 0:
sum += count
count += 1
print(sum)
There's a couple of issues in the code you've supplied which I'll address first:
Firstly, you need to be clear about what is meant by odd and even indices. In some languages (Matlab) for example, the first element of an array is index position 1. In Python and Java it's 0, so, whilst your example has assumed 1, it probably should be 0 unless otherwise specified.
Second, in your line sum+=count you're summing the index positions, not the index values, so that isn't what your question is asking for.
Last point on your code is that you've used sum as a variable name. Whilst that works, sum is also a Python keyword and you should avoid using them as variable names as if you later want to use the sum function, you will get the error TypeError: 'int' object is not callable because you've redefined the sum function to be an integer.
To the answer:
Considering the above, this provides the answer to part 1 by fixing your code:
total = 0
count = 0
while count < n:
if count % 2 == 0:
total += arr[count]
count += 1
print(total)
It's worth noting that as you're looking for even numbers, you could better write that as:
total = 0
count = 0
while count < n:
total += arr[count]
count += 2
print(total)
However, there are even easier ways to do this in much less code, and they involve list slicing. You can slice a list by specifying [start: end: step], so arr[::2] specifies a start of position 0 (the default), an end of the end of the list the default) and a step of 2. This means that if arr contains [1,2,3,4,5,6], then arr[::2] will be [1,3,5] (i.e. the values at all of the even indices) or if you specify a start position of 1 i.e. arr[1::2] you will get [2,4,6] (i.e. the values at all of the even indices).
So, rather using a while loop. You could use a for loop over just the even values:
total = 0
for even_val in arr[::2]:
total += even_val
print(total)
but for sum you can even more easily write is as a simple sum command on the list slice:
print(sum(arr[::2]))
Before Python 3.8, there was no simple equivalent of sum for product, so if you're using a lower version, you can either reuse the method above, allowing for the fact that you would need to prime the total with the first value, then multiply from the next one, i.e.:
total = arr[1]
count = 3
while count < n:
total *= arr[count]
count += 2
print(total)
or with a for loop:
total = arr[1]
for odd_val in arr[3::2]:
total *= odd_val
print(total)
But from Python 3.8 (documentation here) you can now import prod from the math library which will work in the same way as sum:
from math import prod
print(prod(arr[1::2]))
[Thanks #HeapOverflow for the nudge]
As this is for a problem set, it may not be an issue as all examples may have an array length N > 2, but the examples above do assume that there will be at least two entries in arr. If that's not the case, you should put in some validation before trying to access arr[1]
Here's a cute little recursive function to do that (assuming one-based indices):
# def prodSum(increment,multiplier=1,*rest): if zero based indices
def prodSum(multiplier,increment=0,*rest):
if not rest: return multiplier,increment
product,total = prodSum(*rest)
return (product * multiplier, total + increment)
x = [1,2,3,4,5]
print(prodSum(*reversed(x))) # 15,6
Write a func/on first_neg that takes a (possibly empty) list of
numbers as input parameter, finds the first occurrence of a
nega/ve number, and returns the index (i.e. the posi/on in the
list) of that number. If the list contains no nega/ve numbers or it
is empty, the program should return None. Use while loop (and
not for loop) and your while loop should stop looping once the
first nega/ve number is found.
This is the question my teacher asked me any ideas this what i did:
def first_neg(list):
count = 0
for number in list:
if number < 0:
count += 1
return count
Dosent seem to work properly i just joined 1st post hope can get some help
x = [1,2,3,-5]
def first_neg(list):
count = 0
for number in list:
count += 1 #moved it outside of the if
if number < 0:
return count
print(first_neg(x)) #prints 4
You want to increment count not when you've found the answer but everytime the forloops loops. Note that this method returns 4 which is the fourth item in the list, not the index, Index of the list starts from 0 so to access it would be 3. Take our list x = [1,2,3,-5], -5 is in the fourth slot of the list, but to access it we have to call x[3] since lists starts at 0 indexing.
If you want to return the index of the list where the first negative number is found try this:
x = [1,2,3,-5]
def first_neg(list):
for count, number in enumerate(list):
if number < 0:
return count
print(first_neg(x)) # prints 3
This is because enumerate creates a "pairing" of the item in the list and it's the current count. Enumerate just counts from 0 everytime it gets an item out of the list.
Also as a side note ( I didn't change it in my answer since I wanted you to understand what's going on ). Don't name your variables keywords like list, tuple, int, str... Just a bad idea and habit, it works as you can see but it can cause issues.
Return the index immediately once you encounter the negative element. Increment the index otherwise:
def first_neg(lst):
count = 0
while count < len(lst):
if lst[count] < 0:
return count
count = count + 1
return None
Note : Better if you use enumerate() rather than using extra count variable. The code you mentioned is not written in pythonic way.
You may try this as well:
def first_neg(lst):
res = [i for i,x in enumerate(lst) if x<0]
return None if res == [] else res[0]
The code above can be improved using generators as suggested by #Chris_Rands.