Python: find top k-biggest numbers in an array - python

What's wrong with this code? Please, do not use built-in functions
Also, could you add condition for int(k) < int(size)
numbers = list()
size = input("Enter the size of an array: ")
for i in range(int(size)):
n = input("number: ")
numbers.append(int(n))
print(numbers)
k = input("k = ")
max = numbers[0]
top = list()
for j in range(int(k)):
for x in numbers:
if x > max:
max = x
top.append(max)
del numbers[numbers.index(max)]
print(top)

Here is the corrected version of your code:
size = int(input("Enter the size of an array: ")) # Ask the user for the amount of values that will be entered
numbers = [int(input("number: ")) for _ in range(size)] # Use a list comprehension to store each input
k = int(input("k = ")) # The number of greatest values to be printed
top = list() # List to store the greatest values
for i in range(0, k): # For every unit in the number of greatest values
max = numbers[0] # Set the maximum to any value, I chose index 0 to avoid IndexError
for j in numbers: # For every number in the list of numbers
if j > max: # If that number is greater than max
max = j # Set max to that number and repeat
top.append(max) # Add the gratest to the top list
numbers.remove(max) # Now remove the greatest so we can proceed to find the next greatest
print(top) # Print our result!
Please note that it is a bad practice to name any of your variables the names of built-in functions, so maybe change your max to mx.

