I am tryint to write a mergesort in python , but the output was different when I input different list - mergesort

When my input is[6,5,4,3,2,1],the output is [1,2,3,4,5,6],
but when my input is[1,2,3,4,5,6],the output will become [1,1,1,1,1,1].
if there is a number that bigger than the number before it,the output will become wrong
def merge (arr,low,mid,high):
L=arr[low:mid+1]
R=arr[mid+1:high+1]
i=0
j=0
k=low
while i<len(L) and j<len(R):
if L[i]<=R[j]:
arr[k]=L[i]
i+=1
k+=1
else:
arr[k]=R[j]
j+=1
k+=1
while i<len(L):
arr[k]=L[i]
i+=1
k+=1
while j<len(R):
arr[k]=L[j]
j+=1
k+=1
def sort (arr,low,high):
if low<high:
mid=low+(high-low)//2
print(mid)
sort(arr,low,mid)
sort(arr,mid+1,high)
merge(arr,low,mid,high)
arr=[1,2,3,4,5]
print(arr)
sort(arr,0,len(arr)-1)
print(arr)

There is a problem here:
while j<len(R):
arr[k]=R[j] # this was arr[k]=L[j]
Typically merge sort has high set to ending index = 1 + last index. This means that sort will need to check for (high - low) > 1, but it eliminate the +1's.
def merge (arr,low,mid,high):
L=arr[low:mid]
R=arr[mid:high]
i=0
j=0
k=low
while i<len(L) and j<len(R):
if L[i]<=R[j]:
arr[k]=L[i]
i+=1
k+=1
else:
arr[k]=R[j]
j+=1
k+=1
while i<len(L):
arr[k]=L[i]
i+=1
k+=1
while j<len(R):
arr[k]=R[j]
j+=1
k+=1
def sort (arr,low,high):
if (high - low) > 1: # if < 2 elements, nothing to do
mid=low+(high-low)//2
sort(arr,low,mid)
sort(arr,mid,high)
merge(arr,low,mid,high)
arr=[3,2,1,5,4]
print(arr)
sort(arr,0,len(arr)) # len(arr) = ending index of arr
print(arr)

Related

Calculate bigrams co-occurrence matrix

I tried to ask a question regarding nathandrake's #nathandrake post: How do I calculate a word-word co-occurrence matrix with sklearn?
import pandas as pd
def co_occurance_matrix(input_text,top_words,window_size):
co_occur = pd.DataFrame(index=top_words, columns=top_words)
for row,nrow in zip(top_words,range(len(top_words))):
for colm,ncolm in zip(top_words,range(len(top_words))):
count = 0
if row == colm:
co_occur.iloc[nrow,ncolm] = count
else:
for single_essay in input_text:
essay_split = single_essay.split(" ")
max_len = len(essay_split)
top_word_index = [index for index, split in enumerate(essay_split) if row in split]
for index in top_word_index:
if index == 0:
count = count + essay_split[:window_size + 1].count(colm)
elif index == (max_len -1):
count = count + essay_split[-(window_size + 1):].count(colm)
else:
count = count + essay_split[index + 1 : (index + window_size + 1)].count(colm)
if index < window_size:
count = count + essay_split[: index].count(colm)
else:
count = count + essay_split[(index - window_size): index].count(colm)
co_occur.iloc[nrow,ncolm] = count
return co_occur
My question is: what if my words are not one word but bigrams. For example:
corpus = ['ABC DEF IJK PQR','PQR KLM OPQ','LMN PQR XYZ DEF ABC']
words = ['ABC PQR','PQR DEF']
window_size =100
result = co_occurance_matrix(corpus,words,window_size)
result
I changed the word list into a bigram list, then the co_occurance_matrix function is not working. All are showing 0.

