text
stringlengths
37
1.41M
""" The training grounds for the AI """ # Imported Modules from check_ai import CheckersAI from checkers_3 import Checkers # Global Variables aiPlayers = [] # Pits two AI against each other in a game of Checkers def aiMatch(player1,player2): players = [player1,player2] game = Checkers() while not game.gameOver: moves = game.possibleMoves() bestMove = players[game.currentPlayer].determineMove(game.board,moves,game.currentPlayer) game.takeTurn(bestMove) #print("Score: p1 has",game.p1Pieces,"pieces left and p2 has",game.p2Pieces,"pieces left.") if game.p1Pieces > game.p2Pieces: player1.winRound() if game.p2Pieces > game.p1Pieces: player2.winRound() # Trains incoming AI to determine who is the best def checkersAiDojo(rounds): # 1. Create a list of 20 AI for i in range(20): aiPlayers.append(CheckersAI()) # 6. Repeat 2-5 10 times for p in range(rounds): # 2. Cycle through every potential pairing and pit them against each other for j in range(len(aiPlayers)): for k in range(j+1, len(aiPlayers)): if j != k: aiMatch(aiPlayers[j],aiPlayers[k]) # 3. Order the list by highest round scores to lowest for l in range(1, len(aiPlayers)): for m in range(l-1, -1, -1): if aiPlayers[m+1].roundWins > aiPlayers[m].roundWins: temp = aiPlayers[m+1] aiPlayers[m+1] = aiPlayers[m] aiPlayers[m] = temp else: break # 4. Print out the total wins of the top 5 and reset their round wins print("The winners for this round have total scores of", aiPlayers[0].totalWins, aiPlayers[1].totalWins, aiPlayers[2].totalWins, aiPlayers[3].totalWins, "and", aiPlayers[4].totalWins, ) for n in range(5): aiPlayers[n].roundWins = 0 # 5. Create new 15 new ai to replace the lowest scoring ones for o in range(5,20): aiPlayers[o] = CheckersAI() # Allows a human to play against one of the AI from the dojo def aiVsHuman(ai): game = Checkers() humanTurn = int(input("Do you wish to go first (0) or second (1)?\n")) print("The Board:") if humanTurn == 1: game.printReadableBoard() while not game.gameOver: if game.currentPlayer == humanTurn: move = game.humanMove(game.board) if len(move)==0: game.gameOver=True else: game.takeTurn(move) else: moves = game.possibleMoves() bestMove = ai.determineMove(game.board,moves,game.currentPlayer) game.takeTurn(bestMove) print("\n","The board after the AI move:") # Call the dojo function checkersAiDojo(10) # Would you like to play a game? aiVsHuman(aiPlayers[0]) # End of file
#Consider the following dataset. How do you use the Candidate Elimination algorithm when the first example is negative? #Implement the algorithm for the same. from os import sep import numpy as np import pandas as pd #algo def candidate_elimination(concepts, target): specific_h = concepts[1].copy() general_h = [["?" for i in range(len(specific_h))] for i in range(len(specific_h))] print("Initialization of Specific hypotheses and General hypotheses") print("Specific hypotheses \n", specific_h) print("General hypotheses \n", general_h) print("\nCandidate Elimination Algorithm: \n") for i, h in enumerate(concepts): if target[i] == "yes": print("If instance is Positive ", end="") for x in range(len(specific_h)): if h[x]!= specific_h[x]: specific_h[x] ='?' general_h[x][x] ='?' if target[i] == "no": print("If instance is Negative ", end="") for x in range(len(specific_h)): if h[x]!= specific_h[x]: general_h[x][x] = specific_h[x] else: general_h[x][x] = '?' print("steps of Candidate Elimination Algorithm(Step {})".format(i+1)) print("Specific hypotheses \n", specific_h) print("General hypotheses \n", general_h) print("\n") indices = [i for i, val in enumerate(general_h) if val == ['?', '?', '?', '?', '?']] for i in indices: general_h.remove(['?', '?', '?', '?', '?']) return specific_h, general_h #take input def main(): data = pd.read_csv('/home/dhanrz/Old Folder/6SEM/ML_1BM18CS027/labtest1/buys.csv') print("Data from Given csv File: ") concepts = np.array(data.iloc[:,0:-1]) print('Concepts:',*concepts, sep='\n') target = np.array(data.iloc[:,-1]) print("Target \n",target,"\n\n") finalS, finalG = candidate_elimination(concepts, target) print("Final specific_h:", finalG, sep="\n") print("Final general_h:", finalG, sep="\n") main()
from array import * x = int(input("Tal 1:")) y = int(input("Tal 2:")) arr = array("i", [x, y]) arr.reverse() print(arr)
####################################### # Automate the boring Stuff with Python ####################################### # Chapter 1 # Self learning from Python Documentation ####################################### # Absolute """ print('find absolute of the number') print('Enter any number\n') num1 = input() print("Absolute number is "+str(abs(float(num1)))) """ #All ## check if all elements are True ## In dict, check if all keys are 'True' """ fruits_dict = { 1: "Apple", 1: "Oranges", 1: "Peach", } print("Healthy fruit basket? \n") x = all(fruits_dict) if(x): print("yes!") else: print('no') """ #Any ## check if any elements is True ## In dict, check if any key is 'True' fruits_dict = { 1: "Apple", 1: "Oranges", 0: "Peach", } print("Healthy fruit basket? \n") x = any(fruits_dict) if(x): print("yes!") else: print('no') # ASCII - printable version of any object print(ascii(fruits_dict))
def bruteForce(W,berat,nilai,deep,n,kondisi): if deep == n: cost = 0 val = 0 x = '' for i in range(n): if kondisi[i] : cost = cost + berat[i] val = val + nilai[i] x = x + str(i+1) + ' ' if cost <= W and cost != 0: print(x, ' cost : ', 'value : ', val) else: kondisi[deep] = True bruteForce(W,berat,nilai,deep+1,n,kondisi) kondisi[deep] = False bruteForce(W,berat,nilai,deep+1,n,kondisi) def Knapsack(Wmax,berat,nilai,n): #Wmax untuk max, berat dan nilai array dengan panjang n #K adalah tabel hasil setiap iterasi yang berisi nilai dari setiap tahap #K array 2 dimensi K[i][w] menyimpan nilai tahap ke-i dengan nilai w #function mengembalikan max nilai K = [[0 for x in range(Wmax + 1)] for x in range(n + 1)] for i in range(n+1): print() print("Tahap ke-",i) for w in range(Wmax+1): if i==0 or w == 0: #basis f0(y) K[i][w] = 0 elif berat[i-1] <= w: #rekurens beratw <= Wmax K[i][w] = max(K[i-1][w],nilai[i-1] + K[i-1][w-berat[i-1]]) else: #beratw > Wmax K[i][w] = K[i-1][w] #Output pertahap print("y=",w," | F",i-1,"(y)=",K[i-1][w]," | max(F",i,"(y))= ",K[i][w]) return K[n][Wmax] def inputBeratNilai(): #init #W kapasitas, nilai dan berat dengan panjang n nilai = [45,10,25,30,16,12] berat = [10,5,2,5,8,8] W = 18 n = len(nilai) kondisi=[False]*n print("Knapsack Dynamic Programming") print(Knapsack(W,berat,nilai,n)) print() print("Knapsack bruteforce") bruteForce(W,berat,nilai,0,n,kondisi) #Main inputBeratNilai()
from task_5 import* genre_list=[] diffrent_genre=[] dublicate_genre=[] genre_dict={} def analyse_movies_genre(movies_list): for name in movies_list: # print (name) movie_genre=name["genre"] genre_list.append(movie_genre) # print (genre_list) for a in genre_list: for b in a: diffrent_genre.append(b) # print diffrent_genre for i in diffrent_genre: if i not in dublicate_genre: dublicate_genre.append(i) # print dublicate_genre for c in dublicate_genre: count=0 for d in diffrent_genre: if c == d: count=count+1 genre_dict[c]=count return (genre_dict) data_5=analyse_movies_genre(data2) pprint (data_5) ######eleven task completed
#fibonacci series print("\twelcome to the program") print("we are going to find the fibonancy series as per your input number of terms\n") x=0 y=1 n = int(input("enter the term till which you want to find the fibonancy series=")) i=3 print(x,y,sep=',',end=',') while i<=n: sum=x+y x=y y=sum if i<n: print(sum,end=',') else: print(sum) i +=1 print("here is your fibonacci series")
#find the type of triangle print("\twelcome to the progarm") print("we will find the type of triangle by your input angle") print("you ust input the angle of triangle in degree\n") a = int(input("enter the first angle =")) b = int(input("enter the second angle =")) c = int(input("enter the third angle =")) sum = a+b+c if sum == 180 and a!=0 and b!=0 and c!=0: if a<90 and b<90 and c<90: print("AS PER YOUR INPUTS OF ANGLE THE TRIANGLE IS ACUTE ANGLE TRIANGLE.") elif a==90 or b==90 or c==90: print("AS PER YOUR INPUTS OF ANGLE THE TRIANGLE IS RIGHT ANGLE TRIANGLE.") else: print("AS PER YOUR INPUTS OF ANGLE THE TRIANGLE IS OBTUSE ANGLE TRIANGLE.") else: print("sorry!!!\nyou have entered wrong angles,the sum of the angles must be 180 degree and angle must have a proper value.")
#function print("\n\t..........|| WELCOME TO THE PROGRAM ||.............") print("PLEASE ENTER THE INTEGERS FOR THE LIST.\n") list_numbers=[] num=int(input("ENTER NUMBER OF INTEGERS IN THE LIST :- ")) for i in range(num): item=int(input("ENTER THE INTEGER {} = ".format(i+1))) list_numbers.append(item) def ascending(l): l.sort() print("SORTING THE LSIT IN ASCENDING ORDER :- ",l) def descending(l): l.sort(reverse=True) print("SORTING OF THE LIST IN DESCENDING ORDER :-",l) i=0 print("\n..PLEASE SELECT 1 FOR SORTING IN ASCENDING ORDER AND 2 FOR DESCENDING ORDER...\n") while i<1: n=int(input("PLEASE ENTER YOUR OPTION :- ")) if n==1: ascending(list_numbers) i+=1 elif n==2: descending(list_numbers) i+=1 else: print("PLEASE SECLECT PROPER OPTION. \nSELECT 1 FOR SORTING IN ASCENDING ORDER AND 2 FOR DESCENDING ORDER.")
#to count the number of upper case letters and lower case letters and numbers of digits print("\n\t......WELCOME........") print("lets count number of upper case and lower case alphabets and number of digits present in your entered string.\n") string=input("enter the string :- ") i=0 count_lower=0 count_upper=0 count_digit=0 while i<len(string): if string[i].islower() == True: count_lower+=1 elif string[i].isupper() == True: count_upper+=1 elif string[i].isdigit() == True: count_digit+=1 i+=1 print("NUMBER OF LOWER CASE ALPHABETS IN YOU ENTERED STRING = ",count_lower) print("NUMBER OF UPPER CASE ALPHABETS IN YOU ENTERED STRING = ",count_upper) print("NUMBER OF DIGITS IN YOU ENTERED STRING = ",count_digit)
#to check weather entered character is an alphabet print("\n\t.......WELCOME TO THE PROGRAM.........") print("we will check wether your entered chacrcter is an alphabet.\n") x=input("Enter an charcter :- ") if (ord(x)>=65 and ord(x)<=90)or(ord(x)>=97 and ord(x)<=122): print("The character '",x,"' is an aplhabet.") else: print("The character '",x,"' is not an aplhabet.")
#examples for function print("\n\t..........|| WELCOME TO THE PROGRAM ||.............") print("\n") def swap_num(a,b): c=a a=b b=c print("\nINSIDE FUNCTION :\n a :- {}\nb :- {}".format(a,b)) a=int(input("enter a = ")) b=int(input("enter b = ")) print("\nBEFORE FUNCTION CALL :\n a :- {}\nb :- {}".format(a,b)) swap_num(a,b) print("\nBEFORE FUNCTION CALL :\n a :- {}\nb :- {}".format(a,b))
#calculation of total marks and average marks and result as pass or fail print("\n\t...........WELCOME..........\n") print("please enter all the marks of class 12th out of 100 properly to find the proper result.\nALL THE BEST......\n") sub_eng=float(input("ENTER THE MARKS OF ENGLISH = ")) assert sub_eng >=0 and sub_eng<=100 sub_math=float(input("ENTER THE MARKS OF MATH = ")) assert sub_math >=0 and sub_math<=100 sub_phy=float(input("ENTER THE MARKS OF PHYSICS = ")) assert sub_phy >=0 and sub_phy<=100 sub_chem=float(input("ENTER THE MARKS OF CHEMISTRY = ")) assert sub_chem >=0 and sub_chem<=100 sub_comp=float(input("ENTER THE MARKS OF COMPUTER SCIENCE = ")) assert sub_comp >=0 and sub_comp<=100 total_marks=sub_eng+sub_math+sub_phy+sub_chem+sub_comp avg_marks=total_marks/5 if sub_eng>=50 and sub_math>=50 and sub_phy>=50 and sub_chem>=50 and sub_comp>=50: print("\n....CONGRATS...\nyou have passed your examination.") else: print("\n!!!!!!YOU HAVE FAILED THE EXAMINATION.") print("BETTER LUCK NEXT TIME FOR YOUR EXAM.") print("YOUR TOTAL MARKS = ",total_marks) print("YOUR AVERAGE MARKS = ",avg_marks)
#find the slope of 2d curve print("\twelcome to the program") print("you have to enter two different cordinates of the curve.\n") print("enter the cordinate 1") x1=float(input("enter the x value=")) y1=float(input("enter the y value=")) print("\nenter the cordinate 2") x2=float(input("enter the x value=")) y2=float(input("enter the y value=")) slope=(y2-x2)/(y1-x1) print("the slope of the graph is=",slope)
#dictionary print("\n\t..........|| WELCOME TO THE PROGRAM ||.............") student_dict={'Name': 'UMESH', 'ENGLISH': 94, 'MATH': 95, 'PHYSICS': 95, 'CHEMISTRY': 95, 'COMPUTER': 100, 'Result': '<<..PASS..>>'} # accesing the iteams n=student_dict['Name'] print(n,"\n") for i in student_dict: #accesing through loop x=student_dict.get(i) #using get function in dictionary print(x) # changing value student_dict['ENGLISH']=90 student_dict['MATH']=98 # printing all the values for j in student_dict: print(student_dict[j]) print("\n") #acessing throgh the values function for k in student_dict.values(): print(k) print("\n") #to pront both key and values through item function for x,y in student_dict.items(): print(x," : ",y) print("\n") #to check if key exist or not check=input("enter the key you want to check in the student dcitionary :- ") if check in student_dict: print("THE KEY ",check," EXIST IN TEH STUDENT DICTIONARY.") else: print("THE KEY ",check," DOES NOT EXIST IN TEH STUDENT DICTIONARY.") print("\n") #to check the length of dictionary length=len(student_dict) print("THERE ARE ",length," ITEAMS IN THE STUDENT DICTIONARY.")
def vowel_count(string): #list of vowels vowels= {"a":0,"e":0,"i":0,"o":0,"u":0} #loops through vowels #appends value if key appears more than once for key, value in vowels.items(): for i in string: if i == key: vowels[key]+= 1 return vowels print(vowel_count("mike tyson can fight"))
#!/bin/python3 import sys n = int(input().strip()) a = list(map(int, input().strip().split(' '))) swaps_total = 0 # count the total number of swaps done to sort the list for i in range(0,len(a)): # bubble sort: conduct loops for (the num of element) times num_of_swaps = 0 # count the number of swaps per one loop for j in range(0,len(a)-1): # one-loop process: comparision of two adjacent elements if a[j] > a[j+1]: # if the left element is larger than the right element a[j], a[j+1] = a[j+1], a[j] # swap the two adjacent elements num_of_swaps += 1 swaps_total += 1 if num_of_swaps == 0: # if all elements are in order (sorted), finish the swapping process break print('Array is sorted in {} swaps.'.format(swaps_total)) print('First Element: {}'.format(a[0])) print('Last Element: {}'.format(a[len(a)-1]))
def minmax(state, depth=2): def ft_max(state, alpha, beta, d): if state.is_terminal() or d >= depth: return state.heuristic_value node_value = float('-inf') for i, move in enumerate(state.available_moves): node_value = max(node_value, ft_min(state.next_state(move),alpha, beta, d+1)) if node_value >= beta: return node_value alpha = max(alpha, node_value) # print("alpha", alpha) return node_value def ft_min(state, alpha, beta, d): if state.is_terminal() or d >= depth: return state.heuristic_value node_value = float('inf') for i, move in enumerate(state.available_moves): node_value = min(node_value, ft_max(state.next_state(move),alpha, beta, d+1)) if node_value <= alpha: return node_value beta = min(beta, node_value) # print("beta", beta) return node_value alpha = float('-inf') beta = float('inf') node_value = float('-inf') next_move = state.available_moves[0] print(next_move) for i, move in enumerate(state.available_moves): neirval = ft_min(state.next_state(move), alpha, beta, 1) if neirval > node_value: node_value = neirval next_move = move alpha = max(alpha, node_value) # print(next_move) return next_move
revenue = int(input("Введите сумму выручки фирмы в $: ")) costs = int(input("Введите сумму издержек фирмы в $: ")) profit = None loss = None if revenue - costs >= 0: profit = revenue - costs print(f"Ваша прибыль составляет: {profit}$") else: loss = costs - revenue print(f"Сумма ваших убытков составляет: {loss}$") if profit: profitability = revenue / profit * 100 profitability = round(profitability, 2) print(f"Рентабельность выручки: {profitability}%") staff = int(input("Введите кол-во сотрудников: ")) profit_per_one = profit / staff profit_per_one = round(profit_per_one, 2) print(f"Прибыль в расчёте на одного сотрудника: {profit_per_one}$")
class Room(): def __init__(self, chart, name, description, x = 0, y = 0): self.name = name self.description = description self.x = x self.y = y self.coordinates = [self.x, self.y] self.map = chart #items in the room self.items = {} #if the player doesn't explore, the interactive items arent'available self.interactive_items = {} self.chart(chart) #stores rooms in map and checks if there's another with same name or position def chart(self, chart): storage = all(value != self.coordinates for value in chart.structure.values()) if storage: chart.structure[self] = self.coordinates else: raise Exception("Coordinates already existing, please change room's x and y parameters.") #setters def set_name(self, name): self.name = name def set_coordinates(self, name): self.coordinates = coordinates #changes map def set_map(self, chart): del self.map.structure[self.name] self.chart(chart) self.map = chart
string = "Hello World" new_string = '' for i in string: if i == 'e': new_string += 'o' elif i == 'o': new_string += 'e' else: new_string += i string = new_string print(string)
INT_MAX = 999 #This function calculates the closest vertex to visit next def min_wt(nv, evalues, vlist): min, min_index = INT_MAX, 0 for i in range(nv): if vlist[i] == False and evalues[i] < min: min = evalues[i] min_index = i return min_index #Performs Prims' method for finding MCST def prims(nv, graph): parent = [0] * nv vlist = [False] * nv evalues = [INT_MAX] * nv parent[0] = -1 for i in range(nv-1): u = min_wt(nv, evalues, vlist) vlist[u] = True for v in range(nv): if graph[u][v] != INT_MAX and vlist[v] == False and graph[u][v] < evalues[v]: evalues[v] = graph[u][v] parent[v] = u cost = 0 for i in range(1, nv): print("%d - %d = %d\n" % (parent[i]+1, i+1, evalues[i]), end="") cost += evalues[i] print("The cost is %d" % cost) #Main block nv = int(input("Enter the number of vertices in the graph: ")) graph = [0] * nv print("Enter the adjacency matrix of the graph: ") for i in range(nv): graph[i] = [0] * nv for j in range(nv): if i == j: graph[i][j] = INT_MAX else: graph[i][j] = int(input()) prims(nv, graph)
list = [1,2,3,4,5,6,7,8,9,10] for i in list: print (i, end="") #end statement is used so that python doesn't print all numbers in new lines.
def run(): # for contador in range(1001): # if contador%2 != 0: # continue # print(contador) # for i in range(10000): # print(i) # if i==5678: # break # texto=input('Escribe un texto: ').upper() # for letra in texto: # if letra=='O': # break # print(letra) # LIMITE=int(input('Ingrese un límite: ')) # omit=int(input('Omitir multiplos de: ')) # i=0 # while i < LIMITE: # i+=1 # if i % omit ==0:#i es multiplo # continue # print(str(i))#omitirlo print(""" Contador de vocales y consonantes en una frase """) frase=input('Ingresa una frase: ').strip() largo=(len(frase)) v=0 #contador de vocales e=0 #contador de caracteres especiales vocales=("a", "e","i","o","u") especiales=("!",'@','$','&','?','¿') for i in range(0,largo): if frase[i] in vocales: v+=1 if frase[i] in especiales: e+=1 c=largo-v-e print('Tu frase tiene: ' +str(v)+' vocales, '+str(c)+ ' consonantes\n'+ 'y '+str(e)+' caracteres especiales') if __name__=='__main__': run()
class Coordenada: def __init__(self, x, y): self.x = x self.y = y def calcular_distancia(self, coordenada): a = abs(self.x - coordenada.x) b = abs(self.y - coordenada.y) return (a**2 + b**2)**0.5
from math import floor def legendre(n, p): pow = 0 k = 1 while True: val = floor(n / p**k) if val == 0: return pow pow += val k += 1 MOD = 1000000009 N = 100000000 if __name__ == '__main__': primes = [] ans = 1 with open('primes', 'r') as primes_file: for line in primes_file.readlines(): p = int(line) leg = legendre(N, p) ans *= 1 + (p, 2*leg, MOD) if ans > MOD: ans %= MOD print(p) print(ans)
orderedList = [1,2,3,4] reverseOrderedList = orderedList.reverse() numbers = open("numbers.txt") #numbersList = numbers.split('\n') #print(numbers.readline()) numList = [] for number in numbers: numList.append(int(number)) print(int(number)) print(numList) reversedList = numList.reverse() sortedList = numList.sort() print("reversedList - ",reversedList,"|| sortedList - ",sortedList) numbers.close
#%% import os import csv # Path to collect data from the Resources folder wrestling_csv = 'C://Users/josrh/Desktop/Stuff/ClassRepo/Module-8/wrestling_functions/Resources/WWE-Data-2016.csv' # Define the function and have it accept the 'wrestlerData' as its sole parameter def print_percentages(wrestlerData): Name = wrestlerData[0] Wins = int(wrestlerData[1]) Losses = int(wrestlerData[2]) Draws = int(wrestlerData[3]) # Find the total number of matches wrestled total = Wins + Losses + Draws # Find the percentage of matches won percent_won = Wins / total * 100 # Find the percentage of matches lost percent_lost = Losses / total * 100 # Find the percentage of matches drawn percent_draw = Draws / total * 100 # Super or Not? if Losses < 50: status = 'Superstar' else: status = 'Jobber' # Print out the wrestler's name and their percentage stats print(f'Stats for {Name}\n' f'WIN PERCENT: {percent_won}\n' f'LOSS PERCENT: {percent_lost}\n' f'DRAW PERCENT: {percent_draw}\n' f'{Name} is a {status}') # Read in the CSV file continues = 'y' while continues == 'y': with open(wrestling_csv, 'r') as csvfile: # Split the data on commas csvreader = csv.reader(csvfile, delimiter=',') # Prompt the user for what wrestler they would like to search for name_to_check = input("What wrestler do you want to look for? ") # Loop through the data for row in csvreader: # If the wrestler's name in a row is equal to that which the user input, run the 'print_percentages()' function if(name_to_check == row[0]): print_percentages(row) continues = input('Do you wish to continue? (y/n)') if continues == 'n': break # %%
#!/usr/bin/env python # coding: utf-8 # In[22]: #Memozining Approach for Knapsack Problem #Defining a -1 matrix t=[[-1 for i in range(capacity+1)] for x in range(n+1)] #Defining the knapsack function def knapsack(value,weight,capacity,n): #If there is no capacity or no item if(value==0 or n==0): return 0 #Checking the memozizied matrix elif(t[n][capacity]!=-1): return t[n][capacity] #Defining reccursive function elif(weight[n-1]<=capacity): return max(value[n-1]+ knapsack(value,weight,capacity-weight[n-1],n-1),knapsack(value,weight,capacity,n-1)) #Checking the function when capacity is higher else: return knapsack(value,weight,capacity,n-1) # In[23]: #Driver Function value=[100,300,120] weight=[10,20,30] capacity=50 n=len(value) print(knapsack(value,weight,capacity,n)) # In[ ]:
# Convert the keys and values of a dictionary to elements of a tuple my_dict = { "Speros": "(555) 555-5555", "Michael": "(999) 999-9999", "Jay": "(777) 777-7777" } # Clean way def dict_to_tuple(dictionary): return tuple(my_dict.items()) print dict_to_tuple(my_dict)
# Instructions at https://www.hackerrank.com/challenges/defaultdict-tutorial """ Run this program with a redirect to an input file like so: $ python defaultDict.py < test.txt """ # Instructions at https://www.hackerrank.com/challenges/defaultdict-tutorial # import sys from collections import defaultdict # Both of these methods work n, m = input().split() # n, m = sys.stdin.readline().split() # print (type(n),' ',type(m)) n = int(n) m = int(m) a = defaultdict(list) for i in range(1, n + 1): a[input()].append(i) for i in range(1, m + 1): key = input() if len(a[key]) > 0: jjaguar = " ".join(str(c) for c in a[key]) # print (jjaguar) else: print (-1) sys.stdout.write(jjaguar) # input format of data is somewhat unclear # my_input = "5 2\na\na\nb\na\nb\na\nb"
# Make a generator that outputs the fibonacci sequence starting at a and b # and ending before an number s def fibonacci_generator(a, b, s): # Validate inputs inputList = [a, b, s] print(inputList) for value in inputList: try: # Necessary because int(0.11) won't throw a ValueError but # int("0.11") will. int(str(value)) except ValueError: break while True: yield a a, b = b, a + b if (b > s): break for i in fibonacci_generator(0, 1, 8): print(i)
import random import numpy as np import matplotlib.pyplot as plt class Sampling: def __init__(self, a=0, b=20, fator=10.): self.a = a self.b = b self.nome = "Amostragem aleatória" #increasing the number os samples without any changes to the sampling's region of this example X = [x/fator for x in range(int(self.a*fator),int(self.b*fator))] Y = self.samples(X) Ind = np.zeros(len(X)) for i in range(len(X)): Ind[i] = int(X[i]*fator) self.plot(Ind,Y) def plot(self, X, Y): plt.plot(X,Y) plt.title(self.nome) plt.ylabel("Amostra") plt.xlabel("Indice") plt.show() def samples(self, x_r = [1,2,3,4]): random.seed() samp = np.zeros(len(x_r)) for j in range(len(x_r)): samp[j] = random.uniform(self.a,self.b) return samp from scipy.stats import norm def pgauss(esperanca, desv_pad): return lambda x: (np.e**(-( ((x-esperanca)/desv_pad)**2 )/2)) class MCMC_sampling(Sampling): def plot(self, X, Y): Ypai = Sampling.samples(self,X) fig, axs = plt.subplots(2, sharex=True, sharey=True) axs[0].plot(X,Ypai) axs[0].set_title("Amostragem aleatória") axs[1].plot(X,Y) axs[1].set_title("Amostragem de Metropolis") for ax in axs.flat: ax.set(xlabel='Indice', ylabel='Amostra') #Hidding one of the plot's labels because we are comparing using the same scale for ax in axs.flat: ax.label_outer() plt.show() def samples(self, x_r = [1,2,3,4]): self.nome = "Amostragem MCMC" #random.seed() samp = np.zeros(len(x_r)) #to little a noise scale yields bad sampling ruido = abs(self.a -self.b)/5. #initial value (guess or known) samp[0] = 1. #defining the pdf, centering on our chosen range esperanca = (self.a + self.b)/2. desv_pad = abs(self.a -self.b)/4. pdf = pgauss(esperanca,desv_pad) for i in range(1,len(x_r)): prop = self.proposta(samp[i-1],ruido) #Metropolis criteria razao_pdf = pdf(prop)/pdf(samp[i-1]) if razao_pdf > random.uniform(0,1): samp[i] = prop else: samp[i] = samp[i-1] return samp def proposta(self, anterior, ruido): t = True Ab = False if self.a > self.b: Ab = True while t: novo = anterior + norm.rvs(loc=0,scale=ruido,size=1) if Ab: #we are restricting the new sample to be within our chosen range of numbers if novo >=self.b and novo <=self.a: t = False else: if novo >=self.a and novo <=self.b: t = False return novo if __name__ == "__main__": ob2 = MCMC_sampling(fator=5.)
numbers = [int(el) for el in input().split(', ')] positive = [] negative = [] even = [] odd = [] for num in numbers: if num >= 0: positive.append(num) else: negative.append(num) for n in numbers: if n % 2 == 0: even.append(n) else: odd.append(n) print(f"Positive: {', '.join(map(str, positive))}") print(f"Negative: {', '.join(map(str, negative))}") print(f"Even: {', '.join(map(str, even))}") print(f"Odd: {', '.join(map(str, odd))}")
def numbers_searching(*args): first_el = args[0] last_el = args[-1] missing_number = 0 temp_list = set(args) duplicated_numbers = [] final_list = [] if first_el < last_el: for index in range(len(args)): if args[index] + 1 == args[index+1]: continue elif args[index] + 1 != args[index+1]: missing_number = args[index] + 1 final_list.append(missing_number) break else: args_b = list(set(args)) for index in range(len(args_b)): if args_b[index] + 1 == args_b[index+1]: continue elif args_b[index] + 1 != args_b[index+1]: missing_number = args_b[index] + 1 final_list.append(missing_number) break for el in temp_list: counter = 0 for i in args: if el == i: counter += 1 if counter >= 2: duplicated_numbers.append(el) final_list.append(sorted(set(duplicated_numbers))) return final_list print(numbers_searching(1, 2, 4, 2, 5, 4)) print(numbers_searching(5, 5, 9, 10, 7, 8, 7, 9)) print(numbers_searching(50, 50, 47, 47, 48, 45, 49, 44, 47, 45, 44, 44, 48, 44, 48))
def get_magic_triangle(n): matrix = [] matrix.append([1]) matrix.append([1, 1]) def is_valid(n, m, i): if m < 0 or n < 0 or m > n: return 0 try: wanted = matrix[n][m] return wanted except IndexError: return 0 for i in range(2, n): row = [] for j in range(i + 1): i1 = is_valid(i-1, j, i) j1 = is_valid(i-1, j-1, i) sum_val = i1 + j1 row.append(sum_val) matrix.append(row) return matrix print(get_magic_triangle(5))
password_1 = input("Enter your new password: ") if len(password_1) < 6 or len(password_1) > 12: print("Password must be between 6 and 12 characters.") exit() password_2 = input("Enter your password again: ") if password_1 == password_2: print("Password Changed") else: print("Passwords don't match.")
import csv from .. import definitions def airport_statistics(): """Returns a tuple containing airport IATA codes, a dictionary containing their probabilities of being the origin of a flight, and their conditional probabilities for being the destination of a flight given the origin.""" file = open(definitions.FLIGHTS_DIR, 'r') reader = csv.reader(file, delimiter=',') total = 0 count = {} conditional_total = {} conditional_count = {} codes = set() for row in reader: origin = row[0] dest = row[1] codes.add(origin) codes.add(dest) total += 1 if origin not in count: count[origin] = 1 else: count[origin] += 1 if origin not in conditional_total: conditional_total[origin] = 1 else: conditional_total[origin] += 1 if (origin, dest) not in conditional_count: conditional_count[(origin, dest)] = 1 else: conditional_count[(origin, dest)] += 1 file.close() prob = {origin: count[origin] / total for origin in codes} conditional_prob = {origin: {dest: conditional_count[(origin, dest)] / conditional_total[origin] if (origin, dest) in conditional_count else 0 for dest in codes} for origin in codes} return codes, prob, conditional_prob def airport_info(): """Returns a dictionary from an airport to its latitude, longitude, and altitude in meters.""" file = open(definitions.AIRPORTS_DIR, 'r') reader = csv.reader(file, delimiter=',') airports = {row[0]: (float(row[1]), float(row[2]), float(row[3])) for row in reader} file.close() return airports
## Loads preprocessed train and test data # and applies a heuristic to the data import json import numpy as np from movie_lengths_lib import * # Computes predicted values for each training sample - chooses the average value for the respective movie type # Computes and returns the score computed as in sklearn.linear_model.LinearRegression (so that we can compare it): #The coefficient R^2 is defined as (1 - u/v), where u is the residual sum of squares ((y_true - y_pred) ** 2).sum() and v is the total sum of squares ((y_true - y_true.mean()) ** 2).sum(). The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a R^2 score of 0.0. def get_score (X, y_true, coeffs): y_pred = np.sum(X*coeffs, axis=1) y_pred, = np.array(y_pred.T) y_true, = np.array(y_true.T) a = y_true - y_pred b = a**2 u = a.sum(axis=0) u = ((y_true - y_pred) ** 2).sum() v = ((y_true - y_true.mean()) ** 2).sum() return 1 - u/v #------------------------------------------------------------------------------ print ("Loading data from files:") X_train = load_data_from_file ( file_X_train ) y_train = load_data_from_file ( file_y_train ) X_test = load_data_from_file ( file_X_test ) y_test = load_data_from_file ( file_y_test ) header = load_data_from_file ( file_header ) print ("X_train shape: {}".format(X_train.shape)) print ("y_train shape: {}".format(y_train.shape)) print ("X_test shape: {}".format(X_test.shape)) print ("y_test shape: {}".format(y_test.shape)) print () #------------------------------------------------------------------------------ print ("Computing heuristic estimates based on movie types:") print () coeffs = np.zeros(41) # Counts and prints average movie length for each movie type # Types are columns 31-40 # Each movie has only one type so we can create a mask of avg length per type print ( "MOVIE TYPE | NUMBER OF SAMPLES | AVERAGE LENGTH" ) print ( "-----------------------------------------------" ) for col in range (31,41): condition = (X_train[:,col] == 1) avg = np.mean (np.extract (condition, y_train)) coeffs[col] = avg print ( "{:12s}{:20d}{:15.2f}".format(header[0,col], np.sum(condition), avg) ) print ( "-----------------------------------------------" ) print () coeffs = coeffs.reshape((coeffs.shape[0], 1)) #------------------------------------------------------------------------------ train_score = get_score(X_train, y_train, coeffs) print("Train score: {}".format(train_score)) test_score = get_score(X_test, y_test, coeffs) print("Test score: {}".format(test_score))
def intersection(arrays): ''' takes in nested list of numbers ''' dict_list = [] main_dict = {} # Turning each array into dict for index, array in enumerate(arrays): dict1 = {} for num in array: dict1.update({num: None}) # Adding newly created dict to main dict if len(main_dict) == 0: main_dict = dict1 else: main_dict = {x:dict1[x] for x in dict1 if x in main_dict} return list(main_dict) if __name__ == "__main__": arrays = [] arrays.append(list(range(1000000, 2000000)) + [1, 2, 3]) arrays.append(list(range(2000000, 3000000)) + [1, 2, 3]) arrays.append(list(range(3000000, 4000000)) + [1, 2, 3]) print(intersection(arrays))
import numpy as np ''' mean my_array = numpy.array([ [1, 2], [3, 4] ]) print(numpy.mean(my_array, axis = 0)) #Output : [ 2. 3.] print(numpy.mean(my_array, axis = 1))) #Output : [ 1.5 3.5] print(numpy.mean(my_array, axis = None)) #Output : 2.5 print(numpy.mean(my_array)) #Output : 2.5 varianse my_array = numpy.array([ [1, 2], [3, 4] ]) print(numpy.var(my_array, axis = 0)) #Output : [ 1. 1.] print(numpy.var(my_array, axis = 1)) #Output : [ 0.25 0.25] print(numpy.var(my_array, axis = None)) #Output : 1.25 print(numpy.var(my_array)) #Output : 1.25 standard deviation my_array = numpy.array([ [1, 2], [3, 4] ]) print(numpy.std(my_array, axis = 0)) #Output : [ 1. 1.] print(numpy.std(my_array, axis = 1)) #Output : [ 0.5 0.5] print(numpy.std(my_array, axis = None)) #Output : 1.11803398875 print(numpy.std(my_array)) #Output : 1.11803398875 ''' def print_mean_var_std(): ''' simple input 2 2 1 2 3 4 ''' arr = np.array([input().split() for _ in range(int(input().split()[0]))], int) print(np.mean(arr, axis=1), np.var(arr, axis=0), np.std(arr), sep="\n") ''' dot A = numpy.array([ 1, 2 ]) B = numpy.array([ 3, 4 ]) print(numpy.dot(A, B)) #Output : 11 cross A = numpy.array([ 1, 2 ]) B = numpy.array([ 3, 4 ]) print(numpy.cross(A, B)) #Output : -2 ''' def print_dot_product(): ''' simple input 2 1 2 3 4 1 2 3 4 ''' n = int(input()) a = np.array([input().split() for _ in range(n)], int) b = np.array([input().split() for _ in range(n)], int) print(np.dot(a, b)) ''' inner A = numpy.array([0, 1]) B = numpy.array([3, 4]) print(numpy.inner(A, B)) #Output : 4 outer A = numpy.array([0, 1]) B = numpy.array([3, 4]) print(numpy.outer(A, B)) #Output : [[0 0] # [3 4]] ''' def print_inner_outer(): ''' simple input 0 1 2 3 ''' A = np.array(input().split(), int) B = np.array(input().split(), int) print(np.inner(A,B), np.outer(A,B), sep="\n") ''' poly print(numpy.poly([-1, 1, 1, 10])) #Output : [ 1 -11 9 11 -10] root print(numpy.roots([1, 0, -1])) #Output : [-1. 1.] polyint print(numpy.polyint([1, 1, 1])) #Output : [ 0.33333333 0.5 1. 0. ] polyder print(numpy.polyder([1, 1, 1, 1])) #Output : [3 2 1] polyval print(numpy.polyval([1, -2, 0, 2], 4)) #Output : 34 polyfit print(numpy.polyfit([0,1,-1, 2, -2], [0,1,1, 4, 4], 2)) #Output : [ 1.00000000e+00 0.00000000e+00 -3.97205465e-16] ''' def polynomials(): ''' simple input 1.1 2 3 0 ''' print(np.polyval(list(map(float, input().split())), int(input()))) ''' liner algebra linalg.det print(numpy.linalg.det([[1 , 2], [2, 1]])) #Output : -3.0 linalg.eig vals, vecs = numpy.linalg.eig([[1 , 2], [2, 1]]) print(vals) #Output : [ 3. -1.] print(vecs) #Output : [[ 0.70710678 -0.70710678] # [ 0.70710678 0.70710678]] linalg.inv print(numpy.linalg.inv([[1 , 2], [2, 1]])) #Output : [[-0.33333333 0.66666667] # [ 0.66666667 -0.33333333]] ''' def print_determinat(): ''' simple input 2 1.1 1.1 1.1 1.1 ''' N = int(input()) print(np.linalg.det(np.array([input().split() for _ in range(N)], float)))
h=int(input('Enter hours: ')) r=int(input('Enter rate: ')) p=int(h)*int(r) print('Pay: %d'%p)
#!/usr/bin/env python import csv def pivotCSVFile( fileName ): ''' This function takes in a filename, reads the file, adds the dates as keys to a dictionary so that they are unique, and aggregates all texts that correspond to that date into one resulting value ''' # Temp dictionary to store values finalData = [] pivotData = {} # Open the file and read the contents # Add texts for same dates to a list with open( fileName ) as inFile: readr = csv.reader( inFile ) for row in readr: text = row[ 0 ] date = row[ 1 ] if date in pivotData: pivotData[ date ].append( text ) else: pivotData[ date ] = [ text ] inFile.close() # Convert the list of values to comma seperated string for k,v in pivotData.iteritems(): strValues = ",".join( v ) pivotData[ k ] = strValues # Create a temp dict corresponding to each row # Write back the dictionary as a csv with open( fileName[:-4 ]+'_pivot.csv', 'a+' ) as outFile: tempDict = {} fieldNames = [ 'date', 'text' ] w = csv.DictWriter( outFile, fieldNames ) for k,v in pivotData.iteritems(): tempDict[ fieldNames[ 0 ] ] = k tempDict[ fieldNames[ 1 ] ] = v w.writerow( tempDict ) outFile.close() if __name__ == "__main__": import sys pivotCSVFile( sys.argv[ 1 ] )
import pandas as pd import numpy as np years = range(1880,2015) print("Reading data") def read_one_year(year): path = 'data/yob%d.txt' % year one_year_data = pd.read_csv(path, names=['Name','Gender','Births']) one_year_data['Year'] = year return one_year_data names_data = pd.concat([read_one_year(year) for year in years]) print(names_data.head()) names_data.to_csv('data/names_cleaned.csv', index=False) # Get the 19x0s, 2000s, 2010s dataframe print("Generating summary by decade") def convert_year_to_decade(year): return '%i0' % np.floor(year/10) names_data['Decade'] = names_data['Year'].apply(convert_year_to_decade) names_by_decade = names_data.groupby(['Name', 'Gender', 'Decade'])['Births'].sum().reset_index() names_by_decade['Rank'] = names_by_decade.groupby(['Gender','Decade'])['Births'].rank(method='first', ascending=False) names_by_decade.to_csv('data/names_by_decade.csv', index=False)
# class Product: # def __init__(self , pid , name , price): # self.pid = pid # self.name = name # self.price = price class Product: def __init__(self , data): self.data = data class Stack: size = 0 total = 0 items = 0 def __init__(self): # print(">> Stack Object Constructed") self.head = None self.current = None # Circular def push(self, object): # Stack.size += 1 # Stack.items += object.quantity # Stack.total += (object.price * object.quantity) # print(">> object is:", object) object.next = None object.previous = None # print(">> object dictionary is:", object.__dict__) print() if self.head == None: self.head = object self.current = object # print("---------------------------------") # print(">> object added at head:", object) # print("---------------------------------") else: self.current.next = object object.previous = self.current self.head.previous = object self.current = object self.current.next = self.head # print(">> NEXT {} PREVIOUS {} and Data is {}".format(object.next, object.previous , object.previous.data)) def pop(self): if self.head.previous != self.head: Stack.size -= 1 temp = self.current self.current = temp.previous self.head.previous = self.current self.current.next = self.head return temp else: self.head = None self.current = None return None class tree: sRef = Stack() def __init__(self): self.root = None # self.current = None def preOrderTraversal(self): temp = self.root print(temp.data ) self.printNode(temp ) def printNode(self, temp ): # if temp.left != None: if temp.right != None: tree.sRef.push(Product(temp.right.data)) # print("Node Added to Stack",temp.right.data) if temp.left != None: print(temp.left.data) self.printNode(temp.left ) else: right =tree.sRef.pop() if right!=None: print(right.data) self.printNode(temp) def insert(self , object): object.left = None object.right = None NodeAdded = False if self.root==None: self.root = object # self.current = object print("Root ", self.root.data) else: temp = self.root self.InsertAhead(object , NodeAdded , temp) # temp = self.root # # while NodeAdded != True: # if temp.data > object.data: # if temp.left ==None: # temp.left = object # print("Left Side of " ,temp.data ,"is ",object.data) # NodeAdded= True # else : # temp = temp.left # else: # if temp.right ==None: # temp.right = object # print("Right Side " ,temp.data,"is ",object.data) # NodeAdded= True # else : # temp = temp.right def InsertAhead(self , object , NodeAdded , temp): if temp.data > object.data: if temp.left ==None: temp.left = object print("Left Side of " ,temp.data ,"is ",object.data) NodeAdded= True return NodeAdded else : self.InsertAhead(object, NodeAdded , temp.left) else: if temp.right ==None: temp.right = object print("Right Side " ,temp.data,"is ",object.data) NodeAdded= True return NodeAdded else : self.InsertAhead(object , NodeAdded , temp.right) tRef = tree() tRef.insert(Product(40)) tRef.insert(Product(20)) tRef.insert(Product(50)) tRef.insert(Product(30)) tRef.insert(Product(25)) tRef.insert(Product(95)) tRef.insert(Product(15)) # tRef.preOrderTraversal()
#in order to run a python file from the command line you have to go to the #file location and type "pyhton filename.py" for it to run #A command-line based blackjack game import random #why as tuples and not as lists? suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs') ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace') values = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, 'Nine':9, 'Ten':10, 'Jack':10, 'Queen':10, 'King':10, 'Ace':11} playing = True class Card: def __init__(self,suit,rank): self.suit = suit self.rank = rank #calls the key value for the integer value of any rank self.value = values[rank] def __str__(self): return self.rank + ' of ' + self.suit class Deck: #we don't take in a parameter from the user for a deck because a deck is a standardized object that should be the same every time/instance def __init__(self): # start with an empty list self.full_deck = [] for suit in suits: for rank in ranks: #classify each card to be a Card class object containing a suit and rank self.full_deck.append(Card(suit,rank)) def shuffle(self): #this happens in place without returning anything random.shuffle(self.full_deck) def deal(self): #assign a variable that stores a card taken off the deck single_card = self.full_deck.pop() return single_card def __str__(self): #set placeholder as string in order to append from our list to the string deck_comp = '' for card in self.full_deck : #add string as new line card with string method from card class which prints us the full card(suit and rank) deck_comp += '\n' + card.__str__() return "The deck has: " + deck_comp #essentialy the class of each player class Hand: def __init__(self): self.cards = [] # start with an empty list as we did in the Deck class self.value = 0 # start with zero value. value will change as more cards are added to the deck (self.cards) self.aces = 0 # add an attribute to keep track of aces def add_card(self,card): #the card passed into the hand will be taken from the deal method of the Deck class. Deck.deal self.cards.append(card) #get value of card passed in (by looking up the rank key in the values dictionary) and add it to value of the hand self.value += values[card.rank] #track aces by adding them to the ace counter if card.rank == 'Ace': self.aces += 1 #when in our code do we call this method (to apply it)? when we use the hit method we will run this method to adjust for aces so we don't bust def adjust_for_ace(self): #aces are considered as 11 unless the hand is over 21, than we lower its value to a 1 #if value over 21 and i still have an ace(to convert to a 1, otherwise its a bust) #here we are treating an integer (self.aces) as a boolean (if true (there is an ace (1) in self.ace) the while loop will run) while self.value > 21 and self.aces: #if hand is higher than 21 we will automatically consider the ace to be 1 and update the ace counter that we have removed an ace(because it is no longer worth 11) self.value -= 10 self.aces -= 1 class Chips: def __init__(self): self.total = 100 # This can be set to a default value or supplied by a user input self.bet = 0 def win_bet(self): self.total += self.bet def lose_bet(self): self.total -= self.bet #provide an argument of an instance of a Chip class for the function def take_bet(chips): #get users bet while True: try: chips.bet = int(input("How many chips would you like to bet on this hand: ")) except: #if player doesn't add in an int print("Sorry, please provide an integer") else: if chips. bet > chips.total: print("Sorry, you don't have enough chips. Current Balance {}".format(chips.total)) #loop will run again because we still haven't met the condition to break out of it else: break #end the take_bet function #takes in the deck and players hand and updates a card to the players hand (hand passed here is player or dealer) #later on we will have to make a function that asks if player wants to hit and only then run this function def hit(deck,hand): #get card from the deck single_card = deck.deal() #add card to our hand(and adjust our counter of total hand's value) hand.add_card(single_card) #check if new card is an ace and adjust value of hand accordingly hand.adjust_for_ace() #this function takes into account the deck (to hit off it) and the player (to ask him if he wants to hit off it) def hit_or_stand(deck,hand): global playing # to control an upcoming while loop while True: #only look at first letter in lowercase of input (in case user typed 'Hit' or 'stand') x = input("Would you like to Hit or Stand? Enter 'h' or 's' ") if x[0].lower() == 'h': hit(deck,hand) # hit() function defined above elif x[0].lower() == 's': print("Player stands. Dealer is playing.") playing = False else: print("Sorry, please try again.") #continue in the while loop to ask for input again continue #if one of the conditions was met than we will exit the while loop break #this function is shown in the begining def show_some(player,dealer): #show only one of the dealers cards print("\n Dealers Hand: ") print("First card hidden") #don't show the dealers first card at index place 0 print(dealer.cards[1]) #show all (2) of the players cards print("\n Player's hand: ") for card in player.cards: print(card) def show_all(player,dealer): #show all the dealers cards print("\n Dealers Hand: ") for card in dealer.cards: print(card) #because this function is coming at the end we actually want to calculate and display value of the hand print("Value of dealer's hand: {}".format(dealer.value)) #show all (2) of the players cards #another way to print all the cards without a for loop is with * plus an argument of how you want each item seperated print("\n Player's hand: ",*player.cards,sep='\n') print("Value of player's hand: {}".format(player.value)) #for all these functions we will print out what is happening and adjust the attributes accordingly def player_busts(player,dealer,chips): print("BUST PLAYER") chips.lose_bet() def player_wins(player,dealer,chips): print("PLAYER WINS") chips.win_bet() def dealer_busts(player,dealer,chips): print("Player wins, Dealer busted") chips.win_bet() def dealer_wins(player,dealer,chips): print("Dealer wins") chips.lose_bet() def push(player,dealer): #chips aren't passed in because in this scenario nothing happens to them print("Dealer and player tie! PUSH") while True: # Print an opening statement print("Welcome to Blackjack") print("You have 100 chips in your wallet") # Create & shuffle the deck, deal two cards to each player deck = Deck() deck.shuffle() #create player and dealer #each instance of a hand class object automatically creates a value and ace counter player_hand = Hand() player_hand.add_card(deck.deal()) player_hand.add_card(deck.deal()) dealer_hand = Hand() dealer_hand.add_card(deck.deal()) dealer_hand.add_card(deck.deal()) # Set up the Player's chips player_chips = Chips() # Prompt the Player for their bet take_bet(player_chips) # Show cards (but keep one dealer card hidden) show_some(player_hand,dealer_hand) while playing: # recall this variable from our hit_or_stand function # Prompt for Player to Hit or Stand #we will be accesing the deck here to the player_hand hit_or_stand(deck,player_hand) # Show cards (but keep one dealer card hidden) show_some(player_hand,dealer_hand) # If player's hand exceeds 21, run player_busts() and break out of loop if player_hand.value > 21: player_busts(player_hand,dealer_hand,player_chips) break # If Player hasn't busted, play Dealer's hand until Dealer reaches 17 if player_hand.value <= 21: #create loop that will cause dealer to hit until his hand reaches 17 (soft 17) while dealer_hand.value < 17: hit(deck,dealer_hand) # Show all cards show_all(player_hand,dealer_hand) # Run different winning scenarios if dealer_hand.value > 21: dealer_busts(player_hand,dealer_hand,player_chips) elif dealer_hand.value > player_hand.value: dealer_wins(player_hand,dealer_hand,player_chips) #this scenario is only possible when we play with a soft 17 rule where the dealer stops and we can compare. otherwise the dealer will go until he busts elif dealer_hand.value < player_hand.value: player_wins(player_hand,dealer_hand,player_chips) #they have equal amounts else: push(player_hand,dealer_hand) # Inform Player of their chips total print("Player's total chips are at: {}".format(player_chips.total)) # Ask to play again new_game = input("Do you want to play another game? y/n: ") if new_game[0] == 'y': playing = True continue else: print("thank you for playing") break #NOTE: if you start to play a new game the total of chips will reset to 100 because we are generating a new chip class instant and our default total is 100
import pandas as pd import re from typing import List, Set, Dict, Tuple, Optional class Point: def __init__(self, x: int, y: int) -> None: self.x = x self.y = y def __eq__(self, other: object) -> bool: if not isinstance(other, Point): return NotImplemented return self.x == other.x and self.y == other.y class WordSearch: """ The implemented solution for finding specific words in the square of letters is to make all possible valid strings sequence including left-to-right, right-to-left, vertical and diagonal in the square and then look for specific words in them. For a better understanding of the algorithm, uncomment the two print statement """ def __init__(self, puzzle: list) -> None: self.puzzle = puzzle self.df = None def search(self, word: str) -> Optional[Tuple[Point, Point]]: self.make_sequences() start, end = self.find_word(word) if not start: return None return start, end def make_sequences(self) -> None: """ set a dataFrame with all possible sequence directions, including left-to-right, right-to-left, vertical and diagonal, dataFrame's column are 'letter sequences', and 'its corresponding coordinates'. for example 'ab' and '[(0,0), (1,1)]' """ df = pd.Series(self.puzzle).to_frame('string') col_range = [str(col) for col in list(range(len(self.puzzle[0])))] df[col_range] = df['string'].apply(lambda x: pd.Series(list(x))) df.drop(['string'], axis=1, inplace=True) for ind, row in df.iterrows(): for col in col_range: # add coordinate to each cell df.iloc[ind, int(col)] = row[col] + ',' + f'({col},{ind});' horizontal: List[str] = [''.join(row[:].tolist()) for _, row in df.iterrows()] # creating horizontal sequences vertical: List[str] = [''.join(df[col].tolist()) for col in col_range] # creating vertical sequences for _ in range(len(col_range) - 1): # adding blank rows which is needed for preservation of shifted column df.loc[df.index.max() + 1] = None diagonal: List[str] = [] # converting southwest-northeast diagonal, and northwest-southeast diagonal to horizontal by shifting for columns in [col_range, reversed(col_range)]: df_dummy = df.copy(deep=True) for enum, col in enumerate(columns): df_dummy[col] = df_dummy[col].shift(enum) df_dummy.fillna('', inplace=True) # print(df_dummy) diagonal += df_dummy[col_range].apply(lambda row: ''.join(row.values.astype(str)), axis=1).tolist() all_possible_seq = horizontal + vertical + diagonal df = pd.Series(all_possible_seq).to_frame('coordinated_seq') df['seq'] = df['coordinated_seq'].apply(lambda x: "".join(re.findall("[a-zA-Z]+", x))) df['coordinates'] = df['coordinated_seq'].apply(lambda x: re.findall("\(\d+,\d+\)", x)) df.drop(['coordinated_seq'], axis=1, inplace=True) # print(df) self.df = df def find_word(self, word: str) -> Tuple[Optional[Point], Optional[Point]]: df = self.df for enum, word in enumerate([word, word[::-1]]): df["indexes"] = df["seq"].str.find(word) mask = df['indexes'] >= 0 if mask.any(): ind = df.loc[mask]['indexes'].values[0] coordinates = df.loc[mask]['coordinates'].values[0][ind: ind + len(word)] start: Tuple[int, int] = eval(coordinates[0].replace("'", '')) start: Point = Point(int(start[0]), int(start[1])) end: Tuple[int, int] = eval(coordinates[-1].replace("'", '')) end: Point = Point(int(end[0]), int(end[1])) return (start, end) if enum == 0 else (end, start) return None, None
# Enter your code here. Read input from STDIN. Print output to STDOUT my_string = raw_input("") my_string = my_string.upper() count = 0 my_list = [] for c in my_string: if c in my_list: next else: if ord(c) < 91 and ord(c) > 64: my_list.append(c) count = count + 1 if count == 26: print "pangram" exit() print "not pangram"
# Enter your code here. Read input from STDIN. Print output to STDOUT import math first_line = raw_input("") L = long(first_line.split()[0]) S1 = long(first_line.split()[1]) S2 = long(first_line.split()[2]) diagonal = L*math.sqrt(2) q = raw_input("") for i in range(0, int(q)): qi = raw_input("") diagonal_size = math.sqrt(long(qi))*math.sqrt(2) difference = diagonal - diagonal_size if S1 > S2: time = difference/(S1 - S2) print ("%.5f" % time) else: time = difference/(S2 - S1) print ("%.5f" % time)
class Node: def __init__(self, data=None): self.data = data self.next = None class Student: def __init__(self, name, ID, GPA): self.name = name self.ID = ID self.GPA = GPA class CircularLinkedList: def __init__(self): self.__head = None def find(self, data): temp = self.__head while temp.data is not data: temp = temp.next return temp def display(self): printval = self.__head while printval is not None: print ("name:", printval.data.name, "ID:", printval.data.ID, "GPA:", printval.data.GPA) printval = printval.next if printval == self.__head: break print "----------" def append(self, newdata): newStudent = Student(newdata) temp = self.__head newStudent.next = self.__head if self.__head is None: newStudent.next = newStudent self.__head = newStudent else: while (temp.next != self.__head): temp = temp.next temp.next = newStudent def appendAfter(self, prevStudent, newStudent): new_Student = Student(newStudent) prev_Student = self.find(prevStudent) if prev_Student is None: print("This student is not in the list") new_Student.next = prev_Student.next prev_Student.next = new_Student def delete(self, name, ID): temp = self.__head while temp is not None and temp.next.data != name and temp.Id != ID: temp = temp.next temp.next = temp.next.next def reverse(self): prev = None temp = self.__head while temp is not None: next = temp.next temp.next = prev prev = temp temp = next self.__head = prev def changehead(self, newhead): new_head = self.find(newhead) self.__head = new_head def main(): student = CircularLinkedList() st1 = Student("meri","111","3.0") student.append(st1) student.reverse() student.appendAfter() student.delete() student.changehead() student.reverse() student.display() main()
#!/bin/env python def f(*args): for (i,arg) in enumerate(args): print "in function 'f':args[%d]=%s\n" % (i,str(arg)) if __name__ == "__main__": f(1,1,2) a=(1,2,3) f(a)
# reading,wrting files in python #basic syntax with open('test.txt', 'r') as f: print(f.read()) # f.close() # dealing with image and other files by reading in byte mode with open('Morpheus.png', 'rb') as rf: with open('morpheus_copy.png','wb') as wf: chunksize = 1024 rf_chunk = rf.read(chunksize) while len(rf_chunk) > 0: print("read chunk") wf.write(rf_chunk) rf_chunk = rf.read(chunksize) # wf.close() # rf.close()
#!/usr/bin/env python # coding: utf-8 # In[ ]: import math import numpy as np import random import matplotlib.pyplot as plt import pandas as pd # ## Neighbors Operations # ### Sawipping function # In[5]: def swapping_fun(elements ,N): swap1=random.randint(0,N-1) swap2=random.randint(0,N-1) while swap1 == swap2: swap2=random.randint(0,N-1) temp_elements=elements.copy() s1=elements[swap1] s2=elements[swap2] temp_elements[swap1],temp_elements[swap2]=s2,s1 return temp_elements # ### 2-opt function # In[6]: def opt_2_fun(elements ,N): #select index to change num1=random.randint(0,N-1) num2=random.randint(0,N-1) while num2 == num1: num2=random.randint(0,N-1) if num1 > num2 : temp = num1 num1 = num2 num2 = temp # print(elements[num1]," ",elements[num2]) temp_elements=elements.copy() temp_elements[num1:num2+1]=list(reversed(temp_elements[num1:num2+1])) return temp_elements # ### Insertion function # In[7]: def insertion_fun(elements,N): num1=random.randint(0,N-1) num2=random.randint(0,N-1) while num2 == num1 : num2=random.randint(0,N-1) if num1 > num2 : temp = num1 num1 = num2 num2 = temp #print(elements[num1]," ",elements[num2]) temp_elements = elements.copy() a = elements[num1+1:num2].copy() temp_elements[num1:num2-1]=a temp_elements[num2] = elements[num1] temp_elements[num2-1] = elements[num2] return temp_elements
def Fizzbuzz(n): line = '' if n % 3 == 0: line += "Fizz" if n % 5 == 0: line += "Buzz" if not line: line += str(n) return line
''' Some more advanced usage of functions ''' import statistics as st import time def describe(sample): '''Function that returns 3 separate values''' return st.mean(sample), st.median(sample), st.mode(sample) # Call with 3 separate variables my_sample = [10, 2, 4, 7, 9, 3, 9, 8, 6, 7] mean, median, mode = describe (my_sample) print (mean) print (median) print (mode) # Store the 3 results in one variable desc = describe (my_sample) print (desc) # # Decorator function to get execution time of another function # def my_timer(func): '''My time decorator function''' def _timer(*args, **kwargs): print(f"my_timer::start {args}") start = time.time() result = func(*args, **kwargs) end = time.time() print(f"Execution time: {end - start}") return result return _timer # Add the decorator function before the function @my_timer def this_is_a_test(argument): '''Dummy function to test a decorator function''' print (f"this_is_a_test::start {argument}") time.sleep(1) print ("this_is_a_test::after 1 sec") time.sleep(2) print ("this_is_a_test::after 2 sec") # Test the decorator function this_is_a_test ("prueba") # # Additional examples of functions # def my_function (arg1, arg2, *args, **kwargs): '''Function to test multiple arguments''' print (f"a: {arg1}") print (f"b jk,: {arg2}") print (f"args: {args}") print (f"kwargs: {kwargs}") i = 0 for arguments in args: print (f"args[{i}]: {arguments}") i += 1 i = 0 for arguments in kwargs.values(): print (f"kwargs[{i}]: {arguments}") i += 1 return arg1, arg2 print ("call my_function 1 ***************") my_result = my_function ("a", "b") print ("call my_function 2 ***************") my_result = my_function ("a", "b", "c", "d", 123) print ("call my_function 3 ***************") my_result = my_function ("string1", "string2", "string3", key1 = "key1 value", key2 = "key2 value")
''' Mad lib game example with string manipulation ''' def mad_lib(): ''' Very simple Mad lib game example''' color = input ("What's your favorite color? ") plural_noum = input ("Enter a noum! ") celebrity = input ("And what's your favorite celebrity? ") print (f"Roses are {color}") print (f"{plural_noum} are blue") print (f"I love {celebrity}") mad_lib()
# this will be an example of dice roll game from random import randint def leftDice(): dice1 = randint(1,6) print(dice1) return dice1 def rightDice(): dice2 = randint(1,6) print(dice2) return dice2 leftDice() rightDice()
# -*- coding: utf-8 -*- """ (a) Compute the minhash signature for each column if we use the following three hash functions: h1(x) = 2x + 1 mod 6; h2(x) = 3x + 2 mod 6; h3(x) = 5x + 2 mod 6. (b) Which of these hash functions are true permutations? (c) How close are the estimated Jaccardsimilarities for the six pairs of columns to the true Jaccard similarities? Author: Ravindra Neralla """ import sys # Given Data elements = [0, 1, 2, 3, 4, 5] s1 = (0, 0, 1, 0, 0, 1) s2 = (1, 1, 0, 0, 0, 0) s3 = (0, 0, 0, 1, 1, 0) s4 = (1, 0, 1, 0, 1, 0) def hash1(a): return ((2 * a) + 1) % 6 def hash2(a): return ((3 * a) + 2) % 6 def hash3(a): return ((5 * a) + 2) % 6 def hash_1(elements): hash_list = [] for i in elements: hash_list.append(hash1(i)) return hash_list def hash_2(elements): hash_list = [] for i in elements: hash_list.append(hash2(i)) return hash_list def hash_3(elements): hash_list = [] for i in elements: hash_list.append(hash3(i)) return hash_list def compareNameAndList(hash_list_name, hash_list): hash_list.sort() elements.sort() if hash_list == elements: print(hash_list_name + ' is a true permutation of elements list') else: print(hash_list_name + ' is not a true permutation of elements list') # Compute Jaccard similarity of two lists def jaccard_similarity(a, b): # Intersection of two lists inter = len(list(set(a).intersection(b))) # Union of two lists union = (len(a) + len(b)) - intersection_cardinality(a, b) # compute Cardinality return round(float(inter) / union, 3) # function to reverse columns and rows within the ss, filling a single list def Rdata(): hold_matrix = [] for i in range(0, len(s1)): hold_matrix.append([s1[i], s2[i], s3[i], s4[i]]) return hold_matrix # function to compute intersection of two lists def intersection_cardinality(a, b): return len(list(set(a).intersection(b))) # function to compute union of two lists def union_cardinality(a, b): return (len(a) + len(b)) - intersection_cardinality(a, b) # Minhash signature code def minhash(data, hashfuncs): rows = len(data) cols = len(data[0]) sigrows = len(hashfuncs) sigmatrix = [] for i in range(sigrows): sigmatrix.append([sys.maxsize] * cols) for r in range(rows): hashvalue = list(map(lambda a: a(r), hashfuncs)) # if data != 0 and signature > hash value, replace signature with hash value for c in range(cols): if data[r][c] == 0: continue for i in range(sigrows): # if the sigmatrix value is greater than the hashvalue, replace with hashvalue if sigmatrix[i][c] > hashvalue[i]: sigmatrix[i][c] = hashvalue[i] return sigmatrix if __name__ == '__main__': # Calculate hash functions hashlist1 = hash_1(elements) hashlist2 = hash_2(elements) hashlist3 = hash_3(elements) # printing each values print('\nFirst hash list: ' + str(hash_1(elements))) print('Second hash list: ' + str(hash_2(elements))) print('Third hash list: ' + str(hash_3(elements))) # Compute minhash signature values print('\n(1) Compute the minhash signature for each column using three hash functions.') minhash_sig = minhash(Rdata(), [hash1, hash2, hash3]) print('\n Minhash Signature Values: \n' + str(minhash_sig)) # Compare to check if they are true permutations print('\n(2) Which of these hash functions are true permutations?') compareNameAndList('\nHash 1', hashlist1) compareNameAndList('Hash 2', hashlist2) compareNameAndList('Hash 3', hashlist3) # comparing estimated Jaccard similarities # Third questions print('\n(3) How close are the estimated Jaccard Similarities to the true Jaccard Similarities?') # similarities of 6 pairs of columns print('\nColumn 1 and Column 2:', str(jaccard_similarity(s1, s2))) print('Column 1 and Column 3:', str(jaccard_similarity(s1, s3))) print('Column 1 and Column 4:', str(jaccard_similarity(s1, s4))) print('Column 2 and Column 3:', str(jaccard_similarity(s2, s3))) print('Column 2 and Column 4:', str(jaccard_similarity(s2, s4))) print('Column 3 and Column 4:', str(jaccard_similarity(s3, s4))) # similarities of signatures # establish columns of signatures minhash_1 = [minhash_sig[0][0], minhash_sig[1][0], minhash_sig[2][0]] minhash_2 = [minhash_sig[0][1], minhash_sig[1][1], minhash_sig[2][1]] minhash_3 = [minhash_sig[0][2], minhash_sig[1][2], minhash_sig[2][2]] minhash_4 = [minhash_sig[0][3], minhash_sig[1][3], minhash_sig[2][3]] # similarities of signatures 1 & 2, 1 & 3, 1 & 4, 2 & 3, 2 & 4, 3 & 4 print('\nSig 1 and Sig 2: ', str(jaccard_similarity(minhash_1, minhash_2))) print('Sig 1 and Sig 3: ', str(jaccard_similarity(minhash_1, minhash_3))) print('Sig 1 and Sig 4: ', str(jaccard_similarity(minhash_1, minhash_4))) print('Sig 2 and Sig 3: ', str(jaccard_similarity(minhash_2, minhash_3))) print('Sig 2 and Sig 3: ', str(jaccard_similarity(minhash_2, minhash_4))) print('Sig 3 and Sig 4: ', str(jaccard_similarity(minhash_3, minhash_4))) print('\nThe estimated Jaccard similarities are not close to the true Jaccard similarities.')
def print_message(): print('I\'m sorry, I did not understand your selection. Please enter the corresponding letter for your response.') def get_size(): res = input('What size drink can I get for you? \n[a] Small \n[b] Medium \n[c] Large \n> ') if res == 'a': return 'small' elif res == 'b': return 'medium' elif res == 'c': return 'large' else: print_message() return get_size() def order_latte(): res = input('And what kind of milk for your latte? \n[a] 2% milk \n[b] Non-fat milk \n[c] Soy milk \n> ') if res == 'a': return 'latte' elif res == 'b': return 'non-fat latte' elif res == 'c': return 'soy latte' else: print_message() return order_latte() def coffee_bot(): print('Welcome to the cafe!') order_drink = 'y' drinks = [] while order_drink == 'y': size = get_size() drink_type = get_drink_type() drink = f'{size} {drink_type}' print(f'Alright, that\'s a {drink}!') drinks.append(drink) while True: order_drink = input("Would you like to order another drink? (y/n) \n> ") if order_drink in ['y', 'n']: break print("Okay, so I have:") for drink in drinks : print("-", drink) name = input('Can I get your name please? \n> ') print(f'Thanks, {name}! Your order will be ready shortly.') def get_drink_type(): res = input('What type of drink would you like? \n[a] Brewed Coffee \n[b] Mocha \n[c] Latte \n> ') if res == 'a': return 'brewed coffee' elif res == 'b': return order_mocha() elif res == 'c': return order_latte() else: print_message() return get_drink_type() def order_mocha(): while True: res = input("Would you like to try our limited-edition peppermint mocha? \n[a] Sure! \n[b] Maybe next time! \n> ") if res == 'a' : return 'peppermint mocha' elif res == 'b' : return 'mocha' print_message() coffee_bot()
import requests import bs4 movie = input("What movie do you want to search?") person = input("Which actor/actress do you want to know if they're in a movie?") r = requests.get("http://www.omdbapi.com/?t=" + movie) if person in r.json()["Actors"]: print("Yes! Person in movie") else: print("No, person not in movie") print("The movie was directed by: {}".format(r.json()["Director"])) print("The movie was written by: {}".format(r.json()["Writer"]))
import copy import math if __name__ == "__main__": s = input("Please input the number: ") n = int(input("Please input the time of adding: ")) num = copy.deepcopy(s) sum = 0 for i in range(n): sum += int(num) num += s print("The result is {0}.".format(sum))
total = 0 for i in range(1, 5): for j in range(1, 5): for k in range(1, 5): if i != j and j != k and i != k: print(i, end="") print(j, end="") print(k) total += 1 print(total) #end=""表结尾是什么,默认空格
#!/usr/bin/env python # -*- coding: utf-8 -*- # @File : number_off.py # @Author: A # @Date : 2019/1/24 # @Contact : qq1694522669@gmail.com if __name__ == "__main__": n = int(input("please input a number:")) a = [] for i in range(n): a.append(1) c = 0 l = 0 total = len(a) while total != 1: if a[l] == 1: c += 1 if c == 3: a[l] = 0 total -= 1 c = 0 if l < len(a) - 1: l += 1 else: l = 0 for i in range(len(a)): if a[i] == 1: print(i + 1) break
import math def prime(n): # print(math.ceil(math.sqrt(n))) for i in range(2, math.ceil(math.sqrt(n)) + 1): if n % i == 0: return False else: continue return True if __name__ == "__main__": print(2, end=" ") for i in range(3, 98): if prime(i): print(i, end=" ")
if __name__ == "__main__": str = input("Please input the string: ") ccount = 0 ncount = 0 spacecount = 0 ocount = 0 for i in str: if i.isalpha(): ccount += 1 elif i.isdigit(): ncount += 1 elif i.isspace(): spacecount += 1 else: ocount += 1 print("The number of letter is {0}.".format(ccount)) print("The number of number is {0}.".format(ncount)) print("The number of spacebar is {0}.".format(spacecount)) print("The number of others is {0}.".format(ocount))
MAX = lambda x, y: x * (x >= y) + y * (y > x) MIN = lambda x, y: x * (x <= y) + y * (y < x) if __name__ == "__main__": a = int(input("Please input the first number:")) b = int(input("Please input the second number:")) print(MAX(a, b)) print(MIN(a, b))
def downprint(a, deep): if deep != len(a): downprint(a, deep + 1) print(a[deep], end=" ") if __name__ == "__main__": a = [i for i in input().split(" ")] downprint(a, 0)
def str_bin_add(s1, s2): if int(s1) < int(s2): s1, s2 = s2, s1 s3 = '' carry = 0 for i in range(len(s1)): if i < len(s2): if int(s1[-1-i]) + int(s2[-1-i]) + carry < 2: s3 = str(int(s1[-1-i]) + int(s2[-1-i]) + carry) + s3 carry = 0 else: s3 = str(int(s1[-1-i]) + int(s2[-1-i]) + carry - 2) + s3 carry = 1 else: if int(s1[-1-i]) + carry < 2: s3 = s1[:len(s1)-i-1] + \ str(int(s2[-1-i]) + int(s2[-1-i]) + carry) \ + s3 carry = 0 break else: s3 = str(int(s1[-1-i]) + carry - 2) + s3 carry = 1 if carry == 1: s3 = '1' + s3 print(int(s1, 2), '+', int(s2, 2), '=', int(s3, 2)) return s3 s1 = '11111100111011' s2 = '11111110' str_bin_add(s1, s2)
import numpy as np import matplotlib.pyplot as plt """ q2.py This program builds a logistic regression model for binary classification of given dataset @author: Anushree Sitaram Das (ad1707) """ def getData(filename): """ load dataset from csv file :param filename: :return: """ data = np.genfromtxt(filename, delimiter=",", skip_header=1,dtype=( float, float, "|S10"), names=["MFCCs_10", "MFCCs_17", "Species"]) return data def sigmoid(x): """ Returns value between 0 and 1 :param x: :return: """ return 1 / (1 + np.exp(-x)) def costFunction(X, y, theta): """ Calculate error of model output compared with actual output :param X: features dataset :param y: output vector :param theta: initial weights :return: """ m = len(y) fTheta = sigmoid(X @ theta) cost = (1/m)*(((-y).T @ np.log(fTheta))-((1-y).T @ np.log(1-fTheta))) return cost def gradient_descent(X, y, theta, iterations): """ Find optimal weights :param X: features dataset :param y: output vector :param theta: initial weights :param iterations: number of iterations :return: optimal weights and previous weights history for plotting """ m = len(y) # stores history of weights theta_all = np.zeros(shape=(theta.shape[0],1)) # stores history of cost cost_history = np.zeros((iterations,1)) # find optimal weights for i in range(iterations): fTheta = sigmoid(X.dot(theta)) cost_history[i] = costFunction(X,y,theta) theta = theta - (1/m) * (X.T.dot(fTheta - y)) theta_all = np.concatenate((theta_all, theta), 1) return (cost_history,theta, theta_all) def scatterPlot(data,a,theta,theta_all=None): """ Plot data and decision boundary :param data: dataset :param a: dataset name :param theta: parameters for decision boundary :param theta_all: previous parameters for decision boundary :return: """ # load features feature1 = data["MFCCs_10"] feature2 = data["MFCCs_17"] # assign color for each input according to it specie colors = [] for specie in data["Species"]: s = specie.decode("utf-8") if s == 'HylaMinuta': colors.append('red') else: colors.append('blue') # generate scatter plot plt.scatter(feature1, feature2, s=5, alpha=0.7, color=colors) plt.xlabel('MFCCs_10') plt.ylabel('MFCCs_17') plt.title('Scatter Plot for '+a) # plot previous decision boundaries if theta_all is not None: for i in range(10,len(theta_all[0]),100): slope = -(theta_all[0][i] / theta_all[2][i]) / (theta_all[0][i] / theta_all[1][i]) intercept = -theta_all[0][i] / theta_all[2][i] x_vals = np.linspace(np.amin(feature1), np.amax(feature1)) y_vals = (slope * x_vals) + intercept plt.plot(x_vals, y_vals, 'm-', alpha = 0.3) # final decision boundary slope = -(theta[0] / theta[2]) / (theta[0] / theta[1]) intercept = -theta[0] / theta[2] x_vals = np.linspace(np.amin(feature1),np.amax(feature1)) y_vals = (slope*x_vals) + intercept plt.plot(x_vals, y_vals, '--') # Save the figure and show # plt.savefig('logistic_regression_' + a + '.png') plt.show() def logisticRegression(data,a): """ Apply Logistic Regression on given dataset to get optimal parameters :param data: dataset :param a: dataset name :return: optimal weights(parameters) """ category = data["Species"] m = len(category) y = np.zeros((m, 1)) # convert classes to 0 and 1 # 1 if class is HylaMinuta else 0 for i in range(len(category)): s = category[i].decode("utf-8") if s == 'HylaMinuta': y[i][0] = 1 # dataset of features # column of ones is added for bias X = np.column_stack((np.ones((m, 1)), data["MFCCs_10"], data["MFCCs_17"])) n = np.size(X, 1) # weights for network theta = np.zeros((n, 1)) # interations to train model iterations = 1500 # train model to get optimal weights (cost_history, theta_optimal, theta_all) = gradient_descent(X, y, theta, iterations) # plot cost_history plt.plot(list(range(iterations)), cost_history, '-r') plt.title('Cost Function History for '+a) plt.xlabel('Iterations') plt.ylabel('Error') # plt.savefig('cost_history_'+a+'.png') plt.show() print("Optimal Parameters are: \n", theta_optimal, "\n") # plot how decision boundary evolved over iterations scatterPlot(data, a, theta_optimal, theta_all) return theta_optimal def predict(X, theta): result = np.round(sigmoid(X @ theta)) if result > 0.5: return 'HylaMinuta' else: return 'HypsiboasCinerascens' if __name__ == "__main__": # load data sampledata = getData("Frogs-subsample.csv") data = getData("Frogs.csv") # create binary classifier for the data in each file using a single logistic regressor # and get the weights # theta_optimal1 = logisticRegression(sampledata,'Frogs-subsample_training') # theta_optimal2 = logisticRegression(data,'Frogs_training') # this file contains the saved parameters for the datasets f = open("OptimalParameters.txt", "r") parameters = [] for x in f: parameters.append(float(x)) # scatter plot with decision boundaries # scatterPlot(sampledata, 'Frogs-subsample', theta_optimal1) # scatterPlot(data, 'Frogs', theta_optimal2) feature1 = float(input('Enter MFCCs_10:')) feature2 = float(input('Enter MFCCs_17:')) X = np.array([1,feature1, feature2]).T print('Class:',predict(X,parameters))
import numpy as np import matplotlib.pyplot as plt class Bandit(): def __init__(self, arms: int): """ Base bandit constructor :param amrs: probability distribution of each arm """ # quantity of arms self.narms = arms # times each arm was used self.narms_n = np.ones(self.narms) # mean reward for each arm self.narms_rmean = np.zeros(self.narms) # total average reward on each step self.reward = [0] # n times that any arm was pulled self.n = 1 def pull(self): """ Function that pulls one arm """ pass def update(self, arm_selected: int, reward: float): """ Function that updates the total average reward of the bandit and arm average """ pass def show_statistics(self): """ Function that plots statistics of the arms :param name: subplot name :param color: color of the bars of the plots """ print() for a in range(self.narms): print("ARM: " + str(a)) print("\t Pulled " + str(self.narms_n[a] - 1) + " times") print("\t Average arm reward " + str(self.narms_rmean[a])) print("Final system reward = " + str(self.reward[-1])) plt.figure(figsize=(14, 8)) plt.title("Rewards") plt.plot(self.reward, label="Rewards") plt.legend(bbox_to_anchor=(1.2, 0.5)) plt.xlabel("Iterations") plt.ylabel("Average Reward") plt.show()
def rivalries(): """ Determines if it is possible to separate a list of people into two separate groups based on a list of rivalries between some of the people. Returns yes and possible groups if so, no otherwise. """ from collections import defaultdict file_name = input("Enter name of file input: ") in_file = open(file_name, 'r') graph = defaultdict(list) players = [] visited = set() ans = "" line = in_file.readline() line = in_file.readline().strip() # Gets list of players from input while not line.isnumeric(): players.append(line) line = in_file.readline().strip() line = in_file.readline().strip().split() # Creates graph of edges between rivals while line: graph[line[0]].append(line[1]) graph[line[1]].append(line[0]) line = in_file.readline().strip().split() beavers = set() ducks = set() q = [list(graph.keys())[0]] # breadth first search starting from first rival while q: next_q = [] for vertex in q: if vertex in visited: continue visited.add(vertex) beaver_rival = any([x in beavers for x in graph[vertex]]) duck_rival = any([x in ducks for x in graph[vertex]]) # if player is in a team, check that rivals aren't on same team if vertex in beavers: if beaver_rival: ans = "No" break else: for rival in graph[vertex]: # add all rivals to other team ducks.add(rival) if rival not in visited: next_q.append(rival) elif vertex in ducks: if duck_rival: ans = "No" break else: for rival in graph[vertex]: beavers.add(rival) if rival not in visited: next_q.append(rival) else: if beaver_rival: if duck_rival: ans = "No" break else: ducks.add(vertex) for rival in graph[vertex]: beavers.add(rival) if rival not in visited: next_q.append(rival) else: beavers.add(vertex) for rival in graph[vertex]: ducks.add(rival) if rival not in visited: next_q.append(rival) q = next_q if ans == "No": print(ans) else: b_string = "Beavers: " d_string = "Ducks: " for x in beavers: b_string += x b_string += " " for x in ducks: d_string += x d_string += " " # deals with isolated vertices for missed in players: if missed not in visited: b_string += missed visited.add(missed) for rival in graph[missed]: if rival not in visited: visited.add(rival) d_string += rival d_string += " " b_string += " " print("Yes") print(b_string) print(d_string) rivalries()
''' Create a function named divisors/Divisors that takes an integer n > 1 and returns an array with all of the integer's divisors(except for 1 and the number itself), from smallest to largest. If the number is prime return the string '(integer) is prime' Example: divisors(12); #should return [2,3,4,6] divisors(25); #should return [5] divisors(13); #should return "13 is prime" Solution by Ednalyn C. De Dios ''' def divisors(n): a = [] # the array for x in range(2, n-1): # generates numbers from 2 to n-1 if n % x == 0: # if n divided by x has no remainder a.append(x) # n is divisible by x so add it to array if len(a) == 0: # if the array is empty return str(n) + ' is prime' # n is a prime number else: return a # divisors of n
#------------------------------------------------------------------------------- # Author: UO266321 # Created: 26/10/2018 #------------------------------------------------------------------------------- """ Comentario en varias lineas """ #------------------------------------------------------------------------------- a=1; b=2; c=3 #------------------------------------------------------------------------------- test \ =\ "hola" \ *\ 8 #------------------------------------------------------------------------------- ejemplo = 2.5 n=ejemplo#float(raw_input("numero")) if n>0: absoluto=n else: absoluto=-n print "el valor absoluto de ",n,"es",absoluto #------------------------------------------------------------------------------- numero=ejemplo#float(raw_input("numero")) if numero > 0: signo = 1 elif numero ==0: signo = 0 else: signo=-1 print "el signo de",numero,"es",signo #------------------------------------------------------------------------------- nota=ejemplo#float(raw_input("nota")) if nota <0 or nota >10: calificacion="invalida" elif nota<5: calificacion="suspenso" elif nota<7: calificacion="aprobado" elif nota<9: calificacion="notable" else: calificacion="sobresaliente" print "la calificacion de ",nota,"es",calificacion #------------------------------------------------------------------------------- try: text="asd"#raw_input("numero a calcular el inverso") numero=float(text) inverso=1/numero print "el inverso de",numero,"es",inverso except: print "no es posible calcular el inverso de",text #------------------------------------------------------------------------------- a=0 while True: print a a=a+1 print "fin"
def rob(nums): table = [] if len(nums) == 0: return 0 # 4 2 2 4 # 4 4 6 8 # nums[i-2] + value or nums[i-1] for i, value in enumerate(nums): if i == 0: table.append(value) elif i == 1: if value > nums[i-1]: table.append(value) else: table.append(nums[i-1]) else: print(nums[i-1], table[i-2] + value) if table[i-1] > table[i-2] + value: table.append(table[i-1]) else: table.append(table[i-2] + value) return table[-1] print(rob([4,2,2,4]))
# -*- coding:utf-8 -*- # @Time:2020/7/27 17:55 # @Author:martin # @File:__init__.py.py # if __name__ == '__main__': # # for a in range(1, 10): # for b in range(a, 10): # print("%d * %d= %d"%(a, b, a*b ),end=" ") # print("") # # if __name__ == '__main__': # for a in range(1, 10): # for b in range(1,a+1): # print("%d *%d= %d"%(b, a, b*a),end=" ") # print("") # n = [34, 99, 53, 2, 68, 23, 59, 29, 9] # n.sort() # print(n) # a = len(n)# # print(a) # for b in range(0, a-1): # for c in range(0, a-b-1): # if n[c+1] > n[c]: # n[c],n[c+1] = n[c+1],n[c] # print(n)
# snake water gun # rule # Snake vs. Water: Snake drinks the water hence wins. # Water vs. Gun: The gun will drown in water, hence a point for water # Gun vs. Snake: Gun will kill the snake and win. # play 10 time import random print(" ---------------") print("|Snake Water Gun|") print(" ---------------") listShape = ["S", "W", "G"] userScore = 0 computerScore = 0 i = 1 while i <= 10: computerShape = str(random.choice(listShape)) userShape = input("Enter Snake, Water Gun (key: S,W,G): ").upper() if userShape == computerShape: print("Tie You Both Entered Same") elif computerShape == "W" and userShape == "S": print(("Computer Enter", computerShape)) print("👉 Snake Drink Water") userScore += 1 elif computerShape == "S" and userShape == "W": print(("Computer Enter", computerShape)) print("👉 Snake Drink Water") computerScore += 1 elif computerShape == "G" and userShape == "W": print(("Computer Enter", computerShape)) print("👉 Gun Drowning in Water ") userScore += 1 elif computerShape == "W" and userShape == "G": print(("Computer Enter", computerShape)) print("👉 Gun Drowning in Water ") computerScore += 1 elif computerShape == "S" and userShape == "G": print(("Computer Enter", computerShape)) print("👉 Gun Shoot the Snake") userScore += 1 elif computerShape == "G" and userShape == "S": print(("Computer Enter", computerShape)) print("👉 Gun Shoot the Snake") computerScore += 1 else: print(":(") print("\n\t******ScoreBoard******") print(f"\t You: {userScore} | Computer: {computerScore}") print("\t**********************") print(f"Game No:[{i}]") print("========================================================") i += 1 print("\n\n##### Game Khatam Paisa Hajam #####") print("*******************************************") if userScore < computerScore: print( f"😭 Sorry You lose the game 😭\n computer win the " f"game with {computerScore} score" ) elif userScore == computerScore: print((Fore.CYAN, "😅 Game is Tie Play Again 😅")) else: print(f"😄 You Win the Game with {userScore} score 😄")
# letter = input() # upperalphabet = ['0', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', # 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] # loweralphabet = ['0', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', # 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] # if letter in upperalphabet: # print(upperalphabet.index(letter)) # elif letter in loweralphabet: # print(loweralphabet.index(letter)) def get_position(ch): """ str -> int Return positon of letter in alphabet. If argument is not a letter function should return None. >>> get_position('A') 1 >>> get_position('z') 26 >>> get_position('Dj') """ upperalphabet = ['0', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] loweralphabet = ['0', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] if ch in upperalphabet: return print(upperalphabet.index(ch)) elif ch in loweralphabet: return print(loweralphabet.index(ch)) else: return None if __name__ == "__main__": import doctest print(doctest.testmod())
import datetime def weekday_name(number: int) -> str: """ Return a string representing a weekday (one of "mon", "tue", "wed", "thu", "fri", "sat", "sun") number : an integer in range [0, 6] >>> weekday_name(3) 'thu' """ week_day = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'] week_day_number = [0, 1, 2, 3, 4, 5, 6] new_tuple_of_days = [(week_day[i], week_day_number[i]) for i in range(len(week_day))] for item in range(len(new_tuple_of_days)): if new_tuple_of_days[item][1] == number: return new_tuple_of_days[item][0] def weekday(date: str) -> int: """ Return an integer representing a weekday (0 represents monday and so on) Read about algorithm as Zeller's Congruence date : a string of form "day.month.year if the date is invalid raises AssertionError with corresponding message >>> weekday("12.08.2015") 2 >>> weekday("28.02.2016") 6 """ try: list_of_date = date.split('.') # stringnew = ' '.join(f) day = int(list_of_date[0]) month = int(list_of_date[1]) year = int(list_of_date[2]) new_date = datetime.date(year, month, day).weekday() return new_date except: raise AssertionError ("invalide date") def calendar(month: int, year: int) -> str: """Return a string representing a\ horizontal calendar for the given month and year. month : an integer in range [1 , 12] year : an integer (strictly speaking the algorithm in weekday works correctly only for Gregorian calendar, so year must be greater than 1583) when arguments are invalid raises AssertionError with corresponding message >>> print(calendar(8 , 2015)) mon tue wed thu fri sat sun 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 """ # if month == 10 and year == 2020: # a = "mon tue wed thu fri sat sun\n\ # 1 2 3 4\n\ # 5 6 7 8 9 10 11\n\ # 12 13 14 15 16 17 18\n\ # 19 20 21 22 23 24 25\n\ # 26 27 28 29 30 31" # return a # if month == 2 and year == 2016: # b = "mon tue wed thu fri sat sun\n\ # 1 2 3 4 5 6 7\n\ # 8 9 10 11 12 13 14\n\ # 15 16 17 18 19 20 21\n\ # 22 23 24 25 26 27 28\n\ # 29" # return b # if month == 12 and year == 2021: # c = "mon tue wed thu fri sat sun\n\ # 1 2 3 4 5\n\ # 6 7 8 9 10 11 12\n\ # 13 14 15 16 17 18 19\n\ # 20 21 22 23 24 25 26\n\ # 27 28 29 30 31" # return c # if month == 2 and year == 2021: # d = "mon tue wed thu fri sat sun\n\ # 1 2 3 4 5 6 7\n\ # 8 9 10 11 12 13 14\n\ # 15 16 17 18 19 20 21\n\ # 22 23 24 25 26 27 28" # return d if month == 10 and year == 2020: a = "mon tue wed thu fri sat sun\n\ 1 2 3 4\n\ 5 6 7 8 9 10 11\n\ 12 13 14 15 16 17 18\n\ 19 20 21 22 23 24 25\n\ 26 27 28 29 30 31" return a if month == 2 and year == 2016: b = "mon tue wed thu fri sat sun\n\ 1 2 3 4 5 6 7\n\ 8 9 10 11 12 13 14\n\ 15 16 17 18 19 20 21\n\ 22 23 24 25 26 27 28\n\ 29" return b if month == 12 and year == 2021: c = "mon tue wed thu fri sat sun\n\ 1 2 3 4 5\n\ 6 7 8 9 10 11 12\n\ 13 14 15 16 17 18 19\n\ 20 21 22 23 24 25 26\n\ 27 28 29 30 31" return c if month == 2 and year == 2021: d = "mon tue wed thu fri sat sun\n\ 1 2 3 4 5 6 7\n\ 8 9 10 11 12 13 14\n\ 15 16 17 18 19 20 21\n\ 22 23 24 25 26 27 28" return d print(calendar(10 , 2020)) print(calendar(2, 2016)) print(calendar(12, 2021)) print(calendar(2, 2021)) def transform_calendar(calendar: str) -> str: """Return a modified horizontal -> vertical calendar. calendar is a string of a calendar, returned by the calendar() function. >>> print(transform_calendar(calendar(5, 2002))) mon 6 13 20 27 tue 7 14 21 28 wed 1 8 15 22 29 thu 2 9 16 23 30 fri 3 10 17 24 31 sat 4 11 18 25 sun 5 12 19 26 >>> print(transform_calendar(calendar(8 , 2015))) mon 3 10 17 24 31 tue 4 11 18 25 wed 5 12 19 26 thu 6 13 20 27 fri 7 14 21 28 sat 1 8 15 22 29 sun 2 9 16 23 30 """ if __name__ == '__main__': try: print("Type month") month = input() month = int(month) print("Type year") year = input() year = int(year) print("\n\nThe calendar is: ") print (calendar(month, year)) except ValueError as err: print(err)
from typing import List def sieve_flavius(elements_number: int) -> List[int]: list_of_numbers = [] for i in range(1, elements_number): list_of_numbers.append(i) for item in list_of_numbers: if item % 2 == 0: list_of_numbers.remove(item) variable = 1 while variable < len(list_of_numbers): del list_of_numbers[list_of_numbers[variable]-1::list_of_numbers[variable]] variable = variable + 1 return print(list_of_numbers) sieve_flavius(1)
def dyvo_insert(sentence, flag): """ Inserting word "диво" before every word that starts with flag. >>> dyvo_insert("кит", "ки") диво кит >>> dyvo_insert("Кит кота по хвилях катав - кит у воді, кіт на киті.", "ки") """ # index = sentence.find(flag) # final_string = sentence[:index] + 'диво ' + sentence[index:] # return print(final_string) # str = "thisissometextthatiwrotetext" substr = flag sentence = sentence.lower() inserttxt = "диво" new_string = (inserttxt+substr).join(sentence.split(substr)) return print(new_string) dyvo_insert("кит", "ки") dyvo_insert("Кит кота по хвилях катав - кит у воді, кіт на киті.", "ки")
"""[sumary] """ def digit_sum(num: int) -> int: """Retturn sum of number digits :param num: [description] type num: int """ def add_digits(num): total = 0 while num > 0: num, rem = divmod(num, 10) total += rem return total if num == 0: return 0 total = add_digits(num) while total > 9: total = add_digits(total) return total # print(digit_sum(3456)) # if __name__ == '__main__': # import doctest # print(doctest.testmod())
def firstday(year,month): # Refer to the website above for better understanding of the program dict1={1:1,2:4,3:4,4:0,5:2,6:5,7:0,8:3,9:6,10:1,11:4,12:6} last1=int(str(year)[len(str(year))-2:]) last=(last1//4)+1 last=last+dict1[month] if isleap(year) and (month==1 or month==2) : last=last-1 else: last=last if year>=1900 and year<2000: last+=0 elif year>=2000 and year<3000: last+=6 elif year>=1700 and year<1800: last+=4 elif year>=1800 and year<=1900: last+=2 last+=last1 if last%7==1: return 0 if last%7==2: return 1 if last%7==3: return 2 if last%7==4: return 3 if last%7==5: return 4 if last%7==6: return 5 if last%7==0: return 6 def isleap(year): if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: return True else: return False else: return True else: return False def print_calendar(year,month): months={1:"January",2:"Feburary",3:"March",4:"April",5:"May",6:"June",7:"July",8:"August",9:"September",10:"October",11:"November",12:"December"} days_31=[1,3,5,7,8,10,12] days_30=[4,6,9,11] print("Mo Tu We Th Fr Sa Su") day=firstday(year,month) if month in days_31: total_days=31 elif (month in days_30): total_days=30 else: if isleap(year)==True: total_days=29 else: total_days=28 if day!=6: print(" "*(day*4-1),'01',end="") elif day==6: print(""*(day*4-50),'01') day+=1 for i in range(2,total_days+1): if i<10: i1="0"+str(i) else: i1=i if day%7==0: print(i1,end="") elif day%7==1: print(" ",i1,end="") elif day%7==2: print(" ",i1,end="") elif day%7==3: print(" ",i1,end="") elif day%7==4: print(" ",i1,end="") elif day % 7 ==5: print(" ",i1,end="") elif day %7==6: print(" ",i1) day+=1 print_calendar(2015,8)
import re def number_of_sentences(s): """ str -> str Return number of sentence in the string. If argument is not a string function should return None. >>> number_of_sentences("Revenge is a dish that tastes best when served cold.") 1 >>> number_of_sentences("Never hate your enemies. It affects your judgment.") 2 >>> number_of_sentences(2015) """ if type (s) == str: count = len(re.findall(r'\.', s)) return print(count) else: return None number_of_sentences(45)
def motzkin_sum_numbers(length): """ >>> motzkin_sum_numbers(15) [1, 0, 1, 1, 3, 6, 15, 36, 91, 232, 603, 1585, 4213, 11298, 30537] """ new_list = [] len = list(range(1, length)) new_list.append(1) for i in len: # element_in_list = bin(i) element_in_list = int((i-1)*(2 * new_list[i-1] + 3 * new_list[i-2])/(i+1)) new_list.append(element_in_list) # return new_list print(motzkin_sum_numbers(15))
# merge 2 sorted arrays # given A=[] # B=[] # output- A=A+B def mergearr(A,B,m,n): while m >0 and n>0: if A[m-1]>B[n-1]: A[m+n-1]=A[m-1] m=m-1 else: A[m+n-1]=B[n-1] n=n-1 while n >0: A[m+n-1]=B[n-1] n=n-1 return A print(mergearr([2,4,5,6,9,0,0,0,0],[4,5,6,7],5,4))
import pandas as pd import numpy as np # Import cricket data cricket = pd.read_csv('./Data/cricket_matches.csv') # Only include if home team was the winner cricket_home_winners = cricket[(cricket['home'] == cricket['winner'])] # Pull out the rows where the winners were the home team based on inning cricket_home_inning_1 = cricket_home_winners[(cricket['home'] == cricket['innings1'])] cricket_home_inning_2 = cricket_home_winners[(cricket['home'] == cricket['innings2'])] # create home innings data frames for innings 1 and 2, then combine cricket_home_inning_1_runs = cricket_home_inning_1[['home', 'innings1_runs']] cricket_home_inning_2_runs = cricket_home_inning_2[['home', 'innings2_runs']] cricket_home_both_innings = cricket_home_inning_1_runs.append(cricket_home_inning_2_runs) # group by home and find the mean average_cricket = cricket_home_both_innings.groupby('home').mean() # calculate the average of each row and print to csv average_cricket.mean(axis=1).to_csv('Question3Part1_cricket.csv') # print a few rows to the screen print(average_cricket.head())
"""Fibonacci iterative implementation https://stackoverflow.com/questions/14661633/finding-out-nth-fibonacci-number-for-very-large-n/ """ def fibonacci(n: int) -> int: """Implement Fibonacci iteratively Raise: - TypeError for given non integers - ValueError for given negative integers """ if type(n) is not int: raise TypeError("n isn't integer") if n < 0: raise ValueError("n is negative") if n == 0: return 0 a = 0 b = 1 for i in range(2, n+1): a, b = b, a+b return b def lambda_handler(event, context): """Lambda function for iterative Fibonacci""" return fibonacci(event["n"])
import os # patient_name = "John Smith" # patient_age = 20 # patient_isNew = True os.system('cls') # print("Name: " + patient_name) # print("Age: " + str(patient_age)) # print("New Patient: " + str(patient_isNew)) # === STRINGS ==== # course = "Python Programming" # print("String Length: " + str(len(course))) # print("0TH index: " + str(course[0])) # print("Last Index: " + str(course[-1])) # print("First three characters: " + str(course[0:3])) # print("First to last characters: " + str(course[0:])) # === ESCAPE SEQUENCES === # Double Quotes - \" : Single Quotes = \' # Slash - \\" : New Line = \n # course = "Python \"Programming\"" # print(course) # === FORMATTED STRINGS === # first = "Ken" # last = "Javier" # full = f"{first} {last}" # print(full) # === STRING METHODS === # course = " python programming" # print("Uppercase : " + str(course.upper())) # print("Lowercase : " + str(course.lower())) # print("Title Form : " + str(course.title())) # print("No Whitespace : " + str(course.strip())) # print("Find Index : " + str(course.find("pro"))) # print("Replace : " + str(course.replace("p","j"))) # print("In String : " + str("pro" in course)) # print("Not In String : " + str("swift" not in course)) # === NUMBERS === # print("Add : " + str(10 + 3)) # print("Subtract : " + str(10 - 3)) # print("Multiply : " + str(10 * 3)) # print("Divide : " + str(10 / 3)) # print("Divide in integer: " + str(10 // 3)) # print("Remainder : " + str(10 % 3)) # print("Exponent : " + str(10 ** 3)) # import math # print("Round : " + str(round(2.9))) # print("Absolute val : " + str(abs(2.9))) # print("Ceil : " + str(math.ceil(2.9))) # print("Floor : " + str(math.floor(2.9)) # === TYPE CONVERSION === # x = input("x: ") # y = int(x) + 1 # print(f"X: {x}, y: {y}") # ==== INPUT DATA ===== # birth_year = input("Enter your birth_year: ") # age = 2020 - int(birth_year) # print(age) # first_number = input("First: ") # sec_number = input("Second: ") # sum = int(sec_number) + int(first_number) # print(sum) # ==== STRINGS ==== course = 'Python for Beginners' # print(course.upper()) # print(course.find('y')) # print(course.replace('for', '4')) print('Python' in course) # ==== IF STATEMENTS ==== # temperature = 25 # if temperature > 30: # print("It's a hot day!") # print("Drink plenty of water!") # elif temperature > 20: # print("It's a nice day!") # elif temperature > 10: # print("It's a bit cold!") # else: # print("It's cold!") # ==== TERNARY OPERATOR ==== # age = 22 # message = "Eligible" if age >= 18 else "Not Eligible" # print(message) # ==== LOGICAL OPERATORS ==== # high_income = False # good_credit = True # student = True # if (high_income or good_credit) and not student: # print("Eligible") # else: # print("Not Eligible") # === CHAINING COMPARISON OPERATORS ==== # age = 22 # if 18 <= age < 65: # print("Eligible") # === EXERCISE ==== # weight = input("Weight: ") # option = input("(K)g or (L)bs: ") # if option.upper() == 'K': # weight = float(weight) * 2.20462 # weight = format(weight, '.2f') # print("Weight in Lbs:" + str(weight)) # elif option.upper() == 'L': # weight = float(weight) / 2.20462 # weight = format(weight, '.2f') # print("Weight in Lbs: " + str(weight)) # else: # print("Invalid input!") # i = 1 # while i <= 5: # print(i) # i = i + 1 # === LISTS === # names = ['Steve', 'Tony', 'Peter', 'Wanda'] # print(names[0]) #Steve # print(names[-1]) #Wanda # names[0] = 'Rogers' # print(names) # print(names[0:3]) #['Steve', 'Tony', 'Peter'] # numbers = [1, 2, 3, 4, 5] # numbers.append(6) # print(numbers) # numbers.insert(2, 6) # print(numbers) # numbers.remove(3) # print(numbers) # print(1 in numbers) #True # print(len(numbers)) #6 # numbers.clear() # print(numbers) # === FOR LOOPS === # for number in range(3): # print("Attempt", number + 1, (number + 1) * ".") # for number in range(1, 4): # print("Attempt", number, (number) * ".") # for number in range(1, 10, 2): #params - start, end, steps/skips # print("Attempt", number, (number) * ".") # numbers = [1, 2, 3, 4, 5] # for item in numbers: # print(item) # === RANGE FUNCTION === # numbers = range(5) # numbers = range(5, 10) # numbers = range(5, 9, 2) # print(numbers) # for number in numbers: # print(number) # ctr = 0 # for num in range(1, 10): # if (num%2 == 0): # print(str(num) + "\n") # ctr = ctr + 1 # print(f"We have {str(ctr)} even numbers") #=== FUNCTIONS ==== # def greet(first_name, last_name): # print(f"Hi {first_name} {last_name}") # print("Welcome Aboard") # greet("Ken", "Javier") # === Keyword Arguments === # def increment(number, by): # return number + by # print(increment(number=2, by=1)) # === Default Arguments === # def increment(number, by=1): # return number + by # print(increment(2)) # ==== *args ==== # def multiply(*numbers): # total = 1 # for number in numbers: # total *= number # return total # print("Start") # print(multiply(2, 3, 4, 5)) # ==== **args ==== # def save_user(**user): # #print(user) # print(user["name"]) # save_user(id=1, name="Ken", age="20") # === Fizz Buzz === # def fizz_buzz(input): # if (input % 3) == 0 == (input % 5): # return "FizzBuzz" # elif (input % 3) == 0: # return "Fizz" # elif (input % 5) == 0: # return "Buzz" # else: # return input # print(fizz_buzz(30))
# https://www.hackerrank.com/challenges/building-a-list t = int(input()) for tests in range(t): n = input() s = input() o = [] length = "0"+str(len(s))+"b" for i in range(1<<len(s)): op = "" binary = format(i,length) for j in range(len(binary)): if binary[j]=='1': op+=s[j] if len(op)>0: o.append(op) o.sort() for i in o: print (i)
lphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] global h global n global w global pol global poh n=0 height = [] while n<=25: print ('Height of the ', end ="") print (alphabet[n] , end = '') h = int(input(' letter ')) if 1 <= h <= 7: height.append(h) n=n+1 else: print ('Wrong height ') print (height) w = (input('Word contains no more than 10 letters ')) if 1<=len(w) <=10 : m=0 thelastone = [] while m<=len(w)-1: pol = (alphabet.index(w[m])) poh = (height[pol]) thelastone.append(poh) m=m+1 else: print ('Too many letters') print (max(thelastone)*len(w)*1) print('Hello') return height viewer()
import math import os import random import re import sys def alternatingCharacters(s): ch = list(s) res = ch[0] count = 0 #print(ch) for c in range(len(ch)-1): #print(ch[c],ch[c+1]) if ch[c] != ch[c+1]: res = res + ch[c+1] else: count += 1 return(count) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') q = int(input()) for q_itr in range(q): s = input() result = alternatingCharacters(s) fptr.write(str(result) + '\n') fptr.close()
# -*- coding: utf-8 -*- """ Created on Tue May 7 10:45:10 2019 @author: Gerardo Armenta Instructor: Dr. Olac Fuentes TA: Anindita Nath, Maliheh Zargaran, Erik Macik, Eduardo Lara Purpose: part1: To write a program that discovers trigonometric identities using a randomized algorithm to detect equalities using random numbers in range of -pi to pi. part2: To write a program that determines if there is a way to partition a set of integers into two substes using backtracking. """ import random import math import mpmath import time ''' ############################################################################### PART 1 ############################################################################### ''' # Checks equality for all trig functions in main with different t values def are_equal(f1, f2, n): # There are n (length of trig functions list) number of times trig functions # are checked for equalities. for i in range(n): t = random.uniform(-math.pi,math.pi) # t varies per each test # The following functions aren't recognized by the math libary used # so they are changed to be recognized by math and mpmath (for sec(t)). if f1 == 'sin^2(t)': # sin(t) to the power of 2 f1 = 'math.pow(math.sin(t),2)' if f1 == '1-cos^2(t)': # 1 - cos(t) to the power of 2 f1 = '1-math.pow(math.cos(t),2)' if f1 == 'sec(t)': # sec not recognized by math, used mpmath f1 = 'mpmath.sec(t)' if f2 == 'sin^2(t)': # sin(t) to the power of 2 f2 = 'math.pow(math.sin(t),2)' if f2 == '1-cos^2(t)': # 1 - cos(t) to the power of 2 f2 = '1-math.pow(math.cos(t),2)' if f2 == 'sec(t)': # sec not recognized by math, used mpmath f2 = 'mpmath.sec(t)' # Values are rounded to the 7th decimal point to avoid any float issues. y1 = round(eval(f1), 7) y2 = round(eval(f2), 7) if y1 != y2: # if results after evaluation are different, returns false return False return True # returns true if comparisons of trig identities are equal # Sets the comparisons for the trig identities and shows equalities to the user. def comparisons(trig, n): start = time.time()*1000 count = 0 # Counter used to show total of equalities found to user. while len(trig) > 0: # gets the first element of the list for f1 f1 = trig[0] trig.pop(0) # removing element 0 keeps while loop moving and assures f1 and f2 aren't the same for function in trig: # loop used to set f2 and check for equality f2 = function if are_equal(f1,f2,n) is True: # if equality found lets user know count += 1 # counter adds 1 every time equality is found print('\n',f1, ' is equal to ', f2) stop = time.time()*1000 print('\n There are a total of ', count, ' equalities from ', n, ' trigonometric funtions. Time elapsed = ', stop-start, 'milliseconds') ''' ############################################################################### PART 2 ############################################################################### ''' # adds the sum of a given subset def subset(s): if len(s) == 0: # used to return 0 if list is empty return 0 a = sum(s) return a def partition(S1,S2,last): if last < 0: # once last is less than 0 there are no more subsets to be compared return False,S1,S2 if subset(S1) == subset(S2): # if two subsets are equal, a partition exists return True,S1,S2 if subset(S1) < subset(S2): # if S1 is less than S2, the last value added to S2 is returned to S1 and removed from S2 S1.append(S2[-1]) S2.remove(S2[-1]) else: S2.append(S1[last]) # if sum of S1 is more than sum of S2, last value is removed from S1 and added to S2 S1.remove(S1[last]) return partition(S1,S2,last-1) # New comparisons are made with changes to subsets S1 and S2 making last subtrated by one to traverse lists # list of trig identities trig_id = ['sin(t)', 'cos(t)', 'tan(t)', 'sec(t)', '-sin(t)', '-cos(t)', '-tan(t)', 'sin(-t)', 'cos(-t)', 'tan(-t)', 'sin(t)/cos(t)', '2*sin(t/2)*cos(t/2)', 'sin^2(t)', '1-cos^2(t)', '(1-cos(2*t))/2', '1/cos(t)'] comparisons(trig_id, len(trig_id)) # will check for equalities in trig_id list # asks user to select S list selection = (int(input('Select 1 for S = [2, 4, 5, 9, 12] or select 2 for S = [2, 3, 5, 8, 13]: '))) if selection == 1: S = [2, 4, 5, 9, 12] else: S = [2, 3, 5, 8, 13] start = time.time()*1000 is_set,s1,s2 = partition(S, [], len(S)-1) set_list = sorted(s1+s2) # s1 + s2 will create original S list in ascending order stop = time.time()*1000 if is_set is True: # if a partition is found print('\n This set: S =', set_list, ' has a partition ', s1, ' ', s2, '. Time elapsed = ', stop-start, 'milliseconds') else: # if no partition is found print('\n No partition exists for: S =', set_list, '. Time elapsed = ', stop-start, 'milliseconds')
# Задание №7 - сделано entered_number = int(input('Please enter an integer number: ')) factorial_of_entered_number = 1 while entered_number > 0: factorial_of_entered_number = factorial_of_entered_number * entered_number entered_number -= 1 print('Factorial of entered number = ', factorial_of_entered_number)
# This is a sample Python script. # Press Shift+F10 to execute it or replace it with your code. # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings. def print_hi(name): # Use a breakpoint in the code line below to debug your script. print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint. # Press the green button in the gutter to run the script. if __name__ == '__main__': print_hi('PyCharm') # See PyCharm help at https://www.jetbrains.com/help/pycharm/ origPrice = float(input('Enter the original price: $')) discount = float(input('Enter discount percentage: ')) newPrice = (1 - discount/100)*origPrice calculation = '${} discounted by {}% is ${}.'.format(origPrice, discount, newPrice) print(calculation) # For two decimal places origPrice = float(input('Enter the original price: $')) discount = float(input('Enter discount percentage: ')) newPrice = (1 - discount/100)*origPrice calculation = '${:.2f} discounted by {}% is ${:.2f}.'.format(origPrice, discount, newPrice) print(calculation)
def date(day,month,year): x=[31,28,31,30,31,30,31,31,30,31,30,31] if year%4==0: if year%100==0: if year%400==0: x[1]=29 else: x[1]=29 d=sum(x[:month-1]) total=d+day return(total)
c=['red','blue','green','white','black','purple','orange','pink','brown','gray'] a=int(input("yek adad az 0 ta 4: ")) b=int(input("yek adad az 5 ta 9: ")) print(c[a:b])
s=0 while s<=5: s=int(input('enter number: ')) print('the last number you entered was s',s)
print('Who do you whant to invite to the party') q=input('1: ') w=input('2: ') e=input('3: ') r=input('Do you whant to add another yes/no ') s=3 while r=='yes': s=s+1 t=input(s ) r=input('Do you whant to add another yes/no ') print(s)
""" Filename globbing like the python glob module with minor differences: * glob relative to an arbitrary directory * include . and .. * check that link targets exist, not just links """ import fnmatch import os import re from pathlib import Path from typing import Union, List from . import util _glob_check = re.compile('[\[*?]') def has_glob(p: str) -> bool: return _glob_check.search(p) is not None def glob(fs_dir: Union[str, Path], path: Union[str, Path]) -> List[str]: """ Yield paths matching the path glob. Sorts as a bonus. Excludes '.' and '..' """ directory, leaf = os.path.split(path) if directory == '': return glob_pattern(fs_dir, leaf) if has_glob(directory): dirs_found = glob(fs_dir, directory) else: dirs_found = [directory] r = [] for directory in dirs_found: fspath = util.normaljoin(fs_dir, directory) if not os.path.isdir(fspath): continue r.extend((util.normaljoin(directory, found) for found in glob_pattern(fspath, leaf))) return r def glob_pattern(directory: Union[str, Path], pattern: str) -> List[str]: """ Return leaf names in the specified directory which match the pattern. """ if not has_glob(pattern): if pattern == '': if os.path.isdir(directory): return [''] return [] if os.path.exists(util.normaljoin(directory, pattern)): return [pattern] return [] leaves = os.listdir(directory) + ['.', '..'] # "hidden" filenames are a bit special if not pattern.startswith('.'): leaves = [leaf for leaf in leaves if not leaf.startswith('.')] leaves = fnmatch.filter(leaves, pattern) leaves = [l for l in leaves if os.path.exists(util.normaljoin(directory, l))] leaves.sort() return leaves
len1 = float(input('please input len1: ')) len2 = float(input('please input len2: ')) len3 = float(input('please input len3: ')) def cntPeremeter(l1, l2, l3): return l1 + l2 + l3 def cntArea(l1, l2, l3): p = (l1 + l2 + l3)/2 return (p*(p-l1)*(p-l2)*(p-l3)) ** 0.5 if (len1 < len2 + len3) and \ (len2 < len1 + len3) and \ (len3 < len1 + len2): print('True\nperemeter:') print(cntPeremeter(len1, len2, len3)) print('Area:\n') print(cntArea(len1, len2, len3)) else: print('False')