You want to have largest k numbers in the list right?
You could just sort the array and take the last k elements with a backwards iteration. Because after you sort, the largest numbers will be at the end.
The algorithm would be as follows:
0. Take the array through a for loop # You seem to have done this
Sort the array (Python has a native sort function, but let's just define a simple bubble sort function as you said no libraries)
Initialize a list or a k-tuple to hold largest numbers
Starting from index = array.length - 1 iterate to index = array.length - 1 - k
Insert each element to the k-tuple in step 2.
In Python, it would be:
def kLargestNumbers(array,k):
### Considering the input array is taken
bubbleSort(array) ## if native python lib is available change it to sort()
largest_k_numbers = list()
for i in range(len(array)-1, len(array)-1-k,-1):
largest_k_numbers.append(array[i])
return largest_k_numbers
def bubbleSort(array):
n = len(arr)
for i in range(n-1):
for j in range(0, n-i-1):
if arr[j] < arr[j+1] :
arr[j], arr[j+1] = arr[j], arr[j+1]

Related

How can I print the difference of each value from the highest value?

I want to print the differences of each value from the highest value but I dont know what to do. Here is my example
from array import *
arr = array('i',[])
array_length = (5)
for i in range(array_length):
element = int(input('Enter a number: ')
arr.append(element)
print('\nArray List:',arr)
def largest(arr, array_length):
max = arr[0]
for i in range(array_length):
if arr[i] > max:
max = arr[i]
return max
answer = largest(arr, array_length)
print('\nThe highest value is:',answer)
def getAllArrayDifferenceFromMax(arr):
biggest = max(arr)
return [biggest-x for x in arr]
So basically I first got the largest number in the array, then returned an array that gets the xth item in the array and then do: biggest-arr[x] that's all.
I know it may seem a bit unclear, so comment down your questions.

How can we find the permutations of a n-digit number?

I wrote the permutations for the 4-digit number using a list and loops in python.
a =list(input("enter a four digit number:"))
n=[]
for i in range (0,4):
for j in range (0,4):
if(j!=i):
for k in range(0,4):
if(k!=i and k!=j):
for w in range (0,4):
if(w!=i and w!=j and w!=k):
n.append(a[i]+""+a[j]+""+a[k]+""+a[w])
print(n)
If the input is 1234, the output will be the permutations of all 1234 i.e., 24 permutations. Can someone help me with the permutations of the n-digit number? I would prefer to see a pythonic solution.
Permutate [1..N]
import itertools
N = 4 # pick a number to permutate [1..N]
print(list(itertools.permutations(range(1, N + 1))))
Now if you want to permutate an arbitrary list:
import itertools
sample = [1,5,6,2,1]
print(list(itertools.permutations(sample)))
For the conditions inside if loop the condition recursion is used,
There should be dynamic number of for loops based on the length of the digits
so loop recursion method is used.
The digits are concatenated in the l variable
When there are repeated digits in number set method can make them as distinct
#n digit number as input converted into list
f=list(input("enter any number:"))
#dynamic array for dynamic for loop inside recursion
a=[0 for k in range(len(f))]
c=[]#list which is to be used for append for digits
ans=[]# result in which the
# recursion for if loop inside for loop
#1st argument is fixed inside the loop
#2nd argument will be decreasing
def conditn(k,m):
if(m==0):
return 1
if(m==1):
if(a[k]!=a[0]):
return 1
if(a[k]!=a[m-1] and conditn(k,m-1)):
return 1
#recursion for for loop
#1st argument y is the length of the number
#2nd argument is for initialization for the varible to be used in for loop
#3rd argument is passing the list c
def loop(y, n,c):
if n<y-1:
#recursion until just befor the last for loop
for a[n] in range(y):
if(conditn(n,n)):
loop(y, n + 1,c)
else:
# last for loop
if(n==y-1):
for a[n] in range(y):
#last recursion of condition
if(conditn(n,n)):
#concatinating the individual number
concat=""
for i in range(y):
concat+=f[a[i]]+""
c.append(concat)
#returning the list of result for n digit number
return c
#printing the list of numbers after method call which has recursion within
#set is used used to convert any of the iterable to the
#distinct element and sorted sequence of iterable elements,
for j in (set(loop(len(f),0,c))):
print(j)
def swapper(s , i,j) :
lst = list(s)
return "".join(lst)
def solve(string , idx, res) :
if idx == len(string) :
res.append(string)
return
for i in range(idx, len(string )) :
lst=list(string)
lst[i],lst[idx]=lst[idx],lst[i]
string = "".join(lst)
solve(string,idx+1,res)
lst=list(string)
lst[i],lst[idx]=lst[idx],lst[i]
string = "".join(lst)
n = 3
k = 3
lst = []
res = []
for i in range(1,n+1) :
lst.append(str(i))
string = "".join(lst)
solve(string, 0 , res)
res.sort()
n is the number of digits you may want in your answer
res will store all the permutations of the number
This is a simple resursion solution : )

Sum of a large list in python

Calculate the index of an integer from a given large list whose removal does not effect the mean of the list
I have tried linear time approach but it seems to fail test cases having numbers above 10^9 and the size of the list exceeds 10^5.
Please suggest some better approach to solve this problem if any or to suggest more efficient way to sum large list with large values .
Here is my code below :
for _ in range(int(input())):
n=int(input())
#ar=list(map(int,input().split()))
ar=[int(x) for x in input().split()]
me=sum(ar)/n
for j in range(n):
#arr2=deepcopy(ar)
arr2=ar[:]
#arr2=[]
#for _ in ar:
# arr2.append(_)
arr2.remove(ar[j])
if (sum(arr2)/(n-1))==me:
print(j+1)
break
else:
print("Impossible")
The code fails in two of the 10 test cases just because of increase in the len of the list and size of the integer
You seem to make a deep copy of the entire array in each iteration, which is expensive. Why not just check whether an item equals the mean?
for _ in range(int(input())):
n = int(input())
ar = [int(x) for x in input().split()]
mean = sum(ar) / n
found = False
for j in range(n):
if ar[j] == mean:
print(j, " is the result.")
found = True
break
if not found:
print("Impossible")
This looks more like a math problem than an algorithm challenge:
given that mean = sum(list)/len(list), we need a value k such that:
mean = (sum(list)-k)/(len(list)-1)
Which a little algebra tells us is:
k = sum(list) - mean * (len(list)-1)
k = sum(list) - mean * len(list) + mean
k = sum(list) - sum(list) + mean <-- because mean*len(list) = sum(list)
k = mean
for example:
a = [1,2,3,4,5,6,7]
k = sum(a)/len(a) # 4
ik = a.index(k) # 3

Python Lists - Highest & Lowest

i am creating a python program, to allow a user to input numbers and find the total, average, highest and lowest of the numbers inputted. my teacher has told me to improve the program by removing the first and last number(which i have now done ) inputted into the list and not to use the min and max functions.I am confused on how doing so.
totalList=[]
TotalNum = int(input("Please enter how many numbers are to be entered:"))
Change=TotalNum
Input=0
Total=0
while TotalNum>0:
TotalNum = TotalNum - 1
Input = int(input("Enter Number: "))
totalList.append(Input)
Total = Total +Input
while 1 == 1:
totalList = totalList[1:-1]
TotalList = totalList
print("Total:" ,Total)
print("Average:",Total/Change)
print("Highest:",max(TotalList))
print("Lowest:",min(TotalList))
When removing the first and last numbers of the list, since lists are zero-indexed in python (meaning the first number is at index 0), you'll want to change totalList = totalList[1:-1] to start from 0, making it totalList = totalList[0:-1].
However, we may want to use those first and last numbers when searching for the maximum and minimum numbers in the list. So, I think what your teacher may have meant was to use the first and last numbers as min and max, and update them as you search through the list.
I will show you finding the minimum, and then using the same idea you can find the maximum.
min_num = TotalList[0]
max_num = TotalList[-1]
for i in TotalList:
if i < min_num:
i = min_num
# print("Highest:",max_num)
print("Lowest:", min_num)
Note: You don't need the infinite while 1 == 1: loop, delete it.
def find_low(nums, index):
lowest = None
lowNum = float("inf")
for num in nums:
if num < lowNum:
lowNum = num
lowest = num
highest = None
highNum = -float("inf")
for num in nums:
if num > highNum:
highNum = num
highest = num
Used = []
newL = []
for num in range(lowest, highest + 1):
if num in nums and not num in Used:
newL.append(num)
Used.append(num)
return newL[index - 1]
numbers = [1,2,3,4,5]
print(find_low(numbers, 1))
#The second paramter, 1, finds the lowest number, not 0

Finding the "centered average" of a list

"Return the "centered" average of a list of integers, which we'll say is the mean average of the values, except ignoring the largest and smallest values in the list. If there are multiple copies of the smallest value, ignore just one copy, and likewise for the largest value. Use integer division to produce the final average. You may assume that the list is length 3 or more."
This is a problem I have from my homework assignment and I am stumped at how to find the the largest/smallest numbers and cut them out of the list. Here is what I have so far. and It works for 10/14 the scenarios that I have to pass.. I think it is just because it grabs the median
def centered_average(nums):
x = 0
for i in range(len(nums)):
x = i + 0
y = x + 1
if y%2 == 0:
return (nums[y/2] + nums[(y/2)+1]) / 2
else:
return nums[y/2]
Sorting the array is certainly terser code, here's an alternative with a manual loop
max_value = nums[0]
min_value = nums[0]
sum = 0
for x in nums:
max_value = max(max_value, x)
min_value = min(min_value, x)
sum += x
return (sum - max_value - min_value) / (len(nums) - 2)
This just adds everything in and removes the max and min at the end.
If the list isn't too long, it shouldn't be too computationally expensive to sort the list:
sorted(nums)
Then you can create a new list without the first and last entries, which will be the smallest and largest values:
new_nums = sorted(nums)[1:-1] # from index 1 to the next-to-last entry
Before i start i know there are easier ways mentioned in the other answers using the function sort, yes that is true but i believe your teacher must have iven you this to able to master loops and use them logically.
First pick your first number and assign it to high and low, don't worry it will make sense afterwards.
def centered average(nums):
high = nums[0]
small = nums[0]
Here is were the magic happens, you loop through your list and if the number your on in the loop is larger then the previous ones then you can replace the variable high with it, let me demonstrate.
for count in nums:
if count > high:
high = count
if count < low:
low = count
Now you have the low and the high all you do is add the values of the loop together minus the high and the low (as you said you do not need them).Then divide that answer by len of nums.
for count in nums:
sum = count + sum
sum = sum - (high + low)
return sum
New here. I like to check my solutions with solutions found on the internet and did not see my code here yet (hence the post). I found this challenge on https://codingbat.com/prob/p126968. And here is my solution:
** This is done in Python 3.9.1.
First the min and max are popped from the list with the index method. After it's just a simple avg calculation.
def centered_average(nums):
nums.pop(nums.index(max(nums)))
nums.pop(nums.index(min(nums)))
return sum(nums)/len(nums)
If I understand the question, this should work:
def centered_average(nums):
trim = sorted(nums)[1:-1]
return sum(trim) / len(trim)
def centered_average(nums):
nums = sorted(nums)
for i in range(len(nums)):
if len(nums)%2 != 0:
return nums[len(nums)/2]
else:
return ((nums[len(nums)/2] + nums[len(nums)/2 - 1]) / 2)
This is a very sub standard solution to the problem. This code is a bad code that does not take into account any consideration for complexity and space. But I think the thought process to be followed is similar to the steps in the code. This then can be refined.
def centered_average(nums):
#Find max and min value from the original list
max_value = max(nums)
min_value = min(nums)
#counters for counting the number of duplicates of max and min values.
mx = 0
mn = 0
sum = 0
#New list to hold items on which we can calculate the avg
new_nums = []
#Find duplicates of max and min values
for num in nums:
if num == max_value:
mx += 1
if num == min_value:
mn += 1
#Append max and min values only once in the new list
if mx > 1:
new_nums.append(max_value)
if mn > 1:
new_nums.append(min_value)
#Append all other numbers in the original to new list
for num in nums:
if num != max_value and num != min_value:
new_nums.append(num)
#Calculate the sum of all items in the list
for new in new_nums:
sum += new
#Calculate the average value.
avg = sum/len(new_nums)
return avg
def centered_average(nums):
min1=nums[0]
max1=nums[0]
for item in nums:
if item > max1:
max1 = item
if item < min1:
min1 = item
sum1=(sum(nums)-(min1+max1))/(len(nums)-2)
return sum1
simple solution
def centered_average(nums):
b=nums
ma=max(b)
mi=min(b)
l=(len(b)-2)
s=sum(b)-(ma+mi)
av=int(s/l)
return av
use sum function to sum the array
max and min functions to get the biggest and smallest number
def centered_average(nums):
return (sum(nums) - max(nums) - min(nums)) / (len(nums) - 2)
def centered_average(nums):
sorted_list = sorted(nums)
return sum(sorted_list[1:-1])/(len(nums)-2)
This will get the job done.
Python 3 Solution using list.index, list.pop, min and max functions.
def solution(input):
average = 0
minimum = min(input)
maximum = max(input)
input.pop(input.index(minimum))
input.pop(input.index(maximum))
average = round(sum(input) / len(input))
return average
def centered_average(nums):
nums.remove((min(nums)))
nums.remove((max(nums)))
new_nums=nums
count = 0
for i in range(len(new_nums)):
count+=1
ans=sum(new_nums)//count
return ans
def centered_average(nums):
maximums = []
minimums = []
sum_of_numbers = 0
length =len(nums) + (len(minimums)-1) + (len(maximums)-1)
for i in nums:
if i == max(nums):
maximums.append(i)
elif i == min(nums):
minimums.append(i)
else:
sum_of_numbers += i
if len(maximums)>=2 or len(minimums)>=2:
sum_of_numbers = sum_of_numbers + (max(nums)*(len(maximums)-1))(min(nums)*(len(minimums)-1))
return sum_of_numbers / length

Categories

Resources