Show the number that appears the most times in a row - python

How to code a program that shows me the item that appears most side-by-side?
Example:
6 1 6 4 4 4 6 6
I want four, not six, because there are only two sixes together.
This is what I tried (from comments):
c = int(input())
h = []
for c in range(c):
h.append(int(input()))
final = []
n = 0
for x in range(c-1):
c = x
if h[x] == h[x+1]:
n+=1
while h[x] != h[c]:
n+=1
final.append([h[c],n])
print(final)

Depends on what exactly you want for an input like
lst = [1, 1, 1, 2, 2, 2, 2, 1, 1, 1]
If you consider the four 2 the most common, because it's the longest unbroken stretch of same items, then you can groupby same values and pick the one with max len:
max((len(list(g)), k) for k, g in itertools.groupby(lst))
# (4, 2) # meaning 2 appeared 4 times
If you are interested in the element that appears the most often next to itself, you can zip the list to get pairs of adjacent items, filter those that are same, pass them through a Counter, and get the most_common:
collections.Counter((x,y) for (x,y) in zip(lst, lst[1:]) if x == y).most_common(1)
# [((1, 1), 4)] # meaning (1,1) appeared 4 times
For your example of 6 1 6 4 4 4 6 6, both will return 4.

maxcount=0; //store maximum number item side by side
num=-1; //store element with max count
for i=0 to n //loop through your array
count=0;
in=i;
while(arr[in++]==arr[i]){//count number of side by side same element
count++;
}
maxcount=max(maxcount,count);
num= maxcount==count? arr[i]:num;
i=in-1;
endfor;

Related

Finding number from list that respects conditions

I need to code a script that chooses a number from a user input (list) depending on two conditions:
Is a multiple of 3
Is the smallest of all numbers
Here is what I've done so far
if a % 3 == 0 and a < b:
print (a)
a = int(input())
r = list(map(int, input().split()))
result(a, r)
The problem is I need to create a loop that keeps verifying these conditions for the (x) number of inputs.
It looks like you want a to be values within r rather than its own input. Here's an example of iterating through r and checking which numbers are multiples of 3, and of finding the minimum of all the numbers (not necessarily only those which are multiples of 3):
r = list(map(int, input().split()))
for a in r:
if a % 3 == 0:
print(f"Multiple of 3: {a}")
print(f"Smallest of numbers: {min(r)}")
1 2 3 4 5 6 7 8 9 0
Multiple of 3: 3
Multiple of 3: 6
Multiple of 3: 9
Multiple of 3: 0
Smallest of numbers: 0
Doing this in one line – or through generators – can improve performance through optimizing memory allocation:
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# The following is a generator
# Also: you need to decide if you want 0 to be included
all_threes = (x for x in my_list if x%3==0)
min_number = min(my_list)

I need to python code to get sum of some of its k consecutive numbers in a list in python

#Given array of integers, find the sum of some of its k consecutive elements.
#Sample Input:
#inputArray = [2, 3, 5, 1, 6] and k = 2
#Sample Output:
#arrayMaxConsecutiveSum(inputArray, k) = 8
#Explaination:
#All possible sums of 2 consecutive elements are:
#2 + 3 = 5;
#3 + 5 = 8;
#5 + 1 = 6;
#1 + 6 = 7.
#Thus, the answer is 8`
Your question is not clear but assuming you need a function to return the sum of the highest pair of numbers in your list:
def arrayMaxConsecutiveSum(inputArray, k):
groups = (inputArray[pos:pos + k] for pos in range(0, len(inputArray), 1)) # iterate through array creating groups of k length
highest_value = 0 # start highest value at 0
for group in groups: # iterate through groups
if len(group) == k and sum(group) > highest_value: # if group is 2 numbers and value is higher than previous value
highest_value = sum(group) # make new value highest
return highest_value
inputArray = [2, 3, 5, 1, 6]
print(arrayMaxConsecutiveSum(inputArray, 2))
#8

How to find how many values are divisible in to certain value in 2d array in python

The following code generate random number of 2d arrays and I want to print how many values in each pair are divisible to 3. For example assume we have an array [[2, 10], [1, 6], [4, 8]].
So the first pair which is [2,10] has 3 ,6 and 9 which are totally 3 and second pair has 3 and 6 which are totally two and last pair[4,8] has just 1 divisible to 3 which is 6. Therefore, The final out put should print sum of total number of divisible values which is 3+2+1=6
a=random.randint(1, 10)
b = np.random.randint(1,10,(a,2))
b = [sorted(i) for i in b]
c = np.array(b)
counter = 0;
for i in range(len(c)):
d=(c[i,0],c[i,1])
if (i % 3 == 0):
counter = counter + 1
print(counter)
One way is to count how many integers in the interval are divisible by 3 by testing each one.
Another way, and this is much more efficient if your intervals are huge, is to use math.
Take the interval [2, 10].
2 / 3 = 0.66; ceil(2 / 3) = 1.
10 / 3 = 3.33; floor(10 / 3) = 3.
Now we need to count how many integers exist between 0.66 and 3.33, or count how many integers exist between 1 and 3. Hey, that sounds an awful lot like subtraction! (and then adding one)
Let's write this as a function
from math import floor, ceil
def numdiv(x, y, div):
return floor(y / div) - ceil(x / div) + 1
So given a list of intervals, we can call it like so:
count = 0
intervals = [[2, 10], [1, 6], [4, 8]]
for interval in intervals:
count += numdiv(interval[0], interval[1], 3)
print(count)
Or using a list comprehension and sum:
count = sum([numdiv(interval[0], interval[1], 3) for interval in intervals])
You can use sum() builtin for the task:
l = [[2, 10], [1, 6], [4, 8]]
print( sum(v % 3 == 0 for a, b in l for v in range(a, b+1)) )
Prints:
6
EDIT: To count number of perfect squares:
def is_square(n):
return (n**.5).is_integer()
print( sum(is_square(v) for a, b in l for v in range(a, b+1)) )
Prints:
5
EDIT 2: To print info about each interval, just combine the two examples above. For example:
def is_square(n):
return (n**.5).is_integer()
for a, b in l:
print('Pair {},{}:'.format(a, b))
print('Number of divisible 3: {}'.format(sum(v % 3 == 0 for v in range(a, b+1))))
print('Number squares: {}'.format(sum(is_square(v) for v in range(a, b+1))))
print()
Prints:
Pair 2,10:
Number of divisible 3: 3
Number squares: 2
Pair 1,6:
Number of divisible 3: 2
Number squares: 2
Pair 4,8:
Number of divisible 3: 1
Number squares: 1