First NeuroNetwork, troubles(

I've never done neural network development before, but it just so happens that I HAVE to do it before January 23, inclusive, or I will miss a huge number of opportunities. I get a huge bunch of mistakes that I don't know what to do with. Be so kind-correct my code and explain to me what I'm doing wrong) thank You all
UPD code:
import numpy as np
def Sigmoid(x):
return 1/(1+np.exp(-x))
trn_inp=np.array([[1],[2],[3]]) #Массив 3 на 1. 3 строки и 1 столбец
trn_out=np.array([[1,2,3]]).T #Ожидаемые выходные данные
print("trn_inp now: \n"+str(trn_inp))
print("trn_inp matrix: "+str(np.shape(trn_inp)))
print("trn_out now: \n"+str(trn_out))
print("trn-out matrix: \n"+str(np.shape(trn_out)))
np.random.seed(1)
syn_wei=2*np.random.random((1,1))-1 #Создается массив размером x на y, который заполняется рандомными значениями от -1 до 1
#print(syn_wei)
o=1
for i in range(100):
print("Try # "+str(o))
out=Sigmoid(np.dot(trn_inp, syn_wei))
err=trn_out-out
adj=np.dot(trn_inp.T,err*(out*(1-out)))
syn_wei+=adj
o+=1
print("=="*10)
print("New weights: ")
print(syn_wei)
print("=="*10)
print("Out after refresh: ")
print(out)
new_inp=np.array([[8,2,3]]).T #Введение нового значения для сравнения
out=Sigmoid(np.dot(new_inp, syn_wei))
print("New out: "+str(out))
print(out)
#out_str="".join(str(x) for x in out)
#print(out_str)
out_flt=0
for k in range(0,len(out)):
out_flt=out[k]
#print(out_flt)
if out_flt==0:
print("No matches")
elif out_flt>=0.5:
print("May have matches")
elif out_flt>=0.8:
print("Match")
else:
print("ERROR")
#out_flt=float(out_str)
#out_int=int(out_str)
#print("Results for new situation : "+out_str)

How to remove a single number from a list with multiples of that number

As I'm a beginner in coding I wanted to try to find the first three repeated numbers in a list. My problem is that in my code when there is a number repeated three, the code breaks.
The usual, remove, pop, and del, don't work as they delete one element in the list.
import random
r = random.randint
string = ""
def first_repeat(myList):
myList = sorted(list(myList))
print(myList)
number = 0
final_numbers = []
loop = 0
while loop < 2:
try:
if number == 0:
number += 1
else:
if myList[loop] == myList[loop-1]:
final_numbers.append(myList[loop])
else:
myList.pop(loop)
myList.pop (loop-1)
number = 0
if loop == 0 :
loop += 1
else:
loop -= 1
if len(final_numbers) > 3:
return final_numbers[0], final_numbers[1], final_numbers[2]
if len(myList) <=1:
loop += 2
except:
continue
return final_numbers
for n in range(20):
string = string+str(r(0,9))
print(first_repeat(string))
the expected result should be at the first three repeated numbers.
I added some print statements so you can go through your program and find out where the logic is wrong with your code.
import random
r = random.randint
string = ""
def first_repeat(myList):
myList = sorted(list(myList))
print(myList)
number = 0
final_numbers = []
loop = 0
while loop < 2:
print( 'inside while loop: loop = {}'.format( loop ))
try:
if number == 0:
number += 1
else:
if myList[loop] == myList[loop-1]:
print( 'in -> if myList[loop] == myList[loop-1]' )
final_numbers.append(myList[loop])
print( 'final_numbers: [{}]'.format( ','.join( final_numbers )))
else:
print( 'in first -> else' )
myList.pop(loop)
myList.pop (loop-1)
number = 0
print( 'myList: [{}]'.format( ','.join( myList ) ))
if loop == 0 :
loop += 1
else:
loop -= 1
if len(final_numbers) > 3:
print( 'returning final numbers' )
print( final_numbers )
return final_numbers[0], final_numbers[1], final_numbers[2]
if len(myList) <=1:
loop += 2
except:
continue
print( 'at end of this loop final numbers is: [{}]'.format( ','.join( final_numbers)))
print( 'press any key to continue loop: ')
input()
return final_numbers
for n in range(20):
string = string+str(r(0,9))
print(first_repeat(string))
Following is a method to do it taking advantage of pythons defaultdict
https://docs.python.org/2/library/collections.html#collections.defaultdict
#import defaultdict to keep track of number counts
from collections import defaultdict
#changed parameter name since you are passing in a string, not a list
def first_repeat( numbers_string ):
#create a dictionary - defaulddict( int ) is a dictionary with keys
#instantiated to 0 - (instead of throwing a key error)
number_count = defaultdict( int )
#convert your string to a list of integers - look up list iterations
numbers = [ int( s ) for s in list( numbers )]
# to store the repeated numbers
first_three_repeats = []
for number in numbers:
# for each number in the list, increment when it is seen
number_count[number] += 1
#at first occurence of 3 numbers, return the number
if number_count[number] == 2:
first_three_repeats.append( number )
if len( first_three_repeats ) == 3:
return first_three_repeats
#if here - not three occurrences of repeated numbers
return []
for n in range(20):
string = string+str(r(0,9))
print( findFirstThreeNumbers( string ))

Program not running with error unsupported operand type(s) for +: 'function' and 'int'

Im creating a program for NIM for my Python Intro class, and am having a problem with trying to get the program to finish.
I am at a loss...
def main():
import random
#User random to generate integer between 10 and 100 for random pile size of marbles.
ballCount = random.randint(10, 100)
print("The size of the pile is: ",ballCount)
#Generate a random integer between 0 and 1, this will tell if the human or computer takes first turn.
def playerTurn(ballCount):
playerTurn = random.randint(0, 1)
if playerTurn == 0:
print("Its the computers turn...")
else:
print("Its your turn...")
#Generate a random integer between 0 and 1, to determine if the computer is smart or dumb.
computerMode = random.randint(0, 1)
def computerDumbMode(ballCount):
computerMode = random.randint(0, 1)
if computerMode == 0:
print("This computer is very dumb, no need to stress")
def computerSmartMode(ballCount):
computerMode = random.randint(0, 1)
if computerMode == 1:
print("This computer is very intelligent, beware")
#In dumb mode the computer generates random values (between 1 and n/2),
#you will use a random integer n for ballCount, when it is the computers turn.
while ballCount != 1: #This will compile untill you are left with only one marble.
if playerTurn == 0: #This will initiate computers turn.
if computerMode == 1: #This will initiate Smart Mode.
temp = random.randint(1, ballCount/2) #Pick a random number between 1, and n/2.
else: # Pick your own number of Marbles for your ballCount (n).
if ballCount - 3 > 0 and ballCount - 3 < ballCount/2:
temp = ballCount - 3
elif ballCount - 7 > 0 and ballCount - 7 < ballCount/2:
temp = ballCount - 7
elif ballCount - 15 > 0 and ballCount - 15 < ballCount/2:
temp = ballCount - 15
elif ballCount - 31 > 0 and ballCount - 31 < ballCount / 2:
temp = ballCount - 31
else:
temp = ballCount - 63
print("The computer has chosen: %d marbles." % temp) #Print the number of marbles the computer has chosen.
ballCount -= temp #Then subtract the number of marbles chosen by the computer.
else:
ballCountToPick = int(input("It is now your turn, Please pick the number of marbles in the range 1 - %d: " % int(ballCount/2))) #Reads the number of marbles to be picked by user.
while ballCountToPick < 1 or ballCountToPick > ballCount/2: #If computer reads this invalidly, it will try repeatedly.
ballCountToPick = int(input("The number you chose, is incorrect. Try again, and pick marbles in the range 1 - %d: " % int(ballCount/2)))
ballCount -= ballCountToPick #Subtract the marbles that were chosen by user.
playerTurn = (playerTurn + 1) % 2 #Changes the turn of player.
print("Now the pile is of size %d." % ballCount)
if playerTurn == 0: #Show the outcome.
print("You came, you saw, and you won... CONGRATULATIONS!!!")
else:
print("Once again... You lost and the computer wins!!!")
main()
Trying to get the program/game to run and print end result if the computer or person wins!
Your "playerTurn" variable is a function in the following line:
playerTurn = (playerTurn + 1) % 2 #Changes the turn of player.
Have a separate "playerTurn" function and "player_turn" variable will resolve your problem.

find out min and max in python 3

5.2 Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter 7, 2, bob, 10, and 4 and match the output below.
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done":
break
print(num)
print("Maximum", largest)
and the output must be like this
Invalid input
Maximum is 10
Minimum is 2
somebody please help me with this????? enter image description here
I think this will do your work,
With simple if conditions
# Defining two variables to None.
largest = None
smallest = None
# starting an infinite loop
while True:
num = input("Enter a number: ")
# try block to capture ValueError
try:
if num == "done":
break
# assign the values of largest and smallest to num if its None ( on first iteration)
if largest is None:
largest = int(num)
if smallest is None:
smallest = int(num)
# changing the values of it greater or smaller
if int(num) > largest:
largest = int(num)
if int(num) < smallest:
smallest = int(num)
# capture the type error and ignores.
except ValueError:
print("ignored.")
continue
print("Maximum: " + str(largest))
print("Minimum: " + str(smallest))
By making use of list and it's methods
# Defining an empty list.
myList = []
# starting an infinite loop
while True:
num = input("Enter a number: ")
# try block to capture ValueError
try:
if num == "done":
break
# append the entered number to list if valid
myList.append(int(num))
# catches value error and ignores it
except ValueError:
print("ignored.")
continue
# prints maximum and min
if len(myList) > 0:
print("Maximum: " + str(max(myList)))
print("Minimum: " + str(min(myList)))
else:
print("List is empty")
largest = None
smallest = None
while True:
try:
num = input("Enter a number: ")
if num == "done":
break
num = int(num)
if largest is None or largest < num:
largest = num
elif smallest is None or smallest > num:
smallest = num
except ValueError:
print("Invalid input")
print ("Maximum is", largest)
print ("Minimum is", smallest)
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done" :
break
try:
n = int(num)
except:
print ('Invalid input')
continue
if largest is None or n > largest:
largest = n
if smallest is None or n < smallest:
smallest = n
print("Maximum is", largest)
print("Minimum is", smallest)
#Print out largest and smallest number
largest=None
smallest=None
while True:
n = input('Enter a number: ')
if n == "done":
break
try:
num=int(n)
if largest is None:
largest = num
elif num > largest:
largest = num
if smallest is None:
smallest = num
elif num < smallest:
smallest = num
except:
print("Invalid input")
print('maximum:', largest)
print('Minimum:', smallest)