How to use 2 index variable in a single for loop in python

In C language we can use two index variable in a single for loop like below.
for (i = 0, j = 0; i < i_max && j < j_max; i++, j++)
Can some one tell how to do this in Python ?
With zip we can achieve this.
>>> i_max = 5
>>> j_max = 7
>>> for i, j in zip(range(0, i_max), range(0, j_max)):
... print str(i) + ", " + str(j)
...
0, 0
1, 1
2, 2
3, 3
4, 4
If the first answer does not suffice; to account for lists of different sizes, a possible option would be:
a = list(range(5))
b = list(range(15))
for i,j in zip(a+[None]*(len(b)-len(a)),b+[None]*(len(a)-len(b))):
print(i,j)
Or if one wants to cycle around shorter list:
from itertools import cycle
for i,j in zip(range(5),cycle(range(2)):
print(i,j)
One possible way to do that is to iterate over a comprehensive list of lists.
For example, if you want to obtain something like
for r in range(1, 3):
for c in range(5, 7):
print(r, c)
which produces
# 1 5
# 1 6
# 2 5
# 2 6
is by using
for i, j in [[_i, _j] for _i in range(1, 3) for _j in range(5, 7)]:
print(i, j)
Maybe, sometimes one more line is not so bad.
You can do this in Python by using the syntax for i,j in iterable:. Of course in this case the iterable must return a pair of values. So for your example, you have to:
define the list of values for i and for j
build the iterable returning a pair of values from both lists: zip() is your friend in this case (if the lists have different sizes, it stops at the last element of the shortest one)
use the syntax for i,j in iterable:
Here is an example:
i_max = 7
j_max = 9
i_values = range(i_max)
j_values = range(j_max)
for i,j in zip(i_values,j_values):
print(i,j)
# 0 0
# 1 1
# 2 2
# 3 3
# 4 4
# 5 5
# 6 6

Constructing Lists

I'm new to Python and I came across the following query. Can anyone explain why the following:
[ n**2 for n in range(1, 6)]
gives:
[1, 4, 9, 16, 25]
It is called a list comprehension. What is happening is similar to the following:
results = []
for n in range(1,6):
results.append(n**2)
It therefore iterates through a list containing the values [0, 1, 2, 3, 4, 5] and squares each value. The result of the squaring is then added to the results list, and you get back the result you see (which is equivalent to 0**2, 1**2, 2**2, etc., where the **2 means 'raised to the second power').
This structure (populating a list with values based on some other criteria) is a common one in Python, so the list comprehension provides a shorthand syntax for allowing you to do so.
Breaking it down into manageable chunks in the interpreter:
>>> range(1, 6)
[1, 2, 3, 4, 5]
>>> 2 ** 2 # `x ** 2` means `x * x`
4
>>> 3 ** 2
9
>>> for n in range(1, 6):
...   print n
1
2
3
4
5
>>> for n in range(1, 6):
... print n ** 2
1
4
9
16
25
>>> [n ** 2 for n in range(1, 6)]
[1, 4, 9, 16, 25]
So that's a list comprehension.
If you break it down into 3 parts; separated by the words: 'for' and 'in' ..
eg.
[ 1 for 2 in 3 ]
Probably reading it backwards is easiest:
3 - This is the list of input into the whole operation
2 - This is the single item from the big list
1 - This is the operation to do on that item
part 1 and 2 are run multiple times, once for each item in the list that part 3 gives us. The output of part 1 being run over and over, is the output of the whole operation.
So in your example:
3 - Generates a list: [1, 2, 3, 4, 5] -- Range runs from the first param to one before the second param
2 - 'n' represents a single number in that list
1 - Generates a new list of n**2 (n to the power of 2)
So an equivalent code would be:
result = []
for n in range(1, 6):
result.append(n**2)
Finally breaking it all out:
input = [1, 2, 3, 4, 5]
output = []
v = input[0] # value is 1
o = v**2 # 1 to the power of two is 1
output.append(o)
v = input[1] # value is 2
o = v**2 # 2 to the power of two = (2*2) = 4
output.append(o)
v = input[2] # value is 3
o = v**2 # 3 to the power of two is = (3*3) = 9
output.append(o)
v = input[3] # value is 4
o = v**2 # 4 to the power of two is = (4*4) = 16
output.append(o)
v = input[4] # value is 5
o = v**2 # 5 to the power of two is = (5*5) = 25
output.append(o)

Categories