blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
8948d4360562d503ec11939634a5bfb6c774d679
chiragJKL/PYTHON
/Chepters/chepter 7 Loops/07_01_while_loop.py
685
3.6875
4
i = 0 while i <= 10: # here i<=10 is condition of loop. till its true programme will loop. if condition never become false it will be infinite loop print("num", i) i = i+1 # ************************************************************************ a = 1 while a <= 50: print(a) a = a+1 # ************************************************************************ x = 0 while x < 5: print("chirag") x = x+1 # ************************************************************************ # print list fruits = ["apple", "banana", "mango"] print(len(fruits)) c = 0 while c < len(fruits): # lengh is 3 and here c[0],c[1],c[2] print(fruits) c = c+1
621f0aed29dce4db75e701279cd65d8c0eb7580d
haominhe/Undergraduate
/CIS211 Computer Science II/Projects/p5/blackjack-py/Deck.py
5,339
4.03125
4
"""Project 3: Decks CIS 211 2015 Winter Haomin He This project defines a new class that extends one of Python’s built-in types, we also explore random number generators. This code has two definitions: a class named Deck and a class named PinochleDeck. I also have tried the Extra Credit Ideas. """ from sys import argv from Card import * import random class Deck(list): """This class should be derived from Python’s list class. An instance of this class will be a list of 52 Card objects (which are defined in Card.py). """ def __init__(self): """When the constructor is called it should return a list of all 52 cards in order from 2♣ up through A♠. """ list.__init__(self, [Card(i) for i in range(52)]) def shuffle(self): """This function should rearrange the cards into a new random permutation Write my own version of a method that makes a random permutation instead of using random.shuffle """ _shuffledlist = [] for every in range(len(self)): pick = random.choice(self) self.remove(pick) _shuffledlist.append(pick) self.extend(_shuffledlist) return None def deal(self, n, optionalPlayer = None): """This function should remove the first n cards from the deck and return them in a list Add a second (optional) argument to the deal method that specifies the number of hands to create. For example, deal(5,2) will make 2 hands with 5 cards each, where the cards are dealt in the traditional fashion, i.e. alternate cards to each hand. """ if optionalPlayer == None: self._firstNcards = self[0:n] del self[0:n] return self._firstNcards elif optionalPlayer != None: total_cardsnum = n * optionalPlayer self._firstNcards = self[0:total_cardsnum] del self[0:total_cardsnum] hands = [[] for player in range(optionalPlayer)] i = -1 for eachcard in range(n): for h in hands: i += 1 h.append(self._firstNcards[i]) return hands def restore(self, a): """This function should add the cards in list a to the end of the deck This function verify its argument is a list of Card objects """ flag = True for i in range(len(a)): if type(a[i]) != Card: flag = False if flag == True: self.extend(a) else: Deck.not_implemented() @staticmethod def not_implemented(): """This function prevents users from altering the decks with list methods like append. """ raise Exception("operation not implemented") def append(self, val): Deck.not_implemented() def insert(self, loc, val): Deck.not_implemented() class PinochleDeck(Deck): """This class has Deck as its base class. An instance of this class should be a list of 48 cards. The game of Pinochle uses only 9s and above, and there are two copies of each card. A new deck should be sorted. """ def __init__(self): """When the constructor is called it should return a list of 48 cards. """ Deck.__init__(self) _PDlist = [] for each in self: if (each._rank >= 7): _PDlist.append(each) _PDlist.append(each) _PDlist.sort() list.__init__(self, _PDlist) if __name__ == "__main__": d = Deck() print("should be 52 ----> {}".format(len(d))) print("should be <class 'Card.Card'> ----> {}".format(type(d[0]))) print("should be [2♣, 3♣, 4♣, ... Q♠, K♠, A♠] ----> {}".format(d)) d.shuffle() print("should be random 52 cards ----> {}".format(d)) h = d.deal(5) print("should be first 5 cards ----> {}".format(h)) print("should be random 47 cards ----> {}".format(d)) print("should be 47 ----> {}".format(len(d))) d.restore(h) print("cards should be added at the end ----> {}".format(d)) print("should be 52 ----> {}".format(len(d))) d.sort() print("should be [2♣, 3♣, 4♣, ... Q♠, K♠, A♠] ----> {}".format(d)) print("=================================================================") d = PinochleDeck() print("should be [9♣, 9♣, 10♣, 10♣, ... Q♠, Q♠, K♠, K♠, A♠, A♠] ----> {}".format(d)) d.shuffle() h = d.deal(12) h.sort() print("12 random cards should be in ordered: ♣, ♦, ♥, ♠ ----> {}".format(h)) print("=================================================================") d = Deck() print("should be [2♣, 3♣, 4♣, ... Q♠, K♠, A♠] ----> {}".format(d)) try: d.append('howdy') print("after appending 'howdy' to the Deck:", d) except Exception as e: print("should have error message ----> {}".format(e)) print("should be 52 ----> {}".format(len(d))) d.shuffle() print("should have no appended string in it ----> {}".format(d))
a016208fc8104ecfcb0cd5a5cde73a0f66a32fab
MirkoNardini/tomorrowdevs
/Workbook - cap 1/Exercise 18 Volume of a Cylinder.py
238
3.828125
4
import math raggio = float(input("inserisci il raggio: ")) altezza = float(input("inserisci l'altezza: ")) area = raggio * raggio * math.pi volume = area * altezza round(volume) print("il volume del cilindro è: ", volume)
83c95ba12fcd66243f76f08a1b7777457b2ccff1
EmilShafikov/Phyton
/If else elif.py
269
4.09375
4
name = "Tom" height = 2 weight = 80 bmi = weight / (height ** 2) print ("Индекс массы тела: " + str(bmi)) if bmi < 25: print ("У" + name + " нет лишнего веса") else: print ("У" + name + " есть лишний вес")
4e230b670dcf41b4b787f09758232c35400c8972
LeafmanZ/CS180E
/[Chapter 05] Loops/Convert to binary.py
102
3.859375
4
''' Type your code here. ''' x = int(input()) while x > 0: print(x%2, end='') x = x//2 print()
77ae6c4c5dd3045dc022a9f1331ec520e8f22666
nmkmms/linear_prog
/problem.py
1,629
3.578125
4
from pulp import * def main(): """Create problems, solve & display.""" # Define variables x1 = pulp.LpVariable("x1", lowBound=0) x2 = pulp.LpVariable("x2", lowBound=0) # Create system of linear equations sys_eq = [ (2 * x1 + 4 * x2, "Target function"), (5 * x1 + 8 * x2 <= 40, "1"), (7 * x1 + 5 * x2 <= 35, "2"), (x1 + x2 >= 2, "3"), (x1 - x2 <= 3, "4"), (-x1 + x2 <= 4, "5") ] # Create problems (maximizing and minimizing) max_prob = pulp.LpProblem("0", LpMaximize) min_prob = pulp.LpProblem("0", LpMinimize) # Get result max_res = solve_problem(max_prob, sys_eq) min_res = solve_problem(min_prob, sys_eq) # Display results print("=" * 50) print(f"Maximum of target function:\n\t{max_res['obj']}") print(f"Variables:\n\t" f"x1 = {max_res['x1']}\n\t" f"x2 = {max_res['x2']}") print("=" * 50) print(f"Minimum of target function:\n\t{min_res['obj']}") print(f"Variables:\n\t" f"x1 = {min_res['x1']}\n\t" f"x2 = {min_res['x2']}") print("=" * 50) def solve_problem(problem, sys_eq: list) -> dict: """Fill & solve problem. Problem is a system of linear equations with target function. """ # Fills problem for eq in sys_eq: problem += eq # Solve and save results in dict problem.solve() res = {} for variable in problem.variables(): res[variable.name] = [variable.varValue] res["obj"] = value(problem.objective) return res if __name__ == "__main__": main()
a5ee0208b69d5297b6f82864d6a4cdde74b4b1be
s19013/my_program_python
/gui/matomete_test.py
1,074
3.515625
4
import tkinter as tk root = tk.Tk().title("Visualizer for function") # ボタンが押されたときのコールバック関数 #def btn0_callback(): # print("ボタン0が押されました") #def btn1_callback(): # print("ボタン1が押されました") #def btn2_callback(): # print("ボタン2が押されました")# ## ボタンの作成 #button0 = tk.Button(root,text="0",command=btn0_callback) #button0.pack(fill="x") #button1 = tk.Button(root,text="1",command=btn1_callback) #button1.pack(fill="x") #button2 = tk.Button(root,text="2",command=btn2_callback) #button2.pack(fill="x") class Application(tk.Frame): def __init__(self, master = None): tk.Frame.__init__(self, master) self.pack(expand = 1, fill = tk.BOTH, anchor = tk.NW) def make_bottun(self,i): self.i=i buttun=tk.Button(root,text=self.i,command=lambda: print("ボタン{}が押されました".format(self.i))) buttun.pack(fill="x") a=Application() for i in range(3): a.make_bottun(i) app = Application(master = root) app.mainloop()
2de2f8e2c6fdc3b67915673147c26da55fd5d555
ProgressBG-Python-Course/ProgressBG-VMware-Python-Code
/lab4/ranges.py
258
4.21875
4
# r1 = range(3) # # print(list(r1)) # # even numbers in the [1..10] # for i in range(-5,0,-1): # print(i) # # odd numbers in interval [-10 .. 0] # # -9, -7,....-1 # for i in range(-9, 0,2): # print(i) str = 'abc' for i in range(len(str)): print(i)
f5e47ff3589f815d5d427008f66a10859ca312e3
Lightblash/CalculatorLibrary
/calculator.py
362
3.5625
4
""" Calculator library containing basic math operations. """ def add(first_term, second_term): return first_term + second_term def subtract(first_term, second_term): return first_term - second_term def multiply(first_item, second_item): return first_item * second_item def divide(first_item, second_item): return first_item / second_item
da6577d866e2707897f96c162dfd614e1fcd86bb
tidalmelon/addrseg
/urlutil.py
1,027
3.84375
4
# -*- coding=utf-8 -*- import urlparse def reverseUrl(url): """ examples: http://bar.foo.com:8983/to/index.html?a=b com.foo.bar:http:8983/to/index.html?a=b https://www.google.com.hk:8080/home/search;12432?newwi.1.9.serpuc#1234 hk.com.google.www:https:8080/home/search;12432?newwi.1.9.serpuc#1234 """ reverse_url = '' url = urlparse.urlsplit(url) reverse_host = '.'.join(url.hostname.split('.')[::-1]) reverse_url += reverse_host reverse_url += ':' reverse_url += url.scheme if url.port: reverse_url += ':' reverse_url += str(url.port) if url.path: reverse_url += url.path if url.query: reverse_url += '?' reverse_url += url.query if url.fragment: reverse_url += '#' reverse_url += url.fragment return reverse_url if __name__ == '__main__': url = 'http://www.tianyancha.com/company/2313776032' url = 'http://www.11467.com/foshan/co/444200.htm' print reverseUrl(url)
969c419251044ee08b3cf62da310fd4b7814a509
chenyao330/Learning-scrap-project
/3report_output_codes.py
5,045
3.625
4
""" Data processing program is to clean the scrape data, then to export a modified .csv file, so that we can use it whenever we want to do analysis Author: Yao Chen Edite Date: 16/05/2019 """ import pandas as pd import matplotlib.pyplot as plt import numpy as np import xlsxwriter import os os.chdir('H:/1ads/COSC480-19S1/project/') # set a path to sav files def column_plot(dataframe, column, figure_no): """Given the column to plot a counts of bar and price of box_plot then save it as a .png file. parameters: dataframe:the target dataframe. column: the name of the plot column. figure_no: number of the figure showed in the report. """ plt.ioff() fig, [axes_1, axes_2] = plt.subplots(2, 1, sharex=True) counts = dataframe[column].value_counts() counts.plot(kind='bar', grid=True, rot=60, ax=axes_1, fontsize=10) axes_1.set_ylabel("number of cars") title = "Firgure{}_counts&price_by_{}".format(figure_no, column) dataframe.boxplot(column="price", by=column, grid=True, rot=60, ax=axes_2, fontsize=10) axes_2.set_ylabel("price") axes_2.set_xlabel(column) plt.savefig(title, dpi=96, bbox_inches='tight') plt.close() def group_count_bar_plot(dataframe, column, bin_list, figure_no): """Group the specific column and draw a bar plot, save as a .png file. Parameters: dataframe: the target dataframe. column: name of a column need to be grouped. bin_list: list of the gaps according to which the column is grouped. figure_no: number of the figure showed in the report. """ plt.ioff() fig, axes = plt.subplots() group_var = pd.cut(dataframe[column], bin_list) counts = dataframe.groupby(group_var)[column].count() counts.plot(kind='bar', grid=True, rot=60, ax=axes, fontsize=10) axes.set_ylabel("number of cars") title = "Firgure{}_counts_by_{}".format(figure_no, column) plt.savefig(title, dpi=96, bbox_inches='tight') plt.close() def group_price_box_plot(dataframe, column, bin_list, figure_no): """Group the specific column and draw a box plot, save as a .png file. Parameters: dataframe: the target dataframe. column: name of a column need to be grouped. bin_list: list of the gaps according to which the column is grouped. figure_no: number of the figure showed in the report. """ plt.ioff() fig = plt.figure() group_var = pd.cut(dataframe[column], bin_list) grouped = dataframe.groupby(group_var) boxplot = grouped.boxplot(column='price', grid=True,fontsize=8) title = "Firgure{}_price_by_{}".format(figure_no, column) plt.savefig(title, dpi=96, bbox_inches='tight') plt.close() def get_file(extension): """Get the list of addresses of files with an specific extension. Parameter: extension: the type of a file, e.g.,'xlsx','png'. """ file_set = set() for path, dirs, filelist in os.walk(".", topdown=False): for filename in filelist: if filename.endswith(extension): file = os.path.join(path, filename) file_set.add(file) file_list = list(file_set) file_list.sort() #order the file according to the name return file_list def main(): """Prompt to imput a price limit; read the modified csv file; form a report for the user """ max_value = int(input("Enter the max price: ")) # read the modified_data and form target dataframe by the given limit filename = '2_modified_data.csv' df_modified = pd.read_csv(filename, encoding='gbk') df_target = df_modified.loc[df_modified["price"] <= max_value] # plot of available columns column_plot(df_target, "district", 1) column_plot(df_target, "Seats", 2) column_plot(df_target, "Fuel type", 3) # plot grouped columns, including enginesize and Kilometres engine_max = df_target['enginesize'].max() engine_bin = [0, 1200, 1500, 2000, 2500, engine_max] group_count_bar_plot(df_target, "enginesize", engine_bin, 4) group_price_box_plot(df_target, "enginesize", engine_bin, 5) #Kilometres group km_max = df_target['Kilometres'].max() kilometres_bin = [0, 1000, 10000, 50000, 100000, 200000, km_max] group_count_bar_plot(df_target, "Kilometres", kilometres_bin, 6) group_price_box_plot(df_target, "Kilometres", kilometres_bin, 7) image_list = get_file("png") workbook = xlsxwriter.Workbook('3_stat_report.xlsx') worksheet = workbook.add_worksheet() worksheet.hide_gridlines(2) start_row = 3 for image in image_list: position = "C" + str(start_row) worksheet.write(position, str(image)) start_row += 1 position = "C" + str(start_row) worksheet.insert_image(position, image) start_row += 30 workbook.close() print("Report has been successfully exported!") # Call the main function to run the program main()
bd9f8a0791b69e07c607fab0b4ec3db224c694a2
Aasthaengg/IBMdataset
/Python_codes/p02865/s429393679.py
149
3.796875
4
# coding: utf-8 # Your code here! N=int(input()) count=-1 for i in range(N//2+1): count+=1 if N%2==0: print(count-1) else: print(count)
cc37bc3938f8068d91b171ffd3e79dc0fc2a30d6
iSouma/Curso-python
/CursoemVideo/Desafio004.py
559
3.9375
4
a = input('Digite algo: ') tipo = type(a) espaços = a.isspace() número = a.isnumeric() alfabético = a.isalpha() alfanumérico = a.isalnum() maiúscula = a.isupper() minúscula = a.islower() capitalizada = a.istitle() print(f'O tipo primitivo desse valor é {tipo}') print(f'Só tem espaços? {espaços}') print(f'É número? {número}') print(f'É alfabético? {alfabético}') print(f'É alfanumérico? {alfanumérico}') print(f'Está em maiúscula? {maiúscula}') print(f'Está em minúscula? {minúscula}') print(f'Está capitalizada? {capitalizada}')
4c679ce567c1e890e248873f2a56a7f6584dac51
Moris-Camporesi/pomodoro
/GUI_study.py
4,113
3.6875
4
# EasyGui-Studies import easygui, random #easygui.msgbox("Hello there!") #user_response = easygui.msgbox("Hello there!") #print(user_response) # flavor = easygui.buttonbox("What is your favourite ice cream flavour?", choices = ['Vanilla', 'Chocolate', 'Strawberry']) # easygui.msgbox("You picked " +flavor) # flavor = easygui.choicebox("What is your favourite ice cream flavour?", choices = ['Vanilla', 'Chocolate', 'Strawberry']) # easygui.msgbox("You picked " +flavor) # flavor = easygui.enterbox("What is your favourite ice cream flavor?") # easygui.msgbox("You entered " + flavor) def number_guessing(): secret = random.randint(1,100) guess = 0 tries = 0 easygui.msgbox("""AHOY! I'm the Dread Prate Roberts, and I have a secret! It's a number from 1 to 100. I'll give you 6 tries.""") while guess != secret and tries < 6: guess = easygui.integerbox("what's yer guess, matey?", upperbound = 100) if not guess: break if guess < secret: easygui.msgbox(str(guess) + " is too low, ye scurvy dog!") elif guess > secret: easygui.msgbox(str(guess) + " is too high, landlubber!") tries += 1 if guess == secret: easygui.msgbox("Avast! Ye got it! Found my secret, ye did!") else: easygui.msgbox("No more guesses! The number was " + str(secret)) # number_guessing() # test_change = "This is a test change to check if I can push onto the repo" # ___________________________________________________________________________________________________________________________________________ # ------------------------------------------------------------------------------------------------------------------------------------------- # root = tk.Tk() # canvas = tk.Canvas(root, height = HEIGHT, width = WIDTH) # canvas.pack() # frame = tk.Frame(root, bg = '#80c1ff') #I can do hex-colors! # frame.place(relx = 0.1, rely = 0.1, relwidth = 0.8, relheight = 0.8) #expand and fill will fill out the frame # button = tk.Button(frame, text = "Test button", bg= "gray") # button.place(relx=0, rely=0, relwidth=0.25, relheight=0.25) # label = tk.Label(frame, text= "This is a label", bg= "yellow") # label.place(relx=0.3,rely=0,relwidth=0.45, relheight=0.25) # entry = tk.Entry(frame, bg='green') # entry.place(relx=0.8, rely=0, relwidth= 0.2, relheight = 0.25) # root.mainloop() import tkinter as tk HEIGHT = 400 WIDTH = 700 TIMER = "Here will be the timer" def start_function(): print("Start-Timer-Button has been clicked") def start_button_toggle(): if(Start_button['text']=='Start'): Start_button['text']='Pause' else: Start_button['text']='Start' def settings_functin(): print("Settings Button has been clicked") def preset_function(): print("Preset Button has beet clicked") root = tk.Tk() canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH) canvas.pack() #Background image # background_image = tk.PhotoImage(file='Backgrounds/tomato.png') # background_label = tk.Label(root, image=background_image) # background_label.place(relwidth=1, relheight=1) frame = tk.Frame(root, bg='#80f3cc', bd = 5) frame.place(relx=0., rely=0, relwidth=1, relheight=1) timer_frame = tk.Frame(root, bg='green', bd=5) timer_frame.place(relx= 0.5, rely=0.1, relwidth= 0.5, relheight= 0.4, anchor='n') Timer_label = tk.Label(timer_frame, text=TIMER) Timer_label.place(relwidth=1,relheight=1) Settings_button = tk.Button(frame, text='Settings', bg='gray', command=settings_functin) Settings_button.place(relx=0.25, rely=0.7, relwidth=0.2, relheight= 0.2, anchor='n') Start_button = tk.Button(frame, text='Start', bg='gray', command=lambda:[start_function(),start_button_toggle()]) Start_button.place(relx=0.5, rely=0.7, relwidth=0.2, relheight=0.2, anchor='n') Preset_button = tk.Button(frame, text='Timer-Presets', bg='gray', command=preset_function) Preset_button.place(relx=0.75, rely=0.7, relwidth=0.2, relheight=0.2, anchor='n') root.mainloop()
dd78a3e560e3970511ffe58e04d58458d101b184
AnoopKunju/code_eval
/moderate/minimun_coins.py2
863
4.03125
4
#!/usr/bin/env python2 # encoding: utf-8 """ Minimum Coins. Challenge Description: You are given 3 coins of value 1, 3 and 5. You are also given a total which you have to arrive at. Find the minimum number of coins to arrive at it. Input sample: Your program should accept as its first argument a path to a filename. Each line in this file contains a positive integer number which represents the total you have to arrive at. E.g. 11 20 Output sample: Print out the minimum number of coins required to arrive at the total. E.g. 3 4 """ import sys with open(sys.argv[1], 'r') as input: test_cases = input.read().strip().splitlines() coins = (5, 3, 1) for test in test_cases: coin, number, total = 0, 0, int(test) while total > 0: number += total / coins[coin] total = total % coins[coin] coin += 1 print number
49647e1b6050e01ae7eef2c946164379a7e5f29c
aditya-kapadia/AI-Judge
/Prediction via CNN/VectorizerEmbeddingOnly/data_preparation.py
955
3.609375
4
# -*- coding: utf-8 -*- from nltk.corpus import stopwords import string # load doc into memory def load_doc(filename): # open the file as read only file = open(filename, 'r') # read all text text = file.read() # close the file file.close() return text # turn a doc into clean tokens def clean_doc(doc): # split into tokens by white space tokens = doc.split() # remove punctuation from each token table = str.maketrans('', '', string.punctuation) tokens = [w.translate(table) for w in tokens] # remove remaining tokens that are not alphabetic tokens = [word for word in tokens if word.isalpha()] # filter out stop words stop_words = set(stopwords.words('english')) tokens = [w for w in tokens if not w in stop_words] # filter out short tokens tokens = [word for word in tokens if len(word) > 1] return tokens # load the document filename = 'dataset/affirmed/case1.txt' text = load_doc(filename) tokens = clean_doc(text) print(tokens)
aaad7abfef0f14bb6b63d2c37fcb1271c2974925
stachenov/PyLeetCode
/problems/remove_nth_node_from_end.py
640
3.875
4
from classes import ListNode # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ dummy = ListNode(0) dummy.next = head ahead = dummy for __ in xrange(n + 1): ahead = ahead.next node = dummy while ahead is not None: node, ahead = node.next, ahead.next node.next = node.next.next return dummy.next
8f6644a5513e8a6f391c22698399d993f53a7577
Antrikshhii17/myPythonProjects
/DataStructure_Algorithm/Merge_sort.py
840
4.03125
4
""" Merge sort algorithm. Time complexity- Worst case = O(n*log n). Average case = O(n*log n). Best case = O(n*log n) """ def mergesort(mylist): if len(mylist) > 1: r = len(mylist)//2 l1 = mylist[:r] l2 = mylist[r:] mergesort(l1) mergesort(l2) i = j = k = 0 while i < len(l1) and j < len(l2): if l1[i] < l2[j]: mylist[k] = l1[i] i += 1 else: mylist[k] = l2[j] j += 1 k += 1 while i < len(l1): mylist[k] = l1[i] i += 1 k += 1 while j < len(l2): mylist[k] = l2[j] j += 1 k += 1 if __name__ == '__main__': mylist = [12, 2, 19, 35, 47, 6, 1] mergesort(mylist) print(mylist)
bf707d909cb72010b6e0a492be852279e746301f
515ek/python-LinkedList
/soln05.py
251
4.25
4
#!/usr/bin/python ## Name: Vivek Babu G R ## Date: 10-09-2018 ## Assignment: Linked List ## Question 5. Write a method to reverse the elements in the same list. #################################################################################################
70a3540826c95be3079ba1c722427ae7c72c1278
heyshb/Competitive-Programming
/CodeChef/17/JULY17/NITIKA.py
295
3.671875
4
def modify(str): return str.capitalize() def modify2(str): return str.upper()[0]+". " T = int(input()); for i in range(0,T): s = input() words = s.split(' '); for j in range(0,len(words)-1): if (words[j] != ""): print(modify2(words[j]),end = '') print(modify(words[len(words)-1]))
3c59dd6190594817d7c7c808d6984d0b72ece9de
Garfounkel/most-significant-graham
/src/ngrams.py
1,456
3.515625
4
from collections import defaultdict def ngrams(input_list, n=1): return zip(*(input_list[i:] for i in range(n))) def ngrams_streams(input_list, ngram_range=(1, 4)): return [ngrams(input_list, x) for x in range(*ngram_range)] def read_words(filename): """Lazy iterator on each words of a file""" last = "" with open(filename) as file: while True: buf = file.read(10240).lower() if not buf: break words = (last+buf).split() last = words.pop() for word in words: yield word yield last def ngrams_read_file(ngrams, doc, ngram_range): words = read_words(doc) buffer = list() ngram_count = defaultdict(int) while True: try: for i in range(*ngram_range): if len(buffer) < i: buffer.append(next(words)) ngram = tuple(buffer[:i]) ngram_count[i] += 1 ngrams[ngram][doc] += 1 buffer.pop(0) except StopIteration: break return ngram_count if __name__ == '__main__': input_list = ['all', 'carl', 'more', 'graham', 'or', 'because', 'of'] print('Trigrams:', list(ngrams(input_list, 3)), '\n') input_list = ["Et", "c'est", "la", "reprise", "de", "Pavard!"] for i, x in enumerate(ngrams_streams(input_list, ngram_range=(1, 4))): print(f'{i+1}:', list(x))
8b48bbfc9be722c063c87f1da758e7d9426fdab6
artemjasan/Epic_drowing
/Epic_painting/Static/flowers.py
1,038
3.625
4
import simple_draw as sd def fractal_flower(point, angle, length, delta, color, border): if length < border: return v1 = sd.get_vector(start_point=point, angle=angle, length=length, width=3) if border < length < border + 5: v1.draw(color=color) else: v1.draw(color=sd.COLOR_GREEN, width=3) random_delta = sd.random_number((delta - 0.4 * delta), int(delta + 0.41 * delta)) # random delta for the angles next_point = v1.end_point next_angle = angle - random_delta next_point2 = v1.end_point next_angle2 = angle + random_delta shift_length = 75 coef = sd.random_number(int(shift_length * 0.8), int(shift_length * 1.21)) # random coef. for the length branch next_length = length * (coef / 100) fractal_flower(point=next_point, angle=next_angle, length=next_length, delta=delta, color=color, border=border) fractal_flower(point=next_point2, angle=next_angle2, length=next_length, delta=delta, color=color, border=border)
9a8f282b5457be55fdd83f13d41871debebb3de6
MatiasPineda/School-ICS-Generator
/main.py
6,758
3.5
4
from datetime import timedelta, datetime, timezone from ics import Calendar, Event import json # import requests # url = 'https://apis.digital.gob.cl/fl/feriados/2020' # api with every holiday in Chile # response = requests.get(url) # not working, don't know why # todo: add url parameter to modify calendar as subscription. https://stackoverflow.com/questions/4239423/is-there-anyway-to-provide-a-ics-calendar-file-that-will-automatically-keep-in-s # https://www.kanzaki.com/docs/ical/url.html # I have to learn file hosting for that # todo: once file can be hosted, add functions to change values of event # todo: https://icalendar.org/validator.html#results with open('2020_Holidays.json') as f: holiday_file = json.load(f) holiday_list = [datetime.strptime(day['fecha'], '%Y-%m-%d').date() for day in holiday_file] c = Calendar() current_day_string = datetime.strftime(datetime.now(), '%Y-%m-%d') current_time_string = datetime.strftime(datetime.now(), '%H:%M') def fix_timezone_issue(): """Returns difference between current time and UTC time to fix ICS Library UTC issue""" d = datetime.now(timezone.utc).astimezone() utc_offset = d.utcoffset() // timedelta(seconds=1) return utc_offset def generate_event(event_name="New Event", event_date=datetime.now(), event_duration="1:00", event_description=""): """Generates event object using event elements as parameters""" e = Event() e.name = event_name e.begin = event_date dur = [int(t) for t in event_duration.split(":")] e.duration = timedelta(hours=dur[0], minutes=dur[1]) e.description = event_description print(e) print('------') return e def get_dates(starting_date=current_day_string, ending_date=current_day_string, starting_time="00:00", days_of_week=[], exclude_holidays=True): """Gets every date when the event takes place, excludes holidays. (exclude_holidays = False) to include holidays""" event_days = [] first_day = datetime.strptime(starting_date + starting_time, '%Y-%m-%d%H:%M') last_day = datetime.strptime(ending_date + '23:59', '%Y-%m-%d%H:%M') # The next to lines have to be deleted if the ICS library fixes UTC issue first_day -= timedelta(seconds=fix_timezone_issue()) last_day -= timedelta(seconds=fix_timezone_issue()) day_index = first_day while day_index < last_day: if exclude_holidays: if day_index.date() not in holiday_list and day_index.weekday() in days_of_week: event_days.append(day_index) elif day_index.weekday() in days_of_week: event_days.append(day_index) day_index += timedelta(days=1) return event_days def add_to_calendar(event_name="New Event", starting_date=current_day_string, ending_date=current_day_string, days_of_week=[], starting_time="00:00", event_duration="1:00", event_description="", exclude_holidays=True): """Generates and event for every day in get_dates function""" for event_day in get_dates(starting_date, ending_date, starting_time, days_of_week, exclude_holidays): c.events.add(generate_event(event_name, event_day, event_duration, event_description)) def create_ics_file(): """Generates ICS file from calendar object""" with open('calendar.ics', 'w') as file: file.writelines(c) def read_ics_file(ics_file='calendar.ics'): """Loads ics file, returns list of the ics file""" with open(ics_file, 'r') as file: ics_as_list = file.readlines() return ics_as_list def identify_events(ics_file='calendar.ics'): """Formats list of events as a list of lists, separating each event on a new list""" ics_as_list = read_ics_file(ics_file) events_list = [] event_begin = -1 event_end = -1 for index in range(len(ics_as_list)): if ics_as_list[index][0:6] == 'BEGIN:': event_begin = index if ics_as_list[index][0:4] == 'END:': event_end = index if event_begin != -1 and event_end != -1: events_list.append(ics_as_list[event_begin:event_end + 1]) event_begin = -1 event_end = -1 # this part deletes the \n for event in events_list: for element in event: event[event.index(element)] = element[:-1] return events_list def event_dictionary(ics_file='calendar.ics'): """Turn list of events as dictionary, returns a list of dictionaries""" event_list = identify_events(ics_file) dict_list = [] for event in event_list: dictionary = {} for element in event: split = element.index(':') dictionary[element[:split]] = element[split + 1:] dict_list.append(dictionary) return dict_list def check_if_event_in_ics(uid): """Returns tuple with bool as first element and a dict as second element""" for event in event_dictionary(): if event.get('UID') == uid: return True, event return False, {} def cancel_event(uid): """You can't cancel events from ics file, has to be manually, this moves selected event to now so you can delete it """ event = list(check_if_event_in_ics(uid)) time_now = datetime.now() - timedelta(seconds=(fix_timezone_issue())) formatted_time = datetime.strptime(time_now, '%Y%m%dT%H%m%S') if event[0]: event[1]['STATUS'] = 'CANCELLED' event[1]['DTSTART'] = str(formatted_time) def change_duration(uid, new_duration='1:00'): event = list(check_if_event_in_ics()) if event[0]: event[1]['DURATION'] = duration def modify_events(): uid_list = [event.get('UID') for event in event_dictionary()] return uid_list name = "Maths" # input("Name: ") start = "2020-06-01" # input("Start date yyyy-mm-dd") end = "2020-06-14" # input("End date yyyy-mm-dd") days = [0, 2, 4] # Monday, Wednesday, Friday # while True: # d = (input("day of week (0-6)")) # if d == "" or int(d) < 0 or int(d) > 6: # break # days.append(int(d)) start_time = "18:50" # input("Start time (hh:mm)") duration = "1:20" # input("Event duration (hh:mm)") details = "Super boring" # input("event description") # # generate = IcsGenerator(name, start, end, days, start_time, duration, details) # # generate.add_to_calendar() # generate.create_ics_file() new_start_time = '21:00' new_duration = '2:00' # add_to_calendar(name, start, end, days, start_time, duration, details) # print(c) # create_ics_file() # print('---------------') # print(fix_timezone_issue()) # print((read_ics_file())) # print((read_ics_file())[3:-1]) # print(identify_events()) # print("."*20) print(event_dictionary()) print("." * 20) print(modify_events()) print("." * 20)
1d385fe2853ee7fc8c148e5c8c346efc8246f27b
mrtdn/Archive
/2021-1/12-Basic-Python-Projects/3-GuessTheNumber-User-Version/GuessTheNumber-User-Version.py
846
4.09375
4
# Mert Dinçer import random print(f'Welcome to this easy game. Choose an interval. Computer will\n \ try to guess it. If it is lower than its guess type "l" if not type "h".') intv = input('Enter your interval as space-seperated: ') interval = [int(i) for i in intv.split()] x, y = interval[0], interval[1] def make_computer_guess(x, y): count = 1 number = int(input('Enter your number: ')) comps_guess = random.randint(x, y) while comps_guess != number: print(f'Computer\'s guess: {comps_guess}') l_or_h = str(input('Lower or higher: ')) if l_or_h == 'l': comps_guess = random.randint(x, comps_guess) elif l_or_h == 'h': comps_guess = random.randint(comps_guess, y) count += 1 return count print(f'Comp found it on {make_computer_guess(x, y)} try.')
30f17d3a01f2383d5b24c7fd455bbf93d9133e9e
Ariel-De-Sarro/statistics_practices
/mult_sk.py
1,704
3.890625
4
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns sns.set() from sklearn.linear_model import LinearRegression from sklearn.feature_selection import f_regression data = pd.read_csv('1.02. Multiple linear regression.csv') x = data[['SAT', 'Rand 1,2,3']] y = data['GPA'] reg = LinearRegression() reg.fit(x, y) print(reg.coef_) print(reg.intercept_) print(reg.score(x, y)) #aca me tira el r2 # para calcular el r2 ajustado: r2 = reg.score(x, y) print(x.shape) # aca vemos la forma de la variable x, en este caso es 84,2 n = x.shape[0] #numero de observaciones, 84 p = x.shape[1] #numero de predictores, o features, 2 adj_r2 = 1 - (1 - r2)*(n - 1)/(n - p - 1) #formula para calcular r cuadrado ajustado print(adj_r2) print(f_regression(x, y)) # usamos este metodo importado para calcular los estadisticos F y los p valores # en este caso como son dos variables independientes a analizar, nos va a dar 2 listas, la primera con # los F estadisticos y la segundas con los p valores p_values = f_regression(x, y)[1] #los p valores los escribe en cientifico p_values.round(3) #redondeo los p valores a 3 cifras despues de la coma # aca hacemos una tabla con los valores calculados reg_summary = pd.DataFrame(data = x.columns.values, columns=['Features']) reg_summary['Coefficients'] = reg.coef_ reg_summary['p-values'] = p_values.round(3) print(reg_summary) # para estandarizar la data from sklearn.preprocessing import StandardScaler scaler = StandardScaler() # aca creamos al escalador vacio scaler.fit(x) # aca lo hacemos calcular la media y el desvio estandar y lo guarda en scaler x_scaled = scaler.transform(x) # aca transformamos a x en estandarizado
3683aee345379d17b9e92cc9ce48cdfbe426ef72
gmortuza/ctci-python
/3_stack_heaps/2_stack_min.py
1,978
3.75
4
class MultiStack: def __init__(self, stack_capacity): self.num_stack = 3 self.stack_capacity = stack_capacity self.array = [None] * (stack_capacity * self.num_stack) # This will contain the minimum value in each stage self.min = [None] * (stack_capacity * self.num_stack) self.stack_sizes = [0] * self.num_stack def push(self, stack_number, value): """ Push value in the stack :param stack_number: put value in this stack number :param value: Value to be pushed :return: """ if self.stack_sizes[stack_number] > self.stack_capacity: raise Exception("Stack full") self.stack_sizes[stack_number] += 1 self.array[self.__get_stack_offset(stack_number)] = value self.min[self.__get_stack_offset(stack_number)] = self.__get_min(stack_number, value) def __get_min(self, stack_number, value): if self.stack_sizes[stack_number] <= 1: return value return min(self.min[self.__get_stack_offset(stack_number) - 1], value) def __get_stack_offset(self, stack_number): return (stack_number * self.stack_capacity) + self.stack_sizes[stack_number] - 1 def pop(self, stack_number): """ :return: """ value = self.array[(stack_number * self.stack_capacity) + self.stack_sizes[stack_number] - 1] self.array[self.__get_stack_offset(stack_number)] = None self.min[self.__get_stack_offset(stack_number)] = None self.stack_sizes[stack_number] -= 1 return value def get_stack_min(self, stack_number): return self.min[self.__get_stack_offset(stack_number)] if __name__ == '__main__': stack = MultiStack(10) stack.push(0, 1) stack.push(1, 5) stack.push(2, 4) stack.push(0, -1) stack.push(0, 10) stack.push(0, 100) stack.push(0, -100) stack.pop(0) print(stack.get_stack_min(0)) print(stack.array)
92b01d85b006110d07737b33f45d2cdaa51d5dc0
jgingh7/Problem-Solving-Python
/Inter/DistributeCoinsInBinaryTree.py
1,005
3.890625
4
# https://leetcode.com/problems/distribute-coins-in-binary-tree/ # Time: O(number of nodes) # Space: O(height of tree) # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def distributeCoins(self, root: TreeNode) -> int: self.ans = 0 # need to declare this instance variable # so that all recusions can access this variable def dfs(node): # dfs returns the excess amount of coin, which is the same as how many coin shifts will happen # excess can be -1 in the sense that the node is 0 and have -1 access amount if not node: return 0 L, R = dfs(node.left), dfs(node.right) self.ans += abs(L) + abs(R) #abs because it is to and from node's children return node.val + L + R - 1 dfs(root) return self.ans
74c968c274dae7b0e10e81866c965d72be4bbdd2
Vincent0700/leetcode-solution
/s0009-palindrome-number.py
316
3.5625
4
class Solution(object): def isPalindrome(self, x): """ :type x: int :rtype: bool """ if(x < 0): return False tmp = list(str(x)) tmp.reverse() rx = int("".join(tmp)) return x == rx print Solution().isPalindrome(123321)
b6095d3295b698da1b007a30210e90f5c37ad7da
bachdinhthang59ktdh/b-i-t-p-ktlt-tr-n-l-p
/bài tập trên lớp chương4. bài 1.py
90
3.59375
4
my_string=str(input('nhap chuoi')) print(len(my_string)) print(str.upper(my_string))
e5ec5268bfa9b50a5c8ba429e18a41699c14ef27
TMcMac/holbertonschool-higher_level_programming
/0x0A-python-inheritance/2-is_same_class.py
334
3.546875
4
#!/usr/bin/python3 """Docstring, not sure what this is for""" def is_same_class(obj, a_class): """ Returns True if obj is exactly an instance of class parameters - obj: an object to be compared a_class: a class """ if (type(obj) == a_class): return(True) else: return(False)
8a90546eeb49294dc6ad9cce9136b1802bf7dc4a
Mrga637/mohammadReza-
/.github/adad begire mmiangin ngire bde.py
272
3.78125
4
list1 = [] number = 0 sum = 0 while number >= 0: number = int(input('add begoo')) if number>=0 : list1.append(number) a = int(len(list1)) while a > 0 : print(list1[a-1]) sum = sum +list1[a-1] a-=1 sum = sum / len(list1) print(sum) print(list1)
5aaa1a509a166fafd467c4857e952cfee8c7af85
piggy1024/python-learn
/python-course/day-05/code/05.关闭文件.py
571
3.921875
4
# 05.关闭文件.py # 打开文件的标准格式如下: file_name = r'../demo.txt' try: with open(file_name) as file_obj: print(file_obj) except FileNotFoundError as e: print(f'{file_name} not exit!') else: pass finally: pass file_name = r'../demo.txt' file_obj = open(file_name) content = file_obj.read() print(content) # close()关闭文件 file_obj.close() # with ... as语句 with open(file_name) as file_obj : # 在with语句中可以直接使用file_obj # with 结束 文件自动结束 print(file_obj.read())
e57fc7d23fe6d2cd3b0d2d2f14d79b53a2c245be
cxm17/python_crash_course
/do_it_yourself/chapter_5/5_5.py
261
3.8125
4
alien_color = "red" if "green" == alien_color: print("green: alien_color is " + alien_color) elif "yellow" == alien_color: print("yellow if: alien_color is " + alien_color) elif "red" == alien_color: print("red if: alien_color is " + alien_color)
2a42e12ae42087d991bed0ba4bea44b29470651f
rram/aoc
/2020/day2p1.py
713
3.515625
4
#!/usr/bin/python3 import logging def run(data): good = 0 for line in data: nums, let, passwd = line.split() low, _, high = nums.partition("-") low = int(low) high = int(high) assert let[1] == ":" let = let[0] if low <= passwd.count(let) <= high: logging.debug("%s has %i %s's and is GOOD", passwd, passwd.count(let), let) good += 1 else: logging.debug("%s has %i %s's and is BAD", passwd, passwd.count(let), let) return good if __name__ == "__main__": logging.basicConfig(level=logging.DEBUG) data = None with open("day2.txt") as f: data = f.readlines() print(run(data))
e6b1895e605e89478edaaefb369d86e9077c8804
eagle7777/modules
/LinearStructures/Stack.py
2,001
3.90625
4
#!/usr/bin/env python # coding: utf-8 # Author: Valentyn Kofanov (knu) # Created: 12/1/18 class NodeForStack: """ Вспомогательный класс узел стека """ def __init__(self, item=None): self.item = item # нагрузка (значение) self.next = None # ссылка на следующий элемент class Stack: """ Стек """ def __init__(self): """ конструктор """ self.top_node = None # верхний элемент self.size = 0 # кол-во элементов в стеке (размер стека) def empty(self): """ проверка на пустоту :return: True - если стек пуст / False в противном случае """ return self.top_node is None def push(self, item): """ Добавить элемент в стек :param item: элемент :return: """ self.size += 1 new_node = NodeForStack(item) new_node.next = self.top_node self.top_node = new_node def pop(self): """ Извлечь элемент из стека (забирается верхний элемент) :return: искомый элемент """ assert not self.empty(), 'Stack is empty!' current_top = self.top_node res_item = current_top.item self.top_node = self.top_node.next del current_top self.size -= 1 return res_item def top(self): """ возвращает верхний элемент, но не извлекает его :return: верхинй элемент """ assert not self.empty(), 'Stack is empty!' return self.top_node.item def __len__(self): """ :return: длина (размер стека) """ return self.size
afbab6ae04fe93ba3fbe448776106fae739f85df
SmallPotY/leetcode_Python
/最后一个单词的长度.py
320
3.84375
4
""" 给定一个字符串, 包含大小写字母、空格' ',请返回其最后一个单词的长度。 如果不存在最后一个单词,请返回 0 。 样例 给定 s = "Hello World",返回 5。 """ def lengthOfLastWord(s): # write your code here s = s.strip() s = s.split(' ') return len(s[-1])
08363984bdf50b238be14baf2daf622ffe5893ec
Carlosterre/Aeropython
/Clase_002b-Sintaxis_basica_II_librerias.py
3,302
3.796875
4
import numpy as np # Importar la libreria NumPy data = np.loadtxt(fname='inflammation-01.csv', delimiter=',') # Llamada a la funcion 'loadtxt' que pertenece a numpy print(data) # Tipo de data 'type(data)': numpy.ndarray # Tipo de valores de data 'data.dtype': dtype('float64') # Numero de elementos 'data.size': 2400 # Numero de elementos por dimension 'data.shape': (60, 40) print('first value in data:', data[0, 0]) # La indexacion comienza en 0 print('middle value in data:', data[30, 20]) print(data[0:4, 0:10]) # Primeros diez dias para los primeros cuatro pacientes print(data[:4, :10]) # No hace falta poner el valor inicial si es 0 print(data[5:10, 0:10]) # Acceder a cualquier otra seccion print(data[0:10:3, 0:10:2]) # Saltar elementos (ultimo no incluido) small = data[:3, 36:] # Tomando una seccion mas pequeña small # 'data.mean()' para obtener la inflamacion media print('maximum inflammation:', data.max()) # Maximo: 20.0 print('minimum inflammation:', data.min()) # Minimo: 0.0 print('standard deviation:', data.std()) # Desviacion standard patient_0 = data[0, :] # Seleccionando el primer paciente print('maximum inflammation for patient 0:', patient_0.max()) # Calculando su maximo # 'data.mean(axis=1)' media a lo largo de las filas. 'axis=0' para calcular a lo largo de las columnas # 'data.mean(axis=1).shape' para ver el tamaño del array: (60,) element = 'oxygen' # String # 'element[:4]' slicing del string: 'oxyg' # 'element[4:]': 'en' # 'element[:]': 'oxygen' # 'element[-1]': 'n' # 'element[-2]': 'e' # 'element[1:-1]': 'xyge' # 'element[3:3]': '' cadena vacia # 'data[3:3, 4:4]': array([], shape=(0, 0), dtype=float64) # 'data[3:3, :]': array([], shape=(0, 40), dtype=float64) import matplotlib.pyplot as plt # Modulo PyPlot de matplotlib plt.matshow(data) # Las regiones azules corresponden a valores bajos de inflamacion, mientras que las amarillas indican valores mas altos. Se puede ver como a lo largo de los cuarenta dias la inflamacion aumenta y luego disminuye en todos los pacientes plt.show() ave_inflammation = data.mean(axis=0) # Inflamacion media de todos los pacientes para cada día plt.plot(ave_inflammation) plt.show() print('maximum inflammation per day') # Inflamacion maxima por dia plt.plot(data.max(axis=0)) plt.show() print('minimum inflammation per day') # Inflamacion minima por dia plt.plot(data.min(axis=0))
38aca96376789fddcd44fd68dce06ff8d3586c45
puneeth1999/InterviewPreparation
/AlgoExpert/arrays/5. motonicArray/secondApproach.py
772
3.953125
4
#Very much prone to error. Especially if arra[0] and array[1] are equal. #Time complexity = O(n) | Space complexity = O(1) def monotonicArray(array): if array[1] > array[0]: init_direction = 'up' elif array[1] < array[0]: init_direction = 'down' else: init_direction = 'flat' for i in range(2, len(array) - 1): j = i + 1 if array[j] > array[i]: direction = 'up' elif array[j] < array[i]: direction = 'down' else: direction = 'flat' if (direction == init_direction): pass elif(direction == 'flat'): pass else: return False return True print(monotonicArray([-1,-5,-10,-1100,-1100, -1101,-1102,-9001]))
feaa8fed8f08d9eef60a4ebe85fe509b74e10097
Ateeq1234/Symposium
/project3.py
309
4.0625
4
print("Project-3") print("_"*15) email = input("Enter your email address\n").strip() user = email[:email.index("@")] # print(user) domain = email[email.index("@")+1:email.index(".")] # print(domain.capitalize()," is the domain name") print(f"{user} is the username and {domain}.com is the domain name ")
07358bd51fa55e9d03c9c60f789cb48787cc307e
Sparky-Chad/Python-Programming-2021
/Labs/5_Lab/lab05-2019.py
4,369
4.15625
4
## Lab 5: Required Questions - Dictionaries Questions ## # RQ1 def merge(dict1, dict2): """Merges two Dictionaries. Returns a new dictionary that combines both. You may assume all keys are unique. >>> new = merge({1: 'one', 3:'three', 5:'five'}, {2: 'two', 4: 'four'}) >>> new == {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'} True """ "*** YOUR CODE HERE ***" for i in dict2: dict1[i] = dict2[i] return dict1 # RQ2 def counter(message): """ Returns a dictionary of each word in message mapped to the number of times it appears in the input string. >>> x = counter('to be or not to be') >>> x['to'] 2 >>> x['be'] 2 >>> x['not'] 1 >>> y = counter('run forrest run') >>> y['run'] 2 >>> y['forrest'] 1 """ "*** YOUR CODE HERE ***" out = {} for i in message.split(): if i not in out: out[i] = 1 else: out[i] += 1 return out # RQ3 def replace_all(d, x, y): """ >>> d = {'foo': 2, 'bar': 3, 'garply': 3, 'xyzzy': 99} >>> replace_all(d, 3, 'poof') >>> d == {'foo': 2, 'bar': 'poof', 'garply': 'poof', 'xyzzy': 99} True """ "*** YOUR CODE HERE ***" # Was looking into one line for loops and stuff, so its a mess r = {i: d[i] if d[i] != x else y for i in d } return r # RQ4 def sumdicts(lst): """ Takes a list of dictionaries and returns a single dictionary which contains all the keys value pairs. And if the same key appears in more than one dictionary, then the sum of values in list of dictionaries is returned as the value for that key >>> d = sumdicts ([{'a': 5, 'b': 10, 'c': 90, 'd': 19}, {'a': 45, 'b': 78}, {'a': 90, 'c': 10}] ) >>> d == {'b': 88, 'c': 100, 'a': 140, 'd': 19} True """ "*** YOUR CODE HERE ***" sumout = {} # Run through list of dicts for i in lst: # Run through each list for j in i: # Add to sum if j not in sumout: sumout[j] = i[j] else: sumout[j] += i[j] return sumout #RQ5 def middle_tweet(word, table): """ Calls the function random_tweet() 5 times (see Interactive Worksheet) and returns the one string that is of length right in middle of the 5. Returns a string that is a random sentence of average length starting with word, and choosing successors from table. """ "*** YOUR CODE HERE ***" def construct_tweet(word, table): """Returns a string that is a random sentence starting with word, and choosing successors from table. """ import random result = ' ' while word not in ['.', '!', '?']: result += word + ' ' word = random.choice(table[word]) return result + word from math import ceil current_list = [] # Call construct tweet 5 times into a list # So that it then has 5 sentances of the length of for i in range(0,5): current_list.append(construct_tweet(word, table)) # Sort by length for i in range(0, len(current_list)): for j in range(0, len(current_list)): # Now begin to sort the lests by length if len(current_list[i]) > len(current_list[j]): temp = current_list[i] current_list[i] = current_list[j] current_list[j] = temp # The return the central most one, this serves as the median(which is an average type) of the # list lengths return current_list[ceil(len(current_list)/2)] import doctest if __name__ == "__main__": doctest.testmod(verbose=True) # Inputing some of the code from the lab def shakespeare_tokens(path='shakespeare.txt', url='http://composingprograms.com/shakespeare.txt'): #"""Return the words of Shakespeare's plays as a list.""" import os from urllib.request import urlopen if os.path.exists(path): return open('shakespeare.txt', encoding='ascii').read().split() else: shakespeare = urlopen(url) return shakespeare.read().decode(encoding='ascii').split() def build_successors_table(tokens): table = {} prev = '.' for word in tokens: if prev not in table: table[prev] = [] table[prev] += [word] prev = word return table
149c934ed3318fbd3569eebf6ad843d1c54f1610
npalombo/emc
/fibonacci/__init__.py
488
3.5
4
__author__ = 'nick' class Memoize: def __init__(self, fn): self.fn = fn self.memo = {} def __call__(self, arg): if arg not in self.memo: self.memo[arg] = self.fn(arg) return self.memo[arg] @Memoize def fib(n): if n > 0: a, b = 0, 1 seq = [a] for i in range(n - 1): a, b = b, a + b seq.append(a) return seq else: raise Exception('Argument must be at least 1')
a462bbdcb295afc7bfdb0992548414aaa584d02a
ErisonSandro/Exercicios-Python
/exercicios/ex029-Radar eletronico.py
297
3.71875
4
vel = float(input('Qual é a velocidade atual do carro? ')) multa = float(vel - 80) * 7 print('') if vel > 80: print('MULTADO! você excedeu o limite permitido que é de 80Km/h') print('Voce deve pagar uma multa de R${:.2f}'.format(multa)) print('Tenha um bom dia! Dirija com segurança')
e1525e5e0946f6d2aea19739640f0e673330dd89
KvnEYoung/Internet-and-Cloud
/hw4/app.py
1,251
3.671875
4
""" This is a Movie Review flask application. """ from flask import Flask, redirect, request, url_for, render_template import MRModels app = Flask(__name__) model = MRModels.get_model() """ Function decorator using app.route ( '/', index() ). """ @app.route('/') @app.route('/index.html') def index(): """ Main movie review webpage. """ return render_template('index.html') @app.route('/reviews') def reviews(): """ Displays all the movie reviews within a webpage. """ reviews = [dict(movie=row[0], year=row[1], genre=row[2], rating=row[3], review=row[4], reviewer=row[5]) for row in model.select()] return render_template('reviews.html', reviews=reviews) @app.route('/newreview', methods=['GET','POST']) def newreview(): """ Webpage form to add a new movie review. POST requests will process the form and return to the reviews page.""" if request.method == 'POST': model.insert(request.form['movie'], request.form['year'], request.form['genre'], request.form['rating'], request.form['review'], request.form['reviewer']) return redirect(url_for('reviews')) else: return render_template('newreview.html') if __name__ == '__main__': app.run(host='0.0.0.0', port=8000, debug=True)
3daf89162dc05e2ebbf430cdfd36e98ddd9e91c0
LEXBROS/Stepik_PyCharm
/kam_nozn_spok.py
591
3.5625
4
def game_round(timur, ruslan): my_dict = {'камень': ['ящерица', 'ножницы'], 'ножницы': ['ящерица', 'бумага'], 'бумага': ['Спок', 'камень'], 'ящерица': ['Спок', 'бумага'], 'Спок': ['камень', 'ножницы'] } if timur in my_dict.keys() and ruslan in my_dict[timur]: return 'Тимур' if timur == ruslan: return 'ничья' else: return 'Руслан' print(game_round(input(), input()))
123f2670ce38f4e9f9d66d1e316cccb7b1971aa6
orangecig/mit600
/pset_10_memoization/ps10_new.py
13,085
3.5
4
# 6.00 Problem Set 10 Spring 2012 # # Name: # Collaborators: # Time spent: import pylab import random import time ''' Begin helper code ''' class EventTime(object): """ Represents the time for a weekly recurring event. """ def __init__(self, timeStr): """ Initialize a EventTime instance from the string. The input string needs to be of the form <dayOfWeek><times>, where dayOfWeek is a string that represents the days of the week the event occurs, with each letter being either M, T, W, R, F (e.g., MWF), and times is a two character digit from 00 to 23 that represents the hour of the day the event happens (e.g., 09). """ assert isinstance(timeStr, str) and len(timeStr) <= 7 and \ timeStr[-1].isdigit() and timeStr[-2].isdigit() self.time = int(timeStr[-2:]) self.daysOfWeek = timeStr[:-2] assert self.time >= 0 and self.time <= 23 assert False not in [c in 'MTWRF' for c in self.daysOfWeek] def getTime(self): """ Gets the hour that the event happens. Returns: an integer from 0 to 23 """ return self.time def getDaysOfWeek(self): """ Gets the days of the week that the event happens. Returns: a string made up with letters MTWRF """ return self.daysOfWeek def conflict(self, other): """ Checks if the passed in EventTime instance other is in conflict with the current instance. Two EventTime instances are in conflict if any occurence of one of the EventTime coincidences with some occurence of the other EventTime instance. returns: True if the two EventTime instances conflict with each other, False otherwise. """ if not isinstance(other, EventTime): return False dayConflict = True in [d in other.daysOfWeek for d in self.daysOfWeek] return dayConflict and other.time == self.time def __str__(self): return self.daysOfWeek + ' ' + str(self.time) def __cmp__(self, other): if not isinstance(other, EventTime): raise NotImplementedError if self.time == other.time: return cmp(self.daysOfWeek, other.daysOfWeek) else: # the times are not equal return cmp(self.time, other.time) def __hash__(self): return hash(self.time) + hash(self.daysOfWeek) def printSubjects(subjects, sortOutput=True): """ Pretty-prints a list of Subject instances using the __str__ method of the Subject class. Parameters: subjects: a list of Subject instances to be printed sortOutput: boolean that indicates whether the output should be sorted according to the lexicographic order of the subject names """ if sortOutput: subjectCmp = lambda s1, s2: cmp(s1.getName(), s2.getName()) sortedSubjects = sorted(subjects, cmp=subjectCmp) else: sortedSubjects = subjects print 'Course\tValue\tWork\tTime\n======\t=====\t====\t====\n' totalValue, totalWork = 0, 0 for subject in sortedSubjects: print subject totalValue += subject.getValue() totalWork += subject.getWork() print '\nNumber of subjects: %d\nTotal value: %d\nTotal work: %d\n' % \ (len(subjects), totalValue, totalWork) ''' End Helper Code ''' class Subject(object): """ A class that represents a subject. """ def __init__(self, name, value, work, time): """ Initializes a Subject instance. Parameters: name: a string that represents the name of the subject value: an integer that represents the value for the subject work: an integer that represents the amount of work for the subject time: an EventTime instance that represents when the subject meets """ # TODO raise NotImplementedError def getName(self): """ Gets the name of the subject. Returns: a string that represents the name of the subject """ # TODO raise NotImplementedError def getValue(self): """ Gets the value of the subject. Returns: an integer that represents the value of the subject """ # TODO raise NotImplementedError def getWork(self): """ Gets the amount of work for the subject. Returns: an integer that represents the work amount of the subject """ # TODO raise NotImplementedError def getTime(self): """ Gets the hours and days of the week that the subject meets. Returns: an EventTime instance that represents when the subject meets """ # TODO raise NotImplementedError def conflict(self, subjectList): """ Checks whether any subjects in the passed in list conflicts in time with the current subject instance. Parameters: subjectList: a list of Subject instances to check conflicts against Returns: True if current instance conflicts with any subjects in the list, and False otherwise """ # TODO raise NotImplementedError def __str__(self): """ Generates the string representation of the Subject class. Returns: a string of the form <subject name>\t<value>\t<work>\t<times of the day> where \t is the tab character, and <times of the day> is the string representation when the subject meets """ # TODO raise NotImplementedError def loadSubjects(filename): """ Loads in the subjects contained in the given file. Assumes each line of the file is of the form "<subject name>,<value>,<work>,<times of the week>" where each field is separated by a comma. Parameter: filename: name of the data file as a string Returns: a list of Subject instances, each representing one line from the data file """ # TODO raise NotImplementedError class SubjectAdvisor(object): """ An abstract class that represents all subject advisors. """ def pickSubjects(self, subjects, maxWork): """ Pick a set of subjects from the subjects list such that the value of the picked set is maximized, with the constraint that the total amount of work of the picked set needs to be <= maxWork. To be implemented by subclasses. Parameters: subjects: list of Subject instances to choose from, each subject can be chosen at most once maxWork: maximum amount of work the student is willing to take on Returns: a list of Subject instances that are chosen to take """ raise NotImplementedError('Should not call SubjectAdvisor.pickSubjects!') def getName(self): """ Gets the name of the advisor. Useful for generating plot legends. To be implemented by subclasses. Returns: A string that represents the name of this advisor """ raise NotImplementedError('Should not call SubjectAdvisor.getName!') def cmpValue(subject1, subject2): """ A comparator function for two subjects based on their values. To be used by the GreedyAdvisor class. Paramters: subject1, subject2: two Subject instances Returns: -1 if subject1 has more value than subject2, 1 if subject1 has less value than subject2, 0 otherwise """ # TODO raise NotImplementedError def cmpWork(subject1, subject2): """ A comparator function for two subjects based on their amount of work. To be used by the GreedyAdvisor class. Paramters: subject1, subject2: two Subject instances Returns: -1 if subject1 has more less than subject2, 1 if subject1 has more work than subject2, 0 otherwise """ # TODO raise NotImplementedError def cmpRatio(subject1, subject2): """ A comparator function for two subjects based on their value to work ratio. To be used by the GreedyAdvisor class. Paramters: subject1, subject2: two Subject instances Returns: -1 if subject1 has higher value to work ratio than subject2, 1 if subject1 has lower value to work ratio than subject1, 0 otherwise """ # TODO raise NotImplementedError class GreedyAdvisor(SubjectAdvisor): """ An advisor that picks subjects based on a greedy algorithm. """ def __init__(self, comparator): """ Initializes a GreedyAdvisor instance. Parameter: comparator: a comparator function, either one of cmpValue, cmpWork, or cmpRatio """ # TODO raise NotImplementedError def pickSubjects(self, subjects, maxWork): """ Picks subjects to take from the subjects list using a greedy algorithm, based on the comparator function that is passed in during initialization. Parameters: subjects: list of Subject instances to choose from, each subject can be chosen at most once maxWork: maximum amount of work the student is willing to take on Returns: a list of Subject instances that are chosen to take """ # TODO raise NotImplementedError def getName(self): """ Gets the name of the advisor. Returns: A string that represents the name of this advisor """ return "Greedy" class BruteForceAdvisor(SubjectAdvisor): def __init__(self): """ Initializes a BruteForceAdvisor instance. """ # TODO raise NotImplementedError def pickSubjects(self, subjects, maxWork): """ Pick subjects to take using brute force. Use recursive backtracking while exploring the list of subjects in order to cut down the number of paths to explore, rather than exhaustive enumeration that evaluates every possible list of subjects from the power set. Parameters: subjects: list of Subject instances to choose from, each subject can be chosen at most once maxWork: maximum amount of work the student is willing to take on Returns: a list of Subject instances that are chosen to take """ # TODO raise NotImplementedError def getName(self): """ Gets the name of the advisor. Returns: A string that represents the name of this advisor """ return "Brute Force" class MemoizingAdvisor(SubjectAdvisor): def __init__(self): """ Initializes a MemoizingAdvisor instance. """ # TODO raise NotImplementedError def pickSubjects(self, subjects, maxWork): """ Pick subjects to take using memoization. Similar to BruteForceAdvisor except that the intermediate results are saved in order to avoid re-computation of previously traversed subject lists. Parameters: subjects: list of Subject instances to choose from, each subject can be chosen at most once maxWork: maximum amount of work the student is willing to take on Returns: a list of Subject instances that are chosen to take """ # TODO raise NotImplementedError def getName(self): """ Gets the name of the advisor. Returns: A string that represents the name of this advisor """ return "Memoizing" def measureTimes(filename, maxWork, subjectSizes, numRuns): """ Compare the time taken to pick subjects for each of the advisors subject to maxWork constraint. Run different trials using different number of subjects as given in subjectSizes, using the subjects as loaded from filename. Choose a random subject of subjects for each trial. For instance, if subjectSizes is the list [10, 20, 30], then you should first select 10 random subjects from the loaded subjects, then run them through the three advisors using maxWork for numRuns times, measuring the time taken for each run, then average over the numRuns runs. After that, pick another set of 20 random subjects from the loaded subjects, and run them through the advisors, etc. Produce a plot afterwards with the x-axis showing number of subjects used, and y-axis showing time. Be sure you label your plots. After plotting the results, answer this question: What trend do you observe among the three advisors? How does the time taken to pick subjects grow as the number of subject used increases? Why do you think that is the case? Include the answers to these questions in your writeup. """ # TODO raise NotImplementedError
def9e682572dc3da3a030f3386050eae5e3cdb03
jhuffaker13/cse210-student-solo-checkpoints
/05-hide-and-seek/hide_and_seek/game/hider.py
649
3.71875
4
import random # TODO: Define the Hider class here class Hider: def __init__ (self): self.location = random.randint(1,10) self.distance = [0,0] def get_hint(self): hint = "Good luck finding me bozo!" if self.distance[-1] == 0: hint = "\nUh, occupied?" elif self.distance[-1] > self.distance[-2]: hint = "\nBit chilly init?" elif self.distance [-1] < self.distance[-2]: hint = "Is it just me, or is it really toasty?" return hint def watch(self, location): distance = abs(self.location-location) self.distance.append(distance)
936854e309e037e704fdb67685d01b98a57eb99b
IlfatGub/Coursera-Phyton
/week4/Сложение без сложения.py
172
3.78125
4
# Сложение без сложения def summa(a, b): if a == 0: return b return summa(a-1, b+1) a = int(input()) b = int(input()) print(summa(a, b))
d8367ef1c527f4b9f8c68c5d3898aeeb84d50601
TiMusBhardwaj/pythonExample
/python-and-mongo-master/sorting/BubbleSort.py
391
4.15625
4
# Function to do bubble sort def bubbleSort(arr): # Traverse through 1 to len(arr) for i in range(0, len(arr)-1): for j in range (0, len(arr)-i-1): if(arr[j]>arr[j+1]): arr[j],arr[j+1]=arr[j+1],arr[j] print(arr) # Driver code to test above arr = [12, 11, 10, 6, 5] bubbleSort(arr) for i in range(len(arr)): print("% d" % arr[i])
b3f006ea7f7a7f74631ae24e88a1248433b1644a
VSkapenko/python_home_tasks
/Найди и Замени!.py
516
3.703125
4
import random arra = [random.randint(0, 88) for i in range(10)] print(arra) z = (int(input("Введите порядковый номер числа"))) arra[z] = z print(arra) # q = int(input("Хотите попробовать еще раз? ДА - нажмите 5." "Для окончания игры, нажмите 0")) # while (q > 5): # arra = [random.randint(0, 88) for i in range(10)] # print(arra) # z = (int(input("Введите порядковый номер числа"))) # arra[z] =
94df080463821f9e62bd452813591c39a4fc5fa0
Ashersam/tasks
/Task1/array2.py
249
4
4
array = ["test", "ok","how","why","hello"] print (array) newword = str(input("Enter that new word to add to the last postion this array > ")) print ("New array after inserting word to fist position") array.insert(len(array), newword) print(array)
6dd36fb253ed73f381095bd750e21c9931ab3833
vincentt117/coding_challenge
/lc_valid_parantheses.py
570
3.6875
4
# https://leetcode.com/problems/valid-parentheses/description/ def isValid(self, s): """ :type s: str :rtype: bool """ if not s: return True checkStack = [] for i in s: if i == "(": checkStack.append(")") elif i == "[": checkStack.append("]") elif i == "{": checkStack.append("}") else: if not checkStack or checkStack.pop() != i: return False return not checkStack # Faster than 99% of accepted submissions
96823cfb298bda44950d12141b4b82ad0ae662ec
nazzang49/machine-learning-practice
/basic/math/ex4.py
961
3.921875
4
import numpy as np matrix = np.array([[1, 2, 3], [5, 4, 6], [7, 10, 9], [7, 10, 9]]) # reshape reshaped_matrix1 = matrix.reshape(2, 6) print(reshaped_matrix1) print(reshaped_matrix1.shape) # -1 => automatically at the most reshaped_matrix2 = matrix.reshape(-1) print(reshaped_matrix2) print(reshaped_matrix2.shape) # transpose print(matrix.T) # col vector => row vector print(np.array([ [1], [2], [3], [4], [5]]).T) matrix = np.array([[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10], [11, 12]]]) # 2, 3, 2 print(matrix.shape) # 2, 2, 3 print(matrix.transpose((0, 2, 1)).shape) # flatten => multi dimensions to 1-dim flatten = matrix.flatten() reshape = matrix.reshape(-1) print(flatten) print(reshape) # flatten => totally new array matrix[0][1][1] = 300 print(flatten) print(reshape)
d7402c8acdbabde7edc86ff03efce5f9779cf9f7
atrn0/atcoder
/ABC/101/D.py
90
3.765625
4
import math for i in range(int(input())): print(int(str(i%9+1)+'9'*math.floor(i/9)))
24a1d6e3dedb45d2a812aae6612a642d25296d91
gaolichuang/book-algorithm-datastruct
/solution/greedy/candy.py
892
3.625
4
''' Candy There are N children standing in a line. Each child is assigned a rating value. You are giving candies to these children subjected to the following requirements: Each child must have at least one candy. Children with a higher rating get more candies than their neighbors. What is the minimum candies you must give? ''' class Solution(object): def candy(self, ratings): """ :type ratings: List[int] :rtype: int """ if not ratings: return 0 r = ratings lr = len(ratings) d = [1]*lr i = 1 while i < lr: if r[i] > r[i-1]: d[i] = d[i-1]+1 if d[i] < d[i-1]+1 else d[i] i += 1 sumc = d[lr-1] i = lr - 2 while i >= 0: if r[i+1] < r[i]: d[i] = d[i+1]+1 if d[i] < d[i+1]+1 else d[i] sumc += d[i] i -= 1 return sumc s = Solution() print s.candy([4,2,3,4,1]) #print s.candy([1,2,4,4,3])
e3a09ff23bbd3e1445afefc67754351ba148d8b8
habistar/100_Days_of_Code_Challange
/Day_02/exercise_04.py
464
3.78125
4
# 🚨 Don't change the code below 👇 age = input("What is your current age?") # 🚨 Don't change the code above 👆 #Write your code below this line 👇 #You have 12410 days, 1768 weeks, and 408 months left. age = int(age) left_years = 90 - age left_weeks = left_years * 52 left_months = left_years * 12 left_days = left_years * 365 print("You have " + str(left_days) + " days," + str(left_weeks) + " weeks, and " + str(left_months) + " months left.")
10b08eb79024ee800838321f010eb607ff21091f
JevgeniPillau/Algorythms
/lesson _02/lesson_02_task04.py
421
3.8125
4
''' 4. Найти сумму n элементов следующего ряда чисел: 1 -0.5 0.25 -0.125 ...Количество элементов (n) вводится с клавиатуры. ''' num = int(input('type in number of elements in range (1 -0.5 0.25 -0.125 ...): ')) first_element_in_range = 1 sum = 0 for i in range(num): sum += first_element_in_range first_element_in_range /= -2 print(sum)
07079b11afec3ed2e814412e38a037c5d8ced17b
rossvalera/inf1340_2015_asst2
/test_exercise1.py
943
3.578125
4
#!/usr/bin/env python """ Assignment 2, Exercise 1, INF1340, Fall, 2015. Pig Latin Test module for exercise1.py """ __author__ = 'Sinisa Savic', 'Marcos Armstrong', 'Susan Sim' __email__ = "ses@drsusansim.org" __copyright__ = "2015 Susan Sim" __license__ = "MIT License" from exercise1 import pig_latinify def test_basic(): """ # Basic test cases from assignment hand out """ assert pig_latinify("dog") == "ogday" assert pig_latinify("scratch") == "atchscray" assert pig_latinify("is") == "isyay" assert pig_latinify("apple") == "appleyay" # Test cases to check various correct and incorrect inputs added assert pig_latinify("h4h4h") == "try again" assert pig_latinify("13131231") == "try again" assert pig_latinify("street") == "eetstray" assert pig_latinify("YELLOW") == "ellowyay" assert pig_latinify("") == "try again" assert pig_latinify("$%^&*") == "try again" assert pig_latinify("WhY") == "whyay"
1e61d64ade0d530f70092bbadb4d7c9fd4d58fbc
hibellm/speech
/find_files.py
969
3.765625
4
#!/usr/bin/python3 # -*- encoding: utf-8 -*- """ CREATED : AUTHOR : DESCRIPTION: """ import os import fnmatch def find_filelist(path=None, pattern='*', walk=False): '''Find files matching the pattern in the given folder :param path: the path to start searching in (DEFAULT=None) :param pattern: the pattern to match on (DEFAULT='*') :param walk: look in sub-folders of the src_loc(DEFAULT=False) :return: {list} of filenames and path ''' tresult = [] for root, dirs, files in os.walk(path): for name in files: if fnmatch.fnmatch(name, f'{pattern}'): if walk is False: if root == path: tresult.append(os.path.join(root, name)) else: pass elif walk is True: tresult.append(os.path.join(root, name)) else: pass return tresult
f138ca811a1244070ad1de230aff297abcdb91ea
OmarKhanGithub/Data-Science
/Python/Datacamp/0.0_Intro to Python for Data Science/2.05_List-methods.py
935
4.125
4
# 2.05 # List Methods #Strings are not the only Python types that have methods associated with them. Lists, floats, integers and booleans are also types that come packaged with a bunch of useful methods. In this exercise, you'll be experimenting with: #index(), to get the index of the first element of a list that matches its input and #count(), to get the number of times an element appears in a list. #You'll be working on the list with the area of different parts of a house: areas. #INSTRUCTIONS #100 XP #Use the index() method to get the index of the element in areas that is equal to 20.0. Print out this index. #Call count() on areas to find out how many times 9.50 appears in the list. Again, simply print out this number. # Create list areas areas = [11.25, 18.0, 20.0, 10.75, 9.50] # Print out the index of the element 20.0 print(areas.index(20.0)) # Print out how often 14.5 appears in areas print(areas.count(14.5))
7317a47569916893d516a1526ffdb2df4e3696f4
AngelSassin/Project-Euler
/42.py
961
3.90625
4
import string import math # the words file = open('words.txt','r') words = file.read().split(',') # returns the list of all the factors of the specified number def factors(a): x = [] for i in range(1,int(math.floor(math.sqrt(a)))+1): if a%i == 0: x.append(i) if (a/i != i): x.append(a/i) x.sort() return x # returns the value of the word def wordValue(word): value = 0 for char in word: value += string.ascii_uppercase.find(char)+1 return value # returns True if the specified word is a triangle word def isTriangleWord(word): value = wordValue(word) value *= 2 for factor in factors(value): if value/factor == factor+1 or value/factor == factor-1: return True return False # solves for the answer answer = 0 for word in words: if isTriangleWord(word): answer += 1 print answer
daa51cfac898beee50d09abed1419c7137a45948
aprilmao/Code-Practice
/mergeSort.py
556
4
4
def merge(left, right): mergeArr = [] i,j = 0, 0 while len(mergeArr) < len(left) + len(right): if left[i] < right[j]: mergeArr.append(left[i]) i += 1 else: mergeArr.append(right[j]) j += 1 if i == len(left) or j == len(right): mergeArr.extend(left[i:] or right[j:]) break return mergeArr def mergeSort(arr): if len(arr) <= 1: return arr mid = len(arr) / 2 left = mergeSort(arr[:mid]) right = mergeSort(arr[mid:]) return merge(left, right) arr = [4,2,6,3,8,5] print mergeSort(arr)
ebe0a4370b64e547c7b0f912f57815b26a5e798d
xyang57/LeetCode
/Leet3.py
2,516
4.15625
4
""" 3. Longest Substring Without Repeating Characters Given a string, find the length of the longest substring without repeating characters. Example 1: Input: "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. Example 2: Input: "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1. Example 3: Input: "pwwkew" Output: 3 Explanation: The answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring. """ """ Solution1: Find the maximum length of each substring starting with each index, and then return the longest """ def lengthOfLongestSubstring(s: 'str') -> 'int': length_maximum = 0 # Initiate the maximum length for i in range(len(s)): length = 0 # For each starting index, initiate the length to 0 substring = set() # with set we can search with constant time for j in range(i,len(s)): if s[j] not in substring: length += 1 substring.add(s[j]) length_maximum = max(length,length_maximum) else: break return length_maximum # Time complexity: O(n^2), space complexity: O(n) """ Solution2: if we find a duplicate value, then we can cut off the original string to replicated index +1, and continue to iterate through the string """ def lengthOfLongestSubstring(s: 'str') -> 'int': length_maximum = 0 sub = '' for i in range(len(s)): if s[i] not in sub: sub+=s[i] length_maximum = max(length_maximum, len(sub)) else: index = sub.index(s[i]) sub = sub[index+1:]+s[i] return length_maximum # Time complexity: O(n^2), because *in* is O(n); space complexity: O(n) """ Solution 3: similar as solution 2, but use dictionary to store the index of duplicates, and *in* with dictionary is O(1) """ def lengthOfLongestSubstring(self, s: 'str') -> 'int': length_maximum = 0 dic = {} i = 0 for j in range(len(s)): if s[j] not in dic: dic[s[j]] = j length_maximum = max(j-i+1,length_maximum) else: length_maximum = max(j-i,length_maximum) new_i = dic[s[j]] + 1 for k in range(i,dic[s[j]]+1): dic.pop(s[k]) i = new_i dic[s[j]] = j return length_maximum # Time complexity is O(n), space complexity: O(n)
fc9711d8acba4414bc270b0cecd36daada08f392
DhruvGoyal2001/Applied-Programming-EE2703
/Final/endsemester.py
4,061
3.890625
4
""" Program to Find the Magnetic field along z-axis for a given current value Submitted by: EE19B133 Puneet Sangal Written on: 23/05/2021, Sunday Usage example: python EE19B133_ENDSEM_EE2703.py Output: Gives different graph for current and magnetic field varying along z-axis. """ # importing the necessary files for plotting and math computing from pylab import * import numpy as np import matplotlib.pyplot as plt import numpy.linalg as linalg import math #defining the calc function which gives absolute value of R for a given point on loop and A vector def calc(l): R = r_vec - r_pr[l] #finding R vector R_mod = linalg.norm(R, axis=-1) #finding modulus of R vector R_mod = np.transpose(R_mod, axes=[1,0,2]) k = 0.1 F = (abs(np.cos(phi[l]))/R_mod)*(np.exp(k*R_mod*(-1j))) #Finding the terms of A A_x = F*dl[l,0] A_y = F*dl[l,1] return A_x,A_y #return A_x and A_y #Finding C and B for best fit def estimate(vec): G = np.array([[1, np.log(x)] for x in range(1,len(vec)+1)]) x = linalg.lstsq(G, np.log(vec), rcond = None)[0] #Using numpy.linalg.lstsq for estimate return x[0], x[1] # Main Function # Defining the points taken in 3-D plot x = np.linspace(-1,1,3) y = np.linspace(-1,1,3) z = np.linspace(1,1000,1000) # Defining the Value of magnetic permeability u0 = 4*np.pi*(1e-7) #Getting all points in 3-D Plane as 3-D array as [3,3,1000] X,Y,Z = np.meshgrid(x,y,z) #Defining Vector for each point in 3-D array r_vec = np.zeros((3,3,1000,3)) r_vec[:,:,:,0] = X r_vec[:,:,:,1] = Y r_vec[:,:,:,2] = Z #Defining Parameters of loop radius = 10 L = 100 #Defining value of angle of 100 points taken on loop phi = np.linspace(0,2*np.pi,L+1) phi = phi[:-1] #Defining vector for each point taken on the loop r_pr = np.c_[radius*np.cos(phi), radius*np.sin(phi), np.zeros(100)] #Defining the current element vector for each point on loop dl = np.c_[2*np.pi*(-np.sin(phi))/10, 2*np.pi*(np.cos(phi))/10, np.zeros(100)] #Defining the Current vector along current element vector I_vec = np.c_[4*np.pi*np.cos(phi)*(-np.sin(phi))/u0, 4*np.pi*(np.cos(phi))**2/u0, np.zeros(100)] # Plotting the Loop taken in X-Y plane along with current vector at each point dx, dy = np.gradient(I_vec) color = np.sqrt((abs(dx[:,0]+2)/2)*2 + (abs(dy[:,1]+2)/2)*2) #defining color for each vector plt.title("Vector plot of current flow on the loop") plt.quiver(r_pr[:,0], r_pr[:,1], I_vec[:,0], I_vec[:,1],color , label = "current vector",color = 'yellow') #doing quiver plot plt.legend(loc = "best") plt.grid(True) plt.ylabel(r'y$\rightarrow$') plt.xlabel(r'x$\rightarrow$') plt.show() A_x, A_y = 0,0 #Finding the values of A_x and A_y using Calc() function for l in range(100): A_x += calc(l)[0] A_y += calc(l)[1] #Finding Magnetic field along z-Axis B=(A_y[2,1,:]-A_x[1,2,:]-A_y[0,1,:]+A_x[1,0,:])/4 # Plotting The Magnetic Field on log-log scale plt.title(r'Log Log plot of the $|\vec{B_z}|$ vs z') plt.loglog(z,abs(B),'b', label = 'original') # Plotting log-log plot plt.legend(loc = "best") plt.grid(True) plt.ylabel(r'$|\vec{B_z}|\rightarrow$') plt.xlabel(r'z$\rightarrow$') plt.show() #Finding estimate of C and B for B = c*z^b c,b = estimate(B) print(np.exp(c),b) estimate = (np.exp(c))*(z**b) # Plotting The Magnetic Field on log-log scale along with estimate graph plt.title(r'Log Log plot of the $|\vec{B_z}|$ vs z') plt.loglog(z,abs(B),'b', label = 'original') #Plotting Log-log plot plt.loglog(z,estimate,'r',label = 'estimate') #Plotting Log-Log plot on an estimate plt.legend(loc = "best") plt.grid(True) plt.ylabel(r'$|\vec{B_z}|\rightarrow$') plt.xlabel(r'z$\rightarrow$') plt.show()
0e825814a7093e39dedcecfb51da318789695b10
tiagolok/PCAP
/Anagrams.py
278
4.09375
4
def anagrams(word1,word2): lst1 = sorted(list(word1.lower())) lst2 = sorted(list(word2.lower())) if lst1 == lst2: print("Anagrams") else: print("Not anagrams") # print(lst1,lst2) anagrams('Listen','Silent') anagrams('modern','norman')
4b5a592432ad72467f5089efc58db6a8f8a40b6d
jonathan-JIPSlok/Aprendendo_Pandas
/Groupby.py
533
3.59375
4
import pandas as pd import openpyxl df = pd.read_excel("Arquivo.xlsx", engine="openpyxl") print(f"Soma:\t {df.Idade.sum()}") #Faz a soma dos valores desta tabela print(f"Media:\t {df.Idade.mean()}") #Calcula a media dos valores print(f"Menor:\t {df.Idade.min()}") #pega o Menor valor da tabela print(f"Maior:\t {df.Idade.max()}") #Pega o maior valor da tabela print() print(df[["Nome", "Idade"]].groupby(["Idade"]).sum()) #Agrupa os valores exemplo, todos de 15 anos estarao juntos, todos de 30 anos estarao juntos etc... print()
f7a5071478d088533f29e717ebb62d514d6a6ff5
pranavgurditta/data-structures-MCA-201
/random_Access_pranav.py
1,631
3.890625
4
import random,pickle class Record: ''' Objective: To represent a record entity ''' count = 1 def __init__(self): ''' Objective: To instantiate a Record object Input: self: Implicit parameter key: key value for the record others: other information ''' self.key = Record.count + 10000 Record.count +=1 self.others = str(self.key)*random.randint(50,250) def __str__(self): ''' Objective: To override string function Input: self: Implicit parameter Return: STring representation of object ''' return str(self.key)+":"+self.others def getKey(self): ''' Objective: To return key value of a record Input: self: Implicit paramter Return: Key value ''' return self.key if __name__=="__main__": f1 = open("Records.txt",'wb') f2 = open("Index.txt",'wb') threshold=5000000 n = int(input("Enter the number of records to be created:")) for i in range(0,n): r = Record() offset = f1.tell() pickle.dump(r,f1) pickle.dump((r.getKey(),offset+threshold),f2) #print(f1.tell(),f2.tell()) f1.close() f2.close() f1 = open("Records.txt",'rb') f2 = open("Index.txt",'rb') k = int(input("Enter the key value of record to be accessed:")) k = k - 10001 f2.seek(14*k) tup=pickle.load(f2) f1.seek(int(tup[1])-threshold) print(pickle.load(f1))
d7b9d4fd9a105b0b8baec1e7760169594fa1524f
Jashanpreet001/Python-at-VMM-Amritsar.
/Numpy libraary in Python..py
1,579
4.125
4
#Introduction to numpy librabray in python. #One of the most powerful nummerical processing library. ##Numpy provides #1.Extension package for multi-dimensional array. #2.Efficient and convenient scientific computing # Example.Creating a simple array in numpy. import numpy as np a = np.array([1, 2, 3, 4]) print(a) print(np.arange(10)) # L = range(1000) # %timeit [i**2 for i in L] # # a = np.arange(1000) # %timeit a**2 #Creating arrays. b = np.array([1, 3, 4]) # 1-D array (VECTOR) len(a) c = np.array([[1, 2, 3], [3, 5, 6]]) # 2-D Array (MATRIX) print(c) c.shape d = np.array ([[[0, 1], [1, 2]], [[2, 3], [5, 6]]]) # 3-D array (n-dimensional array: TENSOR) # Funtions for creating arrays # using arange function e = np.arange(1, 10, 3) # start - end - step e # Using linspace function f = np.linspace(0, 1, 5) #start - end - number of points f # common arrays functions g = np.zeroes((3, 3)) # all zeros print('c\n', c) h = np.ones((2, 2)) #all ones print('d\n', p) #Using diag() function i = np.diag([1, 2, 3, 5, 0]) print(i) # Creating a random array j = np.random.rand(3, 2) print(j) ## II. Data Types. k = np.arange(5) print('k is', k) print(b.dtype) #Compplex data types l = np.array([1+2t, 3+2t]) print(d.type) # Boolean data types m = np.array([True, False, True]) print(m.dtype) ### III. Slicing and Indexing ## ## #Indexing ## n = np.diag([1, 2, 3, 4]) ## print(a) ## print(a[2, 2]) ## a[2, 2] = 5 ## print(a) ## ## #Slicing ## a = np.arange(10) ## print(a) ## a[1:5:2] #[startindex: endindex(not included: step]
ad033e87bd411f97ca99b27a29c81964b35b208e
Ishanbhatia98/linkedinlearningcourses
/python_code_Challenges/1_find_prime_factors.py
362
3.890625
4
def find(n, i=2, l=[1]): if n==1: return l elif i==2: if n%2==0: l.append(2) return find(n//2,i,l) return find(n,i+1,l) else: if n%i==0: l.append(i) return find(n//i, i) return find(n, i+2,l) n = int(input()) print('The prime factors of n are') print(*find(n))
0a08e12a7d790ce57ce98e41b2c597f8dec08df0
akivaadler/Flight_Radar_Mining_Project
/Route.py
637
4.28125
4
class Route: """Builds class that contains information about the different airports that each airlines flies into. iata and icao are two different international airport codes, and lat and long are the gps coordinates of the airport""" def __init__(self, airport_1, airport_2): self.airport_1 = airport_1 self.airport_2 = airport_2 def __str__(self): return f'Route: Airport 1: {self.airport_1.name} Airport 2: {self.airport_2.name}' def __repr__(self): return f'Route: Airport 1: {self.airport_1.name} Airport 2: {self.airport_2.name}' def get_distance(self): pass
baf9f1d9abf8dfd98427a005a53f1dc87763aaf7
AmiMunshi/Python-programs
/computingparadox
441
3.578125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Sep 6 19:34:37 2019 @author: maulik """ N=input() A= [int(N) for N in input().split()] dict1={} count=0 k=input() for i in A: temp= {i:count} dict1.update(temp) count=count+1 print(dict1) dict2={} for key in sorted(dict1.keys()): temp2= {key:dict1[key]} dict2.update(temp2) print(dict2) print(dict2[k]) #[ for (key, value) in sorted(numbers.items())]
5828fcb06f12e6f21f41eed2cab096f12d86bc1c
ruijis/ME249_pj4_PCM
/data/dataFiltering.py
1,384
4.03125
4
import pandas as pd import numpy as np def select_Columns_fromCSV(filepath, columns, keyColumn, surveyID): """ select desired columns from one CSV file. then select all rows that has the surveyID. Parameters: ---------------- filepath: str The path of CSV file columns: lst A list of strings of desired columns, including the keyColumn keyColumn: str The column for indexing or satisfing conditions surveyID: int Desired ID value in a key column Return: ---------------- data: dataframe Pandas dataframe """ dataCSV = pd.read_csv(filepath, usecols=columns) dataID = dataCSV[dataCSV[keyColumn] == surveyID] # when dataID is a list # dataID = dataCSV[(dataCSV[keyColumn]>=surveyID[0]) & (dataCSV[keyColumn]<=surveyID[1])] return dataID def replace_values(data, column, oldValues, newValues): """ replace old values with new values in a column in the datafame Parameters: ---------------- data: dataframe Pandas dataframe column: str A desired column oldValues: lst A list of all old values to be changed newValues: lst A list of all desired new values Return: ---------------- data: dataframe Pandas dataframe """ for i in range(len(oldValues)): # the column needs to be pure characters without quotations data[column] = np.where((data.column == oldValues[i]), newValues[i], data.column) return data
0e89d845e09ab9d246c6582e4dd6c2c870707d85
renning22/cortana
/model/naive/train.py
4,890
3.515625
4
# coding=utf-8 """ This is a most naive algorithm. For each sentence it assumes each word is generated by the domain it belongs to. It simply predict the target domain d as the one that maximize the value of: P(w1|d) * P(w2|d) * ... * P(wn|d) Use backoff discounting for words never occured in domain d. Ignore words never seen in the training data. http://en.wikipedia.org/wiki/Katz's_back-off_model """ import sys, os, math import argparse import cPickle as pickle from collections import defaultdict import numpy as np from sklearn import cross_validation from util import conv from util.log import _logger from feat.terms.term_categorize import term_category class NaiveBayes(object): def __init__(self, train_path, term_path, alpha = 0.5): self.train_path = train_path self.term_path = term_path self.alpha = alpha self.reset() self.load_data() def get_category(self, term): return term_category(term) def load_data(self): _logger.info("Loading training data from %s" % self.train_path) self.X = [] self.y = [] with open(self.train_path) as train_file: for line in train_file: line = line.strip().decode('utf-8') if not line: continue terms, domain = line.split('\t') self.X.append(terms) self.y.append(domain) def reset(self): self.training_sentence_count = 0 self.count = defaultdict(int) self.domain_has = defaultdict(set) self.domain_count = defaultdict(int) # Number of sentence in each domain self.domain_backoff = dict() self.term_count = defaultdict(int) self.terms = set() def fit(self, X, y): self.reset() size = len(y) for i in xrange(size): if (i + 1) % 10000 == 0: _logger.debug("%d processed" % (i+1)) terms = X[i] domain = y[i] self.training_sentence_count += 1 terms = terms.split(' ') self.domain_count[domain] += 1 term_set = set() for term in terms: term = self.get_category(term) if term in term_set: continue term_set.add(term) self.terms.add(term) self.count[term, domain] += 1 self.count[domain] += 1 self.term_count[term] += 1 self.domain_has[domain].add(term) for domain in self.domain_has: backoff = len(self.domain_has[domain]) * self.alpha / self.count[domain] backoff /= len(self.term_count) - len(self.domain_has[domain]) self.domain_backoff[domain] = backoff self.domains = self.domain_backoff.keys() def train(self): self.fit(self.X, self.y) def get_test_accuracy(self, X, y): total = len(y) correct = 0.0 from decode import NaiveDecoder decoder = NaiveDecoder(self) for idx, x in enumerate(X): y_pred = decoder.predict(x) if y_pred == y[idx]: correct += 1 return correct / total def cv(self, fold): size = len(self.y) kf = cross_validation.KFold(size, fold, shuffle=True) iteration = 0 scores = list() for train_idx, test_idx in kf: X = [self.X[idx] for idx in train_idx] y = [self.y[idx] for idx in train_idx] X_test = [self.X[idx] for idx in test_idx] y_test = [self.y[idx] for idx in test_idx] _logger.debug("Training...") self.fit(X, y) _logger.debug("Testing...") score = self.get_test_accuracy(X_test, y_test) scores.append(score) iteration += 1 _logger.info("CV iteration %d: CV accuracy: %f" % \ (iteration, score)) scores = np.array(scores) return scores.mean(), scores.std() if __name__ == "__main__": cmd = argparse.ArgumentParser() cmd.add_argument("--input", help="path of the training data",default="train.dat") cmd.add_argument("--terms", help="path of the terms file",default="terms.dat") cmd.add_argument("--alpha", help="alpha of discounting", type=float, default=0.5) cmd.add_argument("--cv", help="enable cross validation", type=int, default=0) args = cmd.parse_args() naive = NaiveBayes(conv.redirect(args.input), conv.redirect(args.terms), args.alpha) if args.cv > 0: _logger.info("CV accuracy: %f +/- %f" % naive.cv(args.cv)) else: _logger.info("Start training"); naive.train() with open("naive.model", "w") as outfile: pickle.dump(naive, outfile) _logger.info("Model dumped to naive.model")
fc92a02af0e43b3b4c496baf97a6be4016cb68af
mahfuzar07/learn_python
/Sphere.py
103
4.03125
4
R= int(input()) pi = 3.14159 volume = float((4.0/3) * pi * (pow(R,3))) print(f'VOLUME = {volume:.3f}')
b563f7daa6f73ad2308441d705d2c4c7aed75727
ashutoshm1771/Source-Code-from-Tutorials
/Python/29_python.py
354
3.765625
4
class Enemy: life = 3 def attack(self): print("ouch!") self.life -=1 def checkLife(self): if self.life <= 0: print("I am dead") else: print(str(self.life) + " life left") enemy1 = Enemy() enemy2 = Enemy() enemy1.attack() enemy1.attack() enemy1.checkLife() enemy2.checkLife()
476324d0bda06428aa6016c97ddde36cee55598f
AdlerKot/PyTest
/Sprints/Sprint01/Sprint01.py
2,429
3.578125
4
# #S01-00 # import os.path # def print_filename(): # if __name__ == "__main__": # print(os.path.basename(__file__)) # print_filename() # # #S01-01 # def crystal_ball(courage, intelligence): # if courage > 50 and intelligence > 50: # print("I see great success in your future.") # elif courage >= 100 or intelligence <= 10: # print("Your life is in danger!") # else: # print("Your future is a mystery") # def print_result(coureage, intelligence): # print(f'Reading the future for an adventurer with {coureage} courage ' # f'and {intelligence} intelligence...') # crystal_ball(coureage, intelligence) # print('***') # if __name__ == "__main__": # print_result(19, 0) # print_result(57, 60) # print_result(200, 79) # print_result(150, 15) # print_result(30, 100) # print_result(100, 25) # print_result(50, 55) # print_result(50, 9) # # #S01-02 # def buy_milk(money=0): # product = "[milk]" # price = 25 # if money >= price: # product = product * (money // price) # else: # product = None # return product # def buy_bread(money=0): # product = '[bread]' # price = 19 # if money >= price and money // price >= 3: # product = product * 3 # elif money >= price: # product = product * (money // price) # else: # product = None # return product # # print(f"Buy milk with 25$, result: {buy_milk(25)}") # print(f"Buy bread with 19$, result: {buy_bread(19)}") # print(f"Buy milk with nothing, result: {buy_milk()}") # print(f"Buy bread with nothing, result: {buy_bread(00)}") # print(f"Buy milk with 200$, result: {buy_milk(200)}") # print(f"Buy bread with 200$, result: {buy_bread(200)}") # print(f"Buy milk with 10$, result: {buy_milk(10)}") # print(f"Buy bread with 10$, result: {buy_bread(10)}") # print(f"Buy milk with 53$, result: {buy_milk(53)}") # print(f"Buy bread with 53$, result: {buy_bread(53)}") # print(f"Buy milk with 100$, result: {buy_milk(100)}") # print(f"Buy bread with 100$, result: {buy_bread(100)}") # a = 100 # b = 5 # c = min(7, a//b) # print(c) // ответ 7 # # #S01-03 # def patoi(a): # b = int() # try: # b = int(a) # return b # except ValueError: # return False # print(patoi(3)) # print(patoi('Romanes eunt domus')) # print(patoi('34b')) # print(patoi(-234.59)) # print(patoi('-234'))
e1301d4efef41f254c673855ad669df167d49ead
ravi4all/PythonDecMorning
/PythonDemo/02-Numbers.py
195
3.765625
4
a = 10 b = 12 c = a + b print("Addition is",c) print("Sum of {} and {} is {}".format(a,b,c)) print("Sum of %s and %s is %s"%(a,b,c)) print("Addition of a =",a," and b =",b," =",c)
a0fddaeb1623425fc7e3ae58f1d3728bfaa7a2d6
Yinggewen/CarND_Behavior_Clone
/Project3_model_v3.py
8,889
3.578125
4
# coding: utf-8 # # Use Keras to train a network to do the following: # # 1. Take in an image from the center camera of the car. This is the input to your neural network. # Output a new steering angle for the car. # # 2. You don’t have to worry about the throttle for this project, that will be set for you. # # 3. Save your model architecture as model.json, and the weights as model.h5. # https://keras.io/models/about-keras-models/ # # 4. python drive.py model.json # # 5. Tips # Adding dropout layers to your network. # Splitting your dataset into a training set and a validation set. # # # In[1]: ##get_ipython().magic('matplotlib inline') import argparse import numpy as np import tensorflow as tf import os from os import listdir import matplotlib.pyplot as plt from scipy.misc import imresize, imread from scipy import ndimage from skimage.exposure import adjust_gamma,rescale_intensity from sklearn.model_selection import train_test_split import pandas as pd # ## Step 0: Load The Data # In[2]: df = pd.read_csv("driving_log_clean_all.csv", header=None) df.columns=('Center Image','Left Image','Right Image','Steering Angle') print (df.shape) df.head() # In[3]: listdir=os.listdir("/home/ubuntu/udacity_wu/CarND-behavior-clone/test2/final/IMG/") listdir.sort() # In[4]: import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np import cv2 ''' # In[5]: center_data=df['Center Image'] left_data=df['Left Image'] right_data=df['Right Image'] # In[6]: def load_images_from_center(folder): images = [] for filename in center_data: #img = cv2.imread(os.path.join(folder,filename)) #img = mpimg.imread(filename.strip()) img = mpimg.imread(filename.strip()) if img is not None: images.append(img) images=np.stack(images, axis=0) return images def load_images_from_left(folder): images = [] for filename in left_data: #img = cv2.imread(os.path.join(folder,filename)) img = mpimg.imread(filename.strip()) #print(filename) #print(len(img.shape)) #print(filename) #break if img is not None: images.append(img) images=np.stack(images, axis=0) return images def load_images_from_right(folder): images = [] for filename in right_data: #img = cv2.imread(os.path.join(folder,filename)) img = mpimg.imread(filename.strip()) if img is not None: images.append(img) images=np.stack(images, axis=0) return images # In[7]: image_center=load_images_from_center("/home/ubuntu/udacity_wu/CarND-behavior-clone/test2/IMG/") image_left=load_images_from_left("/home/ubuntu/udacity_wu/CarND-behavior-clone/test2/IMG/") image_right=load_images_from_right("/home/ubuntu/udacity_wu/CarND-behavior-clone/test2/IMG/") # In[8]: plt.imshow(image_center[0]) # In[9]: plt.imshow(image_right[0]) # In[10]: plt.imshow(image_left[0]) ''' # ## Step 1: Preprocess the data # ### Populate controlled driving datasets # In[3]: flags = tf.app.flags FLAGS = flags.FLAGS flags.DEFINE_string('imgs_dir', 'IMG/', 'The directory of the image data.') flags.DEFINE_string('data_path', 'driving_log_clean_all.csv', 'The path to the csv of training data.') flags.DEFINE_integer('batch_size', 128, 'The minibatch size.') flags.DEFINE_integer('num_epochs', 5, 'The number of epochs to train for.') flags.DEFINE_float('lrate', 0.0001, 'The learning rate for training.') # In[4]: def read_imgs(img_paths): imgs = np.empty([len(img_paths), 160, 320, 3]) for i, path in enumerate(img_paths): imgs[i] = imread(path) return imgs def resize(imgs, shape=(32, 16, 3)): """ Resize images to shape. """ height, width, channels = shape imgs_resized = np.empty([len(imgs), height, width, channels]) for i, img in enumerate(imgs): imgs_resized[i] = imresize(img, shape) return imgs_resized def rgb2gray(imgs): """ Convert images to grayscale. """ return np.mean(imgs, axis=3, keepdims=True) def normalize(imgs): """ Normalize images between [-1, 1]. """ return imgs / (255.0 / 2) - 1 def preprocess(imgs): imgs_processed = resize(imgs) imgs_processed = rgb2gray(imgs_processed) imgs_processed = normalize(imgs_processed) return imgs_processed #Augment the data by randomly flipping some angles / images horizontally. def random_flip(imgs, angles): new_imgs = np.empty_like(imgs) new_angles = np.empty_like(angles) for i, (img, angle) in enumerate(zip(imgs, angles)): if np.random.choice(2): new_imgs[i] = np.fliplr(img) new_angles[i] = angle * -1 else: new_imgs[i] = img new_angles[i] = angle return new_imgs, new_angles def augment(imgs, angles): imgs_augmented, angles_augmented = random_flip(imgs, angles) return imgs_augmented, angles_augmented # In[5]: def gen_batches(imgs, angles, batch_size): """ Generates random batches of the input data. :param imgs: The input images. :param angles: The steering angles associated with each image. :param batch_size: The size of each minibatch. :yield: A tuple (images, angles), where both images and angles have batch_size elements. """ num_elts = len(imgs) while True: indeces = np.random.choice(num_elts, batch_size) batch_imgs_raw, angles_raw = read_imgs(imgs[indeces]), angles[indeces].astype(float) batch_imgs, batch_angles = augment(preprocess(batch_imgs_raw), angles_raw) yield batch_imgs, batch_angles # ## Step 2: Split the data # In[6]: # Construct arrays for center, right and left images of controlled driving angles = np.array(df['Steering Angle']) center = np.array(df['Center Image'].map(str.strip)) right = np.array(df['Right Image'].map(str.strip)) left = np.array(df['Left Image'].map(str.strip)) # In[7]: # Concatenate all arrays in to combined training dataset and labels X_train = np.concatenate((center, right, left), axis=0) y_train = np.concatenate((angles, angles-np.array(0.08), angles+np.array(0.08)),axis=0) # Perform train/test split to a create validation dataset X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=.05) # ## Step 3: Design and Test a Model Architecture # In[8]: import json from keras import backend from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, MaxPooling2D from keras.layers.normalization import BatchNormalization from keras.optimizers import Adam from keras.callbacks import ModelCheckpoint, EarlyStopping import matplotlib.pyplot as plt import matplotlib.image as mpimg # In[9]: model = Sequential() model.add(Conv2D(32, 3, 3, input_shape=(32, 16, 1), border_mode='same', activation='relu'),) model.add(Conv2D(24, 3, 3, border_mode='valid', subsample=(1,2), activation='relu')) model.add(Dropout(.5)) model.add(Conv2D(36, 3, 3, border_mode='valid', activation='relu')) model.add(Conv2D(48, 2, 2, border_mode='valid', activation='relu')) model.add(Flatten()) model.add(Dense(512)) model.add(Dropout(.5)) model.add(Activation('relu')) model.add(Dense(10)) model.add(Activation('relu')) model.add(Dense(1, name='output', activation='tanh')) model.summary() # In[10]: # Compile model with adam optimizer and learning rate of .0001 adam = Adam(lr=0.0001) model.compile(loss='mse',optimizer=adam) # Train model for 20 epochs and a batch size of 128 backend.get_session().run(tf.initialize_all_variables()) model.fit_generator(gen_batches(X_train, y_train, FLAGS.batch_size), len(X_train),FLAGS.num_epochs, validation_data=gen_batches(X_val, y_val, FLAGS.batch_size), nb_val_samples=len(X_val)) # In[19]: ''' ### Add recovery data # Get steering angles for recovery driving recovery_angles = pd.read_csv('driving_log_recover.csv', header = None) recovery_angles.columns = ('Center Image','Left Image','Right Image','Steering Angle','Throttle','Brake','Speed') recovery_angles = np.array(recovery_angles['Steering Angle']) ''' # In[20]: ''' # Construct array for recovery driving images recovery_images = np.asarray(os.listdir("../IMG_recover/")) recovery = np.ndarray(shape=(len(recovery_angles), 32, 16, 3)) # Populate recovery driving dataset count = 0 for image in recovery_images: image_file = os.path.join('../IMG_recover', image) image_data = ndimage.imread(image_file).astype(np.float32) #image_data=cv2.cvtColor(image_data, cv2.COLOR_BGR2HSV) recovery[count] = imresize(image_data, (32,64,3))[12:,:,:] count += 1 ''' # ## Step 4: Save model Architecture # In[11]: json = model.to_json() model.save_weights('model_v3.h5') with open('model_v3.json', 'w') as f: f.write(json) # In[ ]:
b16674aee6ad311997c971ad046f0e857e9ff960
ekene966/hackerrank
/python/sock-merchant.py
241
3.625
4
#!/bin/python3 from collections import Counter def pairs(socks): return sum(list(map(lambda sock: sock // 2, Counter(socks).values()))) _ = int(input().strip()) socks = list(map(int, input().strip().split(' '))) print(pairs(socks))
776e8e19ad39b3d1070a55adf45db403c2602fd8
guyuzhilian/Programs
/Python/project_euler/problem36.py
523
3.796875
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # author: lidajun # date: 2015-08-31 13:59 def is_palindromic(num, base = 10): if base == 10: str_num = str(num) else: str_num = bin(num)[2:] if str_num == str_num[::-1]: print(num, base, str_num) return True return False def main(): total = 0 for num in xrange(1, 1000000): if is_palindromic(num, 10) and is_palindromic(num, 2): total += num print(total) if __name__ == "__main__": main()
959600c95a685ac94cee7f589f19257758d7aca3
eggitayi/learnpy
/senior/my_module.py
490
3.890625
4
class Person(object): def __init__(self, name, age=10): self.name = name self.age = age def say(self, content="nothting"): print "%s : %s" % (self.name, content) def leave(self): print "%s left" % (self.name) def introduce(self): print "My name is %s, and I'm %s now" % (self.name, self.age) if __name__ == '__main__': lily = Person('Lily', 14) lily.introduce() lily.say("WTF") lily.leave() one = Person('ONE')
9cb206f67cab9b264e773cd60309e1076c8f1c82
NagaSolo/202007_t4rb0l33t_W3
/07272020_BinTreeFrInPostOrderTraversal/inorderpostorder.py
2,309
4.125
4
''' constructing binary tree from postorder and inorder traversal Problem Statement: Given inorder and postorder traversal of a tree, construct the binary tree. Note: You may assume that duplicates do not exist in the tree. For example, given inorder = [9,3,15,20,7] postorder = [9,15,7,20,3] Return the following binary tree: 3 / \ 9 20 / \ 15 7 Algorithm Inorder(tree): 1. Traverse the left subtree, i.e., call Inorder(left-subtree) 2. Visit the root. 3. Traverse the right subtree, i.e., call Inorder(right-subtree) Uses of Inorder: In case of binary search trees (BST), Inorder traversal gives nodes in non-decreasing order. To get nodes of BST in non-increasing order, a variation of Inorder traversal where Inorder traversal s reversed can be used. Algorithm Postorder(tree) 1. Traverse the left subtree, i.e., call Postorder(left-subtree) 2. Traverse the right subtree, i.e., call Postorder(right-subtree) 3. Visit the root. Uses of Postorder: Postorder traversal is used to delete the tree. Please see the question for deletion of tree for details. Postorder traversal is also useful to get the postfix expression of an expression tree. Please see http://en.wikipedia.org/wiki/Reverse_Polish_notation to for the usage of postfix expression. ''' # Definition for a binary tree node. # Input: # inorder -> list of integers # postorder -> list of integers # Output: # TreeNode class TreeNode: def __init__(self, val): self.val = val self.left = None self.right = None class Solution: def buildTree(self, inorder, postorder): pass def display_inorder(self, root): if root: self.display_inorder(TreeNode(root).left) print(TreeNode(root).val) self.display_inorder(TreeNode(root).right) def display_postorder(self, root): if root: self.display_postorder(TreeNode(root).left) self.display_postorder(TreeNode(root).right) print(TreeNode(root).val) # driver if __name__ == '__main__': inorder = [9,3,15,20,7] for i, j in enumerate(inorder): Solution().display_inorder(j)
251441327a2ce75a820cf745fbc532ac39eb089e
lai-pj/practise
/FindPrimeInt.py
598
3.796875
4
__author__ = 'lai' def prime(): n=int(raw_input()) array=[] for i in range(2,n): if is_prime(i): array.append(i) while True : try: num=int(raw_input()) index= getIndex(array,num,0,len(array)-1) print index except: break def is_prime(num): for i in range(2,num): if num%i==0: return False return True def getIndex(array,num,low,hight): if low>hight: return -1 else: mid=(low+hight)/2 midNum=array[mid] if midNum==num: return mid elif midNum>num: return getIndex(array,num,low,mid-1) else: return getIndex(array,num,mid+1,hight) prime()
16e602615257ed1f7fd1b785defe0bbc5d977847
Infogroep/imp-client
/routing.py
5,194
3.921875
4
import sys import re class Router: """ This module provides a simple way to decide program action based on the command line parameters. This is particularly useful for scripts that will be called by the server, as it allows simple processing of the URI. The Router class is the main brain of the routing module. """ routed = False def __init__(self,argv = sys.argv[2:]): """ Creates a new router that will route based on the arguments provided. @param argv: The arguments to route on. The default argv is sys.argv without the first two parameters, which in server scripts corresponds to the HTTP method followed by the remaining URL path. """ self.argv = argv def match(self,to,rule = [],options = {}): """ Attempts to match a rule. A rule consists of an array of stringss. These will be matched one by one respectively to the arguments provided during the router's initialization. Arguments can be captured into a hashtable which is sent as a parameter to the function provided in to. - A string will be matched verbatim but case insensitive to their respective argument. - A string starting with ":" represents a capture, and will cause the argument to be pulled into the bindings hash. Captures can still be constrained by providing a regexp that needs to be matched with the capture's name in the options. The function provided in will be executed if the rule matches. >>> # get playlist <id> >>> r.match(lambda b: show_pl(b["playlist_id"]), ["get","playlist",":playlist_id"]) >>> # set <numeric id> >>> r.match(lambda b: set_id(int(b["id"])), ["set",":id"], { "id": "[0-9]+" }) >>> # help/info >>> r.match(lambda b: show_info(), [["help","info"]]) >>> # add <id> to <username> >>> r.match( ... lambda b: add_id_to_username(int(b["id"]), b["username"]), ... ["add",":id","to",":username"], ... { "id": "[0-9]+", "username": "[a-z]+" }) Generally you will want to use the helper functions provided by the __getattr__ implementation as it allows for a cleaner notation for standard queries. @param to: A function that will be executed when the rule matches. The function takes a single parameter, which is a hashtable of bound captures. @param rule: An array of strings that the arguments will be matched against. @param options: A hashtable of options. Currently this only accepts regexp constraints on captures. """ ruleOpenEnded = False openArgs = [] args = self.argv if len(rule) > 0 and rule[-1] == "...": ruleOpenEnded = True rule = rule[:-1] if len(args) < len(rule): return if len(args) > len(rule): if ruleOpenEnded: openArgs = args[len(rule):] args = args[:len(rule)] else: return bindings = self._match_rule(rule,args,options) if bindings != False: self.routed = True bindings["..."] = openArgs to(bindings) def __getattr__(self,attr): """ Provides helper methods for the match function. When an arbitrary method is called on the Router object it is processed as a match where the first rule element is the method name as a string. This allows for a shorter and clearer notation for typical usage, especially when handling HTTP requests in server scripts, where it shows a clear difference between the HTTP method and the URL parts. >>> # get playlist <id> >>> r.get(lambda b: show_pl(b["playlist_id"]), ["playlist",":playlist_id"]) >>> # set <numeric id> >>> r.set(lambda b: set_id(int(b["id"])), [":id"], { "id": "[0-9]+" }) >>> # help >>> r.help(lambda b: show_help()) >>> # add <id> to <username> >>> r.add( ... lambda b: add_id_to_username(int(b["id"]), b["username"]), ... [":id","to",":username"], ... { "id": "[0-9]+", "username": "[a-z]+" }) """ return lambda to,rule = [],options = {}: self._special_match(attr,to,rule,options) def _special_match(self,attr,to,rule = [],options = {}): self.match(to,[attr] + rule,options) def is_routed(self): """ Returns if the router has found a route for the arguments. @rtype: bool @return: True if a route has been found, False otherwise """ return self.routed def _match_rule_element(self,rule_el,realarg,bindings,options): if rule_el[0] == ":": rule_el = rule_el[1:] bindings[rule_el] = realarg return not rule_el in options or re.compile(options[rule_el]).match(realarg) elif type(rule_el) == str: return rule_el.lower() == realarg.lower() elif type(rule_el) == list: for el in rule_el: if self._match_rule_element(el,realarg,bindings,options): return True return False else: raise "Illegal rule for router match: #{rule}" def _match_rule(self,rule,realargs,options): bindings = {} for (rule_el,realarg) in zip(rule,realargs): if not self._match_rule_element(rule_el,realarg,bindings,options): return False return bindings def finalize(self): """ Convenience method. Throws a BaseException if no route was found. Call after all your match calls. """ if not self.routed: raise BaseException("Couldn't find a route")
62bbc2bf39d7d65ad320741702b60330ab5adeac
sheerlinvuong/Map-Project
/vpython/parsestring.py
397
3.859375
4
def findLargestNumber(text): ls = list() for w in text.split(): try: ls.append(int(w)) except: pass try: return max(ls) except: return None print (findLargestNumber('I saw 3 dogs, 17 cats, and 14 cows!')) print (findLargestNumber('0;-1')) v="3.5;0;-1" v_split = v.split(";") v = max(v_split) print(str(v))
fb5ec6dbae0d1bf6ddcf8ae700147d96963ecfdd
DannyRH27/RektCode
/Mocks/TJ/mock13.py
2,097
4.125
4
''' Collection of stones Each stone has a positive int weight Each turn, choose the two heaviest stones and smash together x, y x <= y if they are the same, both stones destroyed if not, stone with lesser weight is destroyed, stone with bigger weight is difference At the end, there is at most one stone left. Return weight of this stone or 0 if no stones are left. Strategy: In order to know which stones are always the heaviest I will have a max heap of these stones while the length of this heap is >= to 2 I will heappop one, heappop again, if they are the same, both stones are destroyed if they are different, then i will heappush that difference onto the heap eventually when the heap is 1 or 0, depending on which i will return the stone or 0 Get the smallest possible last rock or return 0 if there are none What is the heuristic for determining which rocks to pick Brainstorm: I always want to be nullifying the biggest number Can't tell by looking at the stones what do i want the result of smashing the stones together to be Outcome is the smallest rock Brute Force: Launch calls to smash them all push answers to a min_heap then return the min runtime: nlogn space: n Example 1: Input: [2,7,4,1,8,1] Output: 1 Explanation: We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then, we combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then, we combine 2 and 1 to get 1 so the array converts to [1,1,1] then, we combine 1 and 1 to get 0 so the array converts to [1] then that's the value of last stone. Note: 1 <= stones.length <= 30 1 <= stones[i] <= 1000 ''' import heapq def lastStoneWeight(stones): heapq._heapify_max(stones) while len(stones) >= 2: first = heapq._heappop_max(stones) second = heapq._heappop_max(stones) if first == second: continue heapq.heappush(stones, first-second) heapq._heapify_max(stones) if len(stones): return stones[0] return 0 # assert(lastStoneWeight([2, 7, 4, 1, 8, 1]) == 1) # assert(lastStoneWeight([10, 4, 2, 10]) == 2) assert(lastStoneWeight([7, 6, 7, 6, 9]) == 3)
d2bcf03412800c79505a57b8c8a3d240d45ca306
johli/aparent-legacy
/cnn/logistic_sgd_global_onesided2_cuts_vis.py
21,236
3.828125
4
""" This tutorial introduces logistic regression using Theano and stochastic gradient descent. Logistic regression is a probabilistic, linear classifier. It is parametrized by a weight matrix :math:`W` and a bias vector :math:`b`. Classification is done by projecting data points onto a set of hyperplanes, the distance to which is used to determine a class membership probability. Mathematically, this can be written as: .. math:: P(Y=i|x, W,b) &= softmax_i(W x + b) \\ &= \frac {e^{W_i x + b_i}} {\sum_j e^{W_j x + b_j}} The output of the model or prediction is then done by taking the argmax of the vector whose i'th element is P(Y=i|x). .. math:: y_{pred} = argmax_i P(Y=i|x,W,b) This tutorial presents a stochastic gradient descent optimization method suitable for large datasets. References: - textbooks: "Pattern Recognition and Machine Learning" - Christopher M. Bishop, section 4.3.2 """ __docformat__ = 'restructedtext en' import cPickle import gzip import os import sys import time import numpy import scipy.sparse as sp import scipy.io as spio import theano import theano.tensor as T class TrainableImage(object): def __init__(self, rng, n_images, n_length, seq, start_seqs): mask = numpy.zeros((n_images, len(seq), 4)) is_trainable = [] is_not_trainable = [] is_zero = [] if start_seqs is None : for i in range(0, len(seq)) : if seq[i] == 'A' : mask[:, i, 0] = 1 is_not_trainable.append(i) elif seq[i] == 'C' : mask[:, i, 1] = 1 is_not_trainable.append(i) elif seq[i] == 'G' : mask[:, i, 2] = 1 is_not_trainable.append(i) elif seq[i] == 'T' : mask[:, i, 3] = 1 is_not_trainable.append(i) elif seq[i] == 'N' : mask[:, i, :] = rng.uniform(low=-0.2, high=0.2, size=(n_images, 4)) is_trainable.append(i) else : is_not_trainable.append(i) is_zero.append(i) else : for j in range(0, n_images) : start_seq = start_seqs[j] for i in range(0, len(start_seq)) : if start_seq[i] == '.' : is_not_trainable.append(i) is_zero.append(i) else : if start_seq[i] == 'A' : mask[j, i, 0] = 0.7 mask[j, i, [1, 2, 3]] = 0.1 is_trainable.append(i) elif start_seq[i] == 'C' : mask[j, i, 1] = 0.7 mask[j, i, [0, 2, 3]] = 0.1 is_trainable.append(i) elif start_seq[i] == 'G' : mask[j, i, 2] = 0.7 mask[j, i, [0, 1, 3]] = 0.1 is_trainable.append(i) elif start_seq[i] == 'T' : mask[j, i, 3] = 0.7 mask[j, i, [0, 1, 2]] = 0.1 is_trainable.append(i) elif seq[i] == 'N' : mask[j, i, :] = rng.uniform(low=-0.2, high=0.2, size=(4,)) is_trainable.append(i) #print(mask[0, :, :]) #print(is_trainable) #print(is_not_trainable) W_trainable = theano.shared( value=numpy.array( mask[:, is_trainable, :], dtype=theano.config.floatX ), name='W_trainable', borrow=True ) W_not_trainable = theano.shared( value=numpy.array( mask[:, is_not_trainable, :], dtype=theano.config.floatX ), name='W_not_trainable', borrow=True ) '''W = theano.shared( value=numpy.array( mask, dtype=theano.config.floatX ), name='masked_W', borrow=True )''' self.is_trainable = is_trainable self.is_not_trainable = is_not_trainable W = theano.shared( value=numpy.zeros( (n_images, len(seq), 4), dtype=theano.config.floatX ), name='masked_W', borrow=True ) W = T.set_subtensor(W[:, is_trainable, :], W_trainable) #W = T.set_subtensor(W[:, is_not_trainable, :], W_not_trainable) self.W = W #self.outputs = self.W #self.outputs = T.switch(self.W<0, 0, self.W) #self.outputs = T.nnet.softmax(self.W) #T.cast(T.switch(self.W >= T.max(self.W, axis=1), 1, 0), 'float64') outputs = T.nnet.softmax(self.W.reshape((n_images * n_length, 4))).reshape((n_images, n_length, 4)) if start_seqs is None : if len(is_zero) > 1 : outputs = T.set_subtensor(outputs[:, is_zero, :], 0) outputs = T.set_subtensor(outputs[:, is_not_trainable, :], W_not_trainable)#Original statement before AWS! #outputs = T.set_subtensor(outputs[:, is_not_trainable, :], W_not_trainable.reshape((n_images, len(is_not_trainable), 4))) #self.outputs[:, zero_region[0]:zero_region[1], :] = 0 self.outputs = outputs #T.eq(x, x.max()) self.params = [W_trainable]#[self.W[:, :zero_region[0], :], self.W[:, zero_region[1]:, :]] class TrainableImageSimple(object): def __init__(self, rng, n_images, n_length, zero_region=[40,73]): """ Initialize the parameters of the logistic regression :type input: theano.tensor.TensorType :param input: symbolic variable that describes the input of the architecture (one minibatch) :type n_in: int :param n_in: number of input units, the dimension of the space in which the datapoints lie :type n_out: int :param n_out: number of output units, the dimension of the space in which the labels lie """ # start-snippet-1 # initialize with 0 the weights W as a matrix of shape (n_in, n_out) self.W = theano.shared( numpy.asarray( rng.uniform(low=-0.2, high=0.2, size=(n_images, n_length, 4)), dtype=theano.config.floatX ), name='W', borrow=True ) '''self.W = theano.shared( value=numpy.zeros( (n_length, 4), dtype=theano.config.floatX ), name='W', borrow=True )''' # initialize the baises b as a vector of n_out 0s '''self.b = theano.shared( value=numpy.zeros( (n_out,), dtype=theano.config.floatX ), name='b', borrow=True )''' #self.outputs = self.W #self.outputs = T.switch(self.W<0, 0, self.W) #self.outputs = T.nnet.softmax(self.W) #T.cast(T.switch(self.W >= T.max(self.W, axis=1), 1, 0), 'float64') self.outputs = T.nnet.softmax(self.W.reshape((n_images * n_length, 4))).reshape((n_images, n_length, 4)) #self.outputs[:, zero_region[0]:zero_region[1], :] = 0 #self.outputs = T.concatenate([self.outputs, T.zeros([x.shape[0], y.shape[1]], dtype=theano.config.floatX), self.outputs], axis=1) #T.eq(x, x.max()) self.params = [self.W]#[self.W[:, :zero_region[0], :], self.W[:, zero_region[1]:, :]] class LogisticRegression(object): """Multi-class Logistic Regression Class The logistic regression is fully described by a weight matrix :math:`W` and bias vector :math:`b`. Classification is done by projecting data points onto a set of hyperplanes, the distance to which is used to determine a class membership probability. """ def store_w(self, w_file, W): numpy.save(w_file, W) def store_b(self, b_file, b): numpy.save(b_file, b) def store_model(self, W, b): self.store_w(self.store_as_w_file, W) self.store_b(self.store_as_b_file, b) def load_w(self, w_file): return numpy.load(w_file) def load_b(self, b_file): return numpy.load(b_file) def __init__(self, cnn, image, input, L_input, n_in, n_out, load_model = False, cost_func='max_score', cost_layer_filter=0, w_file = '', b_file = '', store_as_w_file = None, store_as_b_file = None): """ Initialize the parameters of the logistic regression :type input: theano.tensor.TensorType :param input: symbolic variable that describes the input of the architecture (one minibatch) :type n_in: int :param n_in: number of input units, the dimension of the space in which the datapoints lie :type n_out: int :param n_out: number of output units, the dimension of the space in which the labels lie """ # start-snippet-1 # initialize with 0 the weights W as a matrix of shape (n_in, n_out) self.cost_func = cost_func self.w_file = w_file self.b_file = b_file self.image = image self.cnn = cnn self.cost_layer_filter = cost_layer_filter self.store_as_w_file = w_file self.store_as_b_file = b_file if store_as_w_file is not None and store_as_b_file is not None : self.store_as_w_file = store_as_w_file self.store_as_b_file = store_as_b_file if load_model == False : self.W = theano.shared( value=numpy.zeros( (n_in, n_out), dtype=theano.config.floatX ), name='W', borrow=True ) # initialize the baises b as a vector of n_out 0s self.b = theano.shared( value=numpy.zeros( (n_out,), dtype=theano.config.floatX ), name='b', borrow=True ) else : self.W = theano.shared( value=self.load_w(w_file + '.npy'), name='W', borrow=True ) # initialize the baises b as a vector of n_out 0s self.b = theano.shared( value=self.load_b(b_file + '.npy'), name='b', borrow=True ) # symbolic expression for computing the matrix of class-membership # probabilities # Where: # W is a matrix where column-k represent the separation hyper plain for # class-k # x is a matrix where row-j represents input training sample-j # b is a vector where element-k represent the free parameter of hyper # plain-k self.p_y_given_x = T.nnet.softmax(T.dot(input, self.W) + self.b) self.s_y_given_x = T.dot(input, self.W) + self.b # parameters of the model self.params = [self.W, self.b] def negative_log_likelihood(self, y, epoch): """Return the mean of the negative log-likelihood of the prediction of this model under a given target distribution. .. math:: \frac{1}{|\mathcal{D}|} \mathcal{L} (\theta=\{W,b\}, \mathcal{D}) = \frac{1}{|\mathcal{D}|} \sum_{i=0}^{|\mathcal{D}|} \log(P(Y=y^{(i)}|x^{(i)}, W,b)) \\ \ell (\theta=\{W,b\}, \mathcal{D}) :type y: theano.tensor.TensorType :param y: corresponds to a vector that gives for each example the correct label Note: we use the mean instead of the sum so that the learning rate is less dependent on the batch size """ # start-snippet-2 # y.shape[0] is (symbolically) the number of rows in y, i.e., # number of examples (call it n) in the minibatch # T.arange(y.shape[0]) is a symbolic vector which will contain # [0,1,2,... n-1] T.log(self.p_y_given_x) is a matrix of # Log-Probabilities (call it LP) with one row per example and # one column per class LP[T.arange(y.shape[0]),y] is a vector # v containing [LP[0,y[0]], LP[1,y[1]], LP[2,y[2]], ..., # LP[n-1,y[n-1]]] and T.mean(LP[T.arange(y.shape[0]),y]) is # the mean (across minibatch examples) of the elements in v, # i.e., the mean log-likelihood across the minibatch. #return -T.mean(T.dot(T.log(self.p_y_given_x), T.transpose(y))[T.arange(y.shape[0]), T.arange(y.shape[0])]) #return -T.mean( T.sum(T.mul(T.log(self.p_y_given_x), y), axis=1) ) if self.cost_func == 'max_score_GGCC_punish_aruns_ent' : #return -T.sum(self.s_y_given_x[:, self.cost_layer_filter]) + T.sum(self.image[:, :, :50, 1]) * 0.05 #+ T.sum(self.image[:, :, :, 2]) * 0.0005 #return -T.sum(self.p_y_given_x[:, self.cost_layer_filter-1:self.cost_layer_filter+1]) #return -T.sum(self.p_y_given_x[:, self.cost_layer_filter]) #return T.switch(T.le(epoch, 100), -T.sum(self.s_y_given_x[:, self.cost_layer_filter]), -T.sum(self.p_y_given_x[:, self.cost_layer_filter])) return T.switch(T.le(epoch, 3000),#3000#4000#2000#1000 #-T.sum(self.s_y_given_x[:, self.cost_layer_filter]) + T.sum(self.image[:, :, :45, 1]) * 0.5, #-T.sum(self.s_y_given_x[:, self.cost_layer_filter]) + T.sum(self.image[:, :, :45, 1]) * 0.5 / self.image.shape[0].astype(theano.config.floatX) - T.sum(self.image[:, :, 60:90, 1] * self.image[:, :, 59:89, 1]) * 0.01 * T.sum(self.image[:, :, 60:90, 2] * self.image[:, :, 59:89, 2]) / self.image.shape[0].astype(theano.config.floatX), #-T.sum(self.s_y_given_x[:, self.cost_layer_filter]) + T.sum(self.image[:, :, :45, 1]) * 0.5 - T.sum(self.image[:, :, 60:90, 1] * self.image[:, :, 59:89, 1]) * 0.01 * T.sum(self.image[:, :, 60:90, 2] * self.image[:, :, 59:89, 2]), -T.sum(self.s_y_given_x[:, self.cost_layer_filter]) + T.sum(self.image[:, :, :45, 1]) * 0.5 - T.sum(self.image[:, :, 60:90, 1] * self.image[:, :, 59:89, 1]) * 0.017 * T.sum(self.image[:, :, 60:90, 2] * self.image[:, :, 59:89, 2]) + T.sum(self.image[:, :, 55:-1, 0] * self.image[:, :, 56:, 0]) * 0.5, -T.sum(self.p_y_given_x[:, self.cost_layer_filter])) - T.sum( T.sum( self.image * T.log(self.image + 10**-6), axis=1) ) * 0.02 if self.cost_func == 'max_score_punish_aruns_ent' : #return -T.sum(self.s_y_given_x[:, self.cost_layer_filter]) + T.sum(self.image[:, :, :50, 1]) * 0.05 #+ T.sum(self.image[:, :, :, 2]) * 0.0005 #return -T.sum(self.p_y_given_x[:, self.cost_layer_filter-1:self.cost_layer_filter+1]) #return -T.sum(self.p_y_given_x[:, self.cost_layer_filter]) #return T.switch(T.le(epoch, 100), -T.sum(self.s_y_given_x[:, self.cost_layer_filter]), -T.sum(self.p_y_given_x[:, self.cost_layer_filter])) return T.switch(T.le(epoch, 3000),#3000#2000#1000 #-T.sum(self.s_y_given_x[:, self.cost_layer_filter]) + T.sum(self.image[:, :, :45, 1]) * 0.5, #-T.sum(self.s_y_given_x[:, self.cost_layer_filter]) + T.sum(self.image[:, :, :45, 1]) * 0.5 / self.image.shape[0].astype(theano.config.floatX), -T.sum(self.s_y_given_x[:, self.cost_layer_filter]) + T.sum(self.image[:, :, :45, 1]) * 0.5 + T.sum(self.image[:, :, 55:-1, 0] * self.image[:, :, 56:, 0]) * 0.5, -T.sum(self.p_y_given_x[:, self.cost_layer_filter])) - T.sum( T.sum( self.image * T.log(self.image + 10**-6), axis=1) ) * 0.02 if self.cost_func == 'max_score_GGCC_ent' : #return -T.sum(self.s_y_given_x[:, self.cost_layer_filter]) + T.sum(self.image[:, :, :50, 1]) * 0.05 #+ T.sum(self.image[:, :, :, 2]) * 0.0005 #return -T.sum(self.p_y_given_x[:, self.cost_layer_filter-1:self.cost_layer_filter+1]) #return -T.sum(self.p_y_given_x[:, self.cost_layer_filter]) #return T.switch(T.le(epoch, 100), -T.sum(self.s_y_given_x[:, self.cost_layer_filter]), -T.sum(self.p_y_given_x[:, self.cost_layer_filter])) return T.switch(T.le(epoch, 3000),#3000#4000#2000#1000 #-T.sum(self.s_y_given_x[:, self.cost_layer_filter]) + T.sum(self.image[:, :, :45, 1]) * 0.5, #-T.sum(self.s_y_given_x[:, self.cost_layer_filter]) + T.sum(self.image[:, :, :45, 1]) * 0.5 / self.image.shape[0].astype(theano.config.floatX) - T.sum(self.image[:, :, 60:90, 1] * self.image[:, :, 59:89, 1]) * 0.01 * T.sum(self.image[:, :, 60:90, 2] * self.image[:, :, 59:89, 2]) / self.image.shape[0].astype(theano.config.floatX), #-T.sum(self.s_y_given_x[:, self.cost_layer_filter]) + T.sum(self.image[:, :, :45, 1]) * 0.5 - T.sum(self.image[:, :, 60:90, 1] * self.image[:, :, 59:89, 1]) * 0.01 * T.sum(self.image[:, :, 60:90, 2] * self.image[:, :, 59:89, 2]), -T.sum(self.s_y_given_x[:, self.cost_layer_filter]) + T.sum(self.image[:, :, :45, 1]) * 0.5 - T.sum(self.image[:, :, 60:90, 1] * self.image[:, :, 59:89, 1]) * 0.017 * T.sum(self.image[:, :, 60:90, 2] * self.image[:, :, 59:89, 2]), -T.sum(self.p_y_given_x[:, self.cost_layer_filter])) - T.sum( T.sum( self.image * T.log(self.image + 10**-6), axis=1) ) * 0.02 if self.cost_func == 'max_score_ent' : #return -T.sum(self.s_y_given_x[:, self.cost_layer_filter]) + T.sum(self.image[:, :, :50, 1]) * 0.05 #+ T.sum(self.image[:, :, :, 2]) * 0.0005 #return -T.sum(self.p_y_given_x[:, self.cost_layer_filter-1:self.cost_layer_filter+1]) #return -T.sum(self.p_y_given_x[:, self.cost_layer_filter]) #return T.switch(T.le(epoch, 100), -T.sum(self.s_y_given_x[:, self.cost_layer_filter]), -T.sum(self.p_y_given_x[:, self.cost_layer_filter])) return T.switch(T.le(epoch, 3000),#3000#2000#1000 #-T.sum(self.s_y_given_x[:, self.cost_layer_filter]) + T.sum(self.image[:, :, :45, 1]) * 0.5, #-T.sum(self.s_y_given_x[:, self.cost_layer_filter]) + T.sum(self.image[:, :, :45, 1]) * 0.5 / self.image.shape[0].astype(theano.config.floatX), -T.sum(self.s_y_given_x[:, self.cost_layer_filter]) + T.sum(self.image[:, :, :45, 1]) * 0.5, -T.sum(self.p_y_given_x[:, self.cost_layer_filter])) - T.sum( T.sum( self.image * T.log(self.image + 10**-6), axis=1) ) * 0.02 if self.cost_func == 'max_score_GGCC_punish_aruns' : #return -T.sum(self.s_y_given_x[:, self.cost_layer_filter]) + T.sum(self.image[:, :, :50, 1]) * 0.05 #+ T.sum(self.image[:, :, :, 2]) * 0.0005 #return -T.sum(self.p_y_given_x[:, self.cost_layer_filter-1:self.cost_layer_filter+1]) #return -T.sum(self.p_y_given_x[:, self.cost_layer_filter]) #return T.switch(T.le(epoch, 100), -T.sum(self.s_y_given_x[:, self.cost_layer_filter]), -T.sum(self.p_y_given_x[:, self.cost_layer_filter])) return T.switch(T.le(epoch, 3000),#3000#4000#2000#1000 #-T.sum(self.s_y_given_x[:, self.cost_layer_filter]) + T.sum(self.image[:, :, :45, 1]) * 0.5, #-T.sum(self.s_y_given_x[:, self.cost_layer_filter]) + T.sum(self.image[:, :, :45, 1]) * 0.5 / self.image.shape[0].astype(theano.config.floatX) - T.sum(self.image[:, :, 60:90, 1] * self.image[:, :, 59:89, 1]) * 0.01 * T.sum(self.image[:, :, 60:90, 2] * self.image[:, :, 59:89, 2]) / self.image.shape[0].astype(theano.config.floatX), #-T.sum(self.s_y_given_x[:, self.cost_layer_filter]) + T.sum(self.image[:, :, :45, 1]) * 0.5 - T.sum(self.image[:, :, 60:90, 1] * self.image[:, :, 59:89, 1]) * 0.01 * T.sum(self.image[:, :, 60:90, 2] * self.image[:, :, 59:89, 2]), -T.sum(self.s_y_given_x[:, self.cost_layer_filter]) + T.sum(self.image[:, :, :45, 1]) * 0.5 - T.sum(self.image[:, :, 60:90, 1] * self.image[:, :, 59:89, 1]) * 0.017 * T.sum(self.image[:, :, 60:90, 2] * self.image[:, :, 59:89, 2]) + T.sum(self.image[:, :, 55:-1, 0] * self.image[:, :, 56:, 0]) * 0.5, -T.sum(self.p_y_given_x[:, self.cost_layer_filter])) if self.cost_func == 'max_score_punish_aruns' : #return -T.sum(self.s_y_given_x[:, self.cost_layer_filter]) + T.sum(self.image[:, :, :50, 1]) * 0.05 #+ T.sum(self.image[:, :, :, 2]) * 0.0005 #return -T.sum(self.p_y_given_x[:, self.cost_layer_filter-1:self.cost_layer_filter+1]) #return -T.sum(self.p_y_given_x[:, self.cost_layer_filter]) #return T.switch(T.le(epoch, 100), -T.sum(self.s_y_given_x[:, self.cost_layer_filter]), -T.sum(self.p_y_given_x[:, self.cost_layer_filter])) return T.switch(T.le(epoch, 3000),#3000#2000#1000 #-T.sum(self.s_y_given_x[:, self.cost_layer_filter]) + T.sum(self.image[:, :, :45, 1]) * 0.5, #-T.sum(self.s_y_given_x[:, self.cost_layer_filter]) + T.sum(self.image[:, :, :45, 1]) * 0.5 / self.image.shape[0].astype(theano.config.floatX), -T.sum(self.s_y_given_x[:, self.cost_layer_filter]) + T.sum(self.image[:, :, :45, 1]) * 0.5 + T.sum(self.image[:, :, 55:-1, 0] * self.image[:, :, 56:, 0]) * 0.5, -T.sum(self.p_y_given_x[:, self.cost_layer_filter])) if self.cost_func == 'max_score_GGCC' : #return -T.sum(self.s_y_given_x[:, self.cost_layer_filter]) + T.sum(self.image[:, :, :50, 1]) * 0.05 #+ T.sum(self.image[:, :, :, 2]) * 0.0005 #return -T.sum(self.p_y_given_x[:, self.cost_layer_filter-1:self.cost_layer_filter+1]) #return -T.sum(self.p_y_given_x[:, self.cost_layer_filter]) #return T.switch(T.le(epoch, 100), -T.sum(self.s_y_given_x[:, self.cost_layer_filter]), -T.sum(self.p_y_given_x[:, self.cost_layer_filter])) return T.switch(T.le(epoch, 3000),#3000#4000#2000#1000 #-T.sum(self.s_y_given_x[:, self.cost_layer_filter]) + T.sum(self.image[:, :, :45, 1]) * 0.5, #-T.sum(self.s_y_given_x[:, self.cost_layer_filter]) + T.sum(self.image[:, :, :45, 1]) * 0.5 / self.image.shape[0].astype(theano.config.floatX) - T.sum(self.image[:, :, 60:90, 1] * self.image[:, :, 59:89, 1]) * 0.01 * T.sum(self.image[:, :, 60:90, 2] * self.image[:, :, 59:89, 2]) / self.image.shape[0].astype(theano.config.floatX), #-T.sum(self.s_y_given_x[:, self.cost_layer_filter]) + T.sum(self.image[:, :, :45, 1]) * 0.5 - T.sum(self.image[:, :, 60:90, 1] * self.image[:, :, 59:89, 1]) * 0.01 * T.sum(self.image[:, :, 60:90, 2] * self.image[:, :, 59:89, 2]), -T.sum(self.s_y_given_x[:, self.cost_layer_filter]) + T.sum(self.image[:, :, :45, 1]) * 0.5 - T.sum(self.image[:, :, 60:90, 1] * self.image[:, :, 59:89, 1]) * 0.017 * T.sum(self.image[:, :, 60:90, 2] * self.image[:, :, 59:89, 2]), -T.sum(self.p_y_given_x[:, self.cost_layer_filter])) if self.cost_func == 'max_score' : #return -T.sum(self.s_y_given_x[:, self.cost_layer_filter]) + T.sum(self.image[:, :, :50, 1]) * 0.05 #+ T.sum(self.image[:, :, :, 2]) * 0.0005 #return -T.sum(self.p_y_given_x[:, self.cost_layer_filter-1:self.cost_layer_filter+1]) #return -T.sum(self.p_y_given_x[:, self.cost_layer_filter]) #return T.switch(T.le(epoch, 100), -T.sum(self.s_y_given_x[:, self.cost_layer_filter]), -T.sum(self.p_y_given_x[:, self.cost_layer_filter])) return T.switch(T.le(epoch, 3000),#3000#2000#1000 #-T.sum(self.s_y_given_x[:, self.cost_layer_filter]) + T.sum(self.image[:, :, :45, 1]) * 0.5, #-T.sum(self.s_y_given_x[:, self.cost_layer_filter]) + T.sum(self.image[:, :, :45, 1]) * 0.5 / self.image.shape[0].astype(theano.config.floatX), -T.sum(self.s_y_given_x[:, self.cost_layer_filter]) + T.sum(self.image[:, :, :45, 1]) * 0.5, -T.sum(self.p_y_given_x[:, self.cost_layer_filter])) # end-snippet-2 def recall(self): return self.p_y_given_x[:, :] if __name__ == '__main__': #sgd_optimization_mnist() print('cant be main method')
e21891511d8117e865b53113088e37728c694f43
ssarangi/algorithms
/leetcode/word_break.py
2,420
3.765625
4
# https://leetcode.com/problems/word-break/ import unittest # class Solution(object): # def wordBreak(self, s, wordDict): # """ # :type s: str # :type wordDict: Set[str] # :rtype: bool # """ # curr_word = "" # for c in s: # curr_word += c # if curr_word in wordDict: # curr_word = "" # if len(curr_word) > 0: # return False # return True class Solution(object): def wordBreak(self, s, wordDict): """ :type s: str :type wordDict: Set[str] :rtype: bool """ # Initialize all the dp values as 0 dp = [False] * (len(s) + 1) for i in range(1, len(s) + 1): # If dp[i] is false and then check if the current prefix can make it # true prefix = s[0:i] if dp[i] is False and prefix in wordDict: dp[i] = True # if dp[i] is true then check for all substrings starting from i+1 char # and store their result if dp[i] is True: # If we reached the last prefix if i == len(s): return True for j in range(i+1, len(s) + 1): suffix = s[i: j] if dp[j] is False and suffix in wordDict: dp[j] = True # If we reached the last character if j == len(s) and dp[j] is True: return True # Print the DP table # print("\n".join(str(i) for i in dp)) return False class UnitTests(unittest.TestCase): @classmethod def setUpClass(cls): cls.soln = Solution() def testWordBreak(self): self.assertEqual(self.soln.wordBreak("leetcode", {"leet", "code"}), True) self.assertEqual(self.soln.wordBreak("aaaaaaa", {"aaaa", "aaa"}), True) self.assertEqual(self.soln.wordBreak( "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab", {"a", "aa", "aaa", "aaaa", "aaaaa", "aaaaaa", "aaaaaaa", "aaaaaaaa", "aaaaaaaaa", "aaaaaaaaaa"}), False) self.assertEqual(self.soln.wordBreak("abcd", {"a","abc","b","cd"}), True) if __name__ == "__main__": unittest.main()
afa65ed6e9793d3bd7f6f41f559dd0adc02dd3bb
drfengcoding/PythonBeginners
/07_functions/add_function.py
102
3.859375
4
def add(a, b): return a+b def multiply(a, b): return a*b print(add(3,5)) print(multiply(3,5))
1135afe06eb24b58db91e6237c0f5780de55d862
Healthcare-Innovations-GT/common-sessions
/Session1/arrays.py
352
4.25
4
semesters = ['Fall', 'Spring'] # Add values semesters.append('Summer') semesters.append('Spring') print(semesters) # ['Fall', 'Spring', 'Summer', 'Spring'] # Remove values semesters.remove('Spring') print(semesters) # ['Fall', 'Summer', 'Spring'] # Access any value using it's index first_item_in_list = semesters[0] print(first_item_in_list) # Fall
ff411ee3c3fba7a909501deee07adcd63c16ec0b
rakshsain20/ifelse
/raksha.py/n.py
203
3.84375
4
user1=int(input("enter the number")) user2 =int(input("enter the number")) if user1>user2: print("first number gearter") elif user2>user1: print("second number gearter") else: print("equal")
ab745d0e23e3232ad4d615edfac9c67efc15cf6c
t-kostin/python
/lesson-1/lesson1_task2.py
851
4.375
4
# Пользователь вводит время в секундах. # Переведите время в часы, минуты и секунды и выведите в формате чч:мм:сс. # Используйте форматирование строк. time_in_seconds = int(input('Введите время в секундах: ')) hours = time_in_seconds // 3600 minutes = time_in_seconds % 3600 // 60 seconds = time_in_seconds % 3600 % 60 # разные варианты форматирования строк для достижения одинакового результата print('Время ЧЧ:ММ:СС - %02d:%02d:%02d.' % (hours, minutes, seconds)) print('Время ЧЧ:ММ:СС - {:02}:{:02}:{:02}.'.format(hours, minutes, seconds)) print(f'Время ЧЧ:ММ:СС - {hours:02}:{minutes:02}:{seconds:02}.')
1a55d3f3e27bd2b0810702bffd4ba11458ebce44
jochigt87/PYTHONWORKBOOK
/exercise_75.py
679
4.0625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Loop Exercises. # Exercise 75: Greatest Common Divisor. """ The greastest common divisor of two positive integers, n and m, is the largest number, d which divides evenly into both n and m. There are several algorithms that can be used to solve this problem, including: Initialize d to the smallest of m and n. While d does not evenly divide m or d does not evenly divide n do: Decrease the value of d by 1 Report d as the greastest common divisor of n and m. Write a program that reads two positive integers from the user and uses this algorithm to determine and report their greatest common divisor. """
0f1df8ac95491050f599d8a4101730d80b9722d7
simmoncn/ml-class-python
/solutions/ex4/ex4.py
9,678
3.78125
4
import numpy as np import matplotlib.pyplot as plt import scipy.io as sio from scipy import optimize from ex4_utility import * ## Machine Learning Online Class - Exercise 4: Neural Network Learning # Instructions # ------------ # # This file contains code that helps you get started on the # linear exercise. You will need to complete the following functions # in this exericse: # # sigmoidGradient.m # randInitializeWeights.m # nnCostFunction.m # # ==================== All function declaration ==================== def reshape_param(nn_params, input_layer_size, hidden_layer_size, num_labels): # Reshape nn_params back into parameters Theta1 and Theta2 Theta1 = nn_params[:hidden_layer_size * (input_layer_size + 1)] Theta1 = Theta1.reshape((hidden_layer_size, input_layer_size + 1)) Theta2 = nn_params[(hidden_layer_size * (input_layer_size + 1)):] Theta2 = Theta2.reshape((num_labels, hidden_layer_size + 1)) return Theta1, Theta2 def predict(Theta1, Theta2, X): X = np.column_stack((np.ones(m), X)) z2_val = np.dot(X, np.transpose(Theta1)) hiddenLayer = sigmoid(z2_val) hiddenLayer = np.column_stack((np.ones(m), hiddenLayer)) outputLayer = sigmoid(np.dot(hiddenLayer, np.transpose(Theta2))) p = np.argmax(outputLayer, axis=1) + 1 p = p.reshape(-1, 1) return p def sigmoid(z): g = np.zeros(z.shape) g = 1 / (1 + np.exp(-z)) return g def sigmoidGradient(z): g = np.zeros(z.shape) # ============= YOUR CODE HERE ============= # Instructions: Compute the gradient of the sigmoid function at # each value of z (z can be a matrix, vector or scalar) tmp = sigmoid(z) g = tmp * (1 - tmp) # =========================================== return g def randInitializeWeights(L_in, L_out): W = np.zeros((L_out, 1 + L_in)) # ============= YOUR CODE HERE ============= # Instructions: Initialize W randomly so that we break the symmetry while # training the neural network. # Note: The first row of W corresponds to the parameters for the bias units epsilon_init = 0.12 W = np.random.random((L_out, 1 + L_in)) * 2 * epsilon_init - epsilon_init # =========================================== return W def nnCostFunction(nn_params, input_layer_size, hidden_layer_size, num_labels, X, y, lambda_val): m = X.shape[0] J = 0 Theta1, Theta2 = reshape_param(nn_params, input_layer_size, hidden_layer_size, num_labels) # ============= YOUR CODE HERE ============= # Instructions: Complete the following code to calculate the gradient function # by using feedforward and regularization X = np.column_stack((np.ones(m), X)) z2_val = np.dot(X, np.transpose(Theta1)) hiddenLayer = sigmoid(z2_val) hiddenLayer = np.column_stack((np.ones(m), hiddenLayer)) outputLayer = sigmoid(np.dot(hiddenLayer, np.transpose(Theta2))) y_array = np.zeros((m, num_labels)) for i in xrange(m): y_array[i, y[i]-1] = 1 J1 = -y_array * np.log(outputLayer) J2 = (1 - y_array) * np.log(1 - outputLayer) J = np.sum(J1 - J2) / m J += np.sum(np.power(Theta1[:, 1:], 2)) * lambda_val / (2 * m) J += np.sum(np.power(Theta2[:, 1:], 2)) * lambda_val / (2 * m) # =========================================== return J def nnGradFunction(nn_params, input_layer_size, hidden_layer_size, num_labels, X, y, lambda_val): m = X.shape[0] Theta1, Theta2 = reshape_param(nn_params, input_layer_size, hidden_layer_size, num_labels) Theta1_grad = np.zeros(Theta1.shape) Theta2_grad = np.zeros(Theta2.shape) # ============= YOUR CODE HERE ============= # Instructions: Complete the following code to calculate the gradient function # by using backpropagation and regularization X = np.column_stack((np.ones(m), X)) z2_val = np.dot(X, np.transpose(Theta1)) hiddenLayer = sigmoid(z2_val) hiddenLayer = np.column_stack((np.ones(m), hiddenLayer)) outputLayer = sigmoid(np.dot(hiddenLayer, np.transpose(Theta2))) y_array = np.zeros((m, num_labels)) for i in xrange(m): y_array[i, y[i]-1] = 1 error_3 = outputLayer - y_array for t in xrange(m): error_3_col = error_3[t,:].reshape((-1,1)) hiddenLayer_row = np.array([hiddenLayer[t, :]]) z2_val_col = z2_val[t,:].reshape((-1,1)) X_row = np.array([X[t,:]]) Theta2_grad = Theta2_grad + np.dot(error_3_col, hiddenLayer_row) error_2 = np.dot(np.transpose(Theta2), error_3_col) error_2 = error_2[1:] # Remove bias term error_2 = error_2 * sigmoidGradient(z2_val_col) Theta1_grad = Theta1_grad + np.dot(error_2, X_row) Theta1_grad = Theta1_grad / m Theta2_grad = Theta2_grad / m Theta1_grad[:,1:] += Theta1[:,1:] * lambda_val / m Theta2_grad[:,1:] += Theta2[:,1:] * lambda_val / m # =========================================== grad = np.hstack((Theta1_grad.ravel(), Theta2_grad.ravel())) return grad if __name__ == "__main__": plt.close('all') plt.ion() # interactive mode # Setup the parameters you will use for this part of the exercies input_layer_size = 400 # 20x20 Input Images of Digits hidden_layer_size = 25 # 25 hidden units num_labels = 10 # 10 labels, from 1 to 10 # (note that we have mapped "0" to label 10) # ==================== Part 1: Loading and Visualizing Data ==================== print('Loading and Visualizing Data ...') data_file = '../../data/ex4/ex4data1.mat' mat_content = sio.loadmat(data_file) X = mat_content['X'] y = mat_content['y'] m, n = X.shape rand_indices = np.random.permutation(m) sel = X[rand_indices[:100], :] displayData(sel) raw_input('Program paused. Press enter to continue') # =================== Part 2: Loading Parameters =================== print('Loading Saved Neural Network Parameters ...') data_file = '../../data/ex4/ex4weights.mat' mat_content = sio.loadmat(data_file) Theta1 = mat_content['Theta1'] Theta2 = mat_content['Theta2'] nn_params = np.hstack((Theta1.ravel(), Theta2.ravel())) # =================== Part 3: Compute Cost (Feedforward) =================== print('Feedforward Using Neural Network ...') # Weight regularization parameter (we set this to 0 here). lambda_val = 0 J = nnCostFunction(nn_params, input_layer_size, hidden_layer_size, num_labels, X, y, lambda_val) print('Cost at parameters (loaded from ex4weights): %f \n(this value should be about 0.287629)' % J) raw_input('Program paused. Press enter to continue') # =================== Part 4: Implement Regularization =================== print('Checking Cost Function (w/ Regularization) ...') lambda_val = 1 J = nnCostFunction(nn_params, input_layer_size, hidden_layer_size, num_labels, X, y, lambda_val) print('Cost at parameters (loaded from ex4weights): %f \n(this value should be about 0.383770)' % J) raw_input('Program paused. Press enter to continue') # =================== Part 5: Sigmoid Gradient =================== print('Evaluating sigmoid gradient...') g = sigmoidGradient(np.array([1, -0.5, 0, 0.5, 1])) print('Sigmoid gradient evaluated at [1 -0.5 0 0.5 1]:') print(g) raw_input('Program paused. Press enter to continue') # =================== Part 6: Initializing Parameters =================== print('Initializing Neural Network Parameters ...') initial_Theta1 = randInitializeWeights(input_layer_size, hidden_layer_size); initial_Theta2 = randInitializeWeights(hidden_layer_size, num_labels); initial_nn_params = np.hstack((initial_Theta1.ravel(), initial_Theta2.ravel())) # =================== Part 7: Implement Backpropagation =================== print('Checking Backpropagation...') checkNNGradients(None) raw_input('Program paused. Press enter to continue') # =================== Part 8: Implement Regularization =================== print('Checking Backpropagation (w/ Regularization) ...') lambda_val = 3 checkNNGradients(lambda_val) debug_J = nnCostFunction(nn_params, input_layer_size, hidden_layer_size, num_labels, X, y, lambda_val) print('Cost at (fixed) debugging parameters (w/ lambda = 3): %f' % debug_J) print('(this value should be about 0.576051)') raw_input('Program paused. Press enter to continue') # =================== Part 9: Training NN =================== print('Training Neural Network...') lambda_val = 1 costFunc = lambda p : nnCostFunction(p, input_layer_size, hidden_layer_size, num_labels, X, y, lambda_val) gradFunc = lambda p : nnGradFunction(p, input_layer_size, hidden_layer_size, num_labels, X, y, lambda_val) fmin_ret = optimize.fmin_cg(costFunc, initial_nn_params, gradFunc, maxiter=30, full_output=True) nn_params = fmin_ret[0] cost = fmin_ret[1] print('Cost at theta found by fmin: %f' % cost) Theta1, Theta2 = reshape_param(nn_params, input_layer_size, hidden_layer_size, num_labels) raw_input('Program paused. Press enter to continue') # =================== Part 10: Visualize Weights =================== print('Visualizing Neural Network...') plt.figure() displayData(Theta1[:, 1:]) raw_input('Program paused. Press enter to continue') # =================== Part 11: Implement Predict =================== pred = predict(Theta1, Theta2, X); print('Training Set Accuracy: %f' % (np.mean(pred == y) * 100))
e1d78b3a27539316e0c88392576d52ef4db558aa
amnikoo/iust-computational-intelligence-assignments
/HomeWork1/GradientPerceptronForNOR_1B.py
1,159
3.734375
4
import numpy as np from matplotlib import pyplot as plt import math class Perceptron: def __init__(self, train_data, lr=0.2, epoch=10): self.train_data = train_data # type: np.array self.learn_rate = lr # type: float self.epoch = epoch # type: int self.weights = np.random.rand(len(train_data[0]) - 1) self.error_arr = [] def predict(self, data): """ :rtype: int :type data: np.array """ activation = np.dot(data, self.weights) return 1 if activation >= -1 else 0 def train_weight(self): for i in range(self.epoch): for row in self.train_data: error = row[-1] - self.predict(row[:-1]) self.error_arr.append(error ** 2) self.weights += self.learn_rate * error * row[:-1] return self.weights data = np.array([[0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 0]]) p = Perceptron(data, 0.2, 10) w = p.train_weight() plt.scatter([1, 0, 1], [0, 1, 1]) plt.scatter(0, 0, color='red') x1, y1 = [0, -1 / w[1]], [-1 / w[0], 0] plt.plot(x1, y1, marker='o') print('weights : ', w) plt.show()
4c361c140ad6a5e24acef2d19a04a71272090984
siamobeauty/python-lab
/4_dict/dict_1.py
810
3.65625
4
ages = {} def prAge(name): # ages.get可以拿到ages裡面的東西 if ages.get(name): print(name, ages.get(name)) else: print("N/A") def test(): #input()的意思是吃到換行,所以在input1裡面吃到3,轉成數字放進去num裡面 num = int(input()) #連吃三行,從0吃到第一個迴圈是 for i in range(0, num): #開始吃Bob 10 line = input() #tokens得到的是一個被切割的list,在切東西的時候習慣用tokens tokens = line.split() #名字放在0 name = tokens[0] #歲數放在1 age = int(tokens[1]) ages[name] = age print(ages) #print name and age num = int(input()) for i in range(0, num): line = input() prAge(line) test()
43804a62eb2ace8711be285370b7d43c228cbe06
SungHyunShin/Programming-Challenges-Contest
/challengeIF/program.py
1,736
3.75
4
#!/usr/bin/env python3 # Luke Song Andy Shin # problem 1F import sys scores = [2, 3, 7] def score_possible(wanted_score): result = [[] for _ in range(wanted_score + 1)] # result 2d matrix to store result for each score for index in range(1, wanted_score + 1): # iterate scores upto wanted_score for score in scores: # iterate possible score combinations if (index - score) >= 0: if not result[index - score] and (index - score) == 0: # when wanted_score is a intial case like score = 2, score = 3 result[index].append([score]) else: for comb in result[index - score]: # append previous score combination with current score and add to result list comb = sorted(comb + [score]) if comb not in result[index]: result[index].append(comb) return sorted(result[wanted_score]) if __name__ == '__main__': for score in sys.stdin: wanted_score = int(score.strip()) possibility = score_possible(wanted_score) if possibility: if len(possibility) > 1: print("There are {} ways to achieve a score of {}:".format(len(possibility), wanted_score)) else: print("There is 1 way to achieve a score of {}:".format(wanted_score)) # account for grammar diff for comb in possibility: print(' '.join(str(i) for i in comb)) else: print("There are 0 ways to achieve a score of {}:".format(wanted_score))
2fa57058de9a2efd1c11c03000fbb322d5e88b2a
Amarjeet28/Python-Code-Clinic
/setAlarm.py
611
3.828125
4
#Assignment: Program to play the sound file and display the message on a given input time #A method with 3 arguments: time, sound file, message # Key Learnings: # How to use a sound file # import time as t import playsound as ps def setAlarm(inputTime,soundFile,message): t.sleep(inputTime-t.time()) print(message) ps.playsound("./../Input Files/sound.wav") def main(): time = t.time() + 1 soundFile = "alarm.wav" message = "Time to get up you lazy bum!" setAlarm(time,soundFile,message) if __name__ == "__main__": main()
d51514e05b7552a91cdc97ce1df183f600bcc675
ravalrupalj/BrainTeasers
/Edabit/Map_The_letters_in_String.py
875
4.21875
4
#Map the Letters in a String #Given a word, create a dictionary that stores the indexes of each letter in a list. #Make sure the letters are the keys. #Make sure the letters are symbols. #Make sure the indexes are stored in a list and those lists are values. #Notes #All strings given will be lowercase. from collections import defaultdict def map_letters(word): d = {} for char in word: ind = [i for i, a in enumerate(word) if a==char] if char not in d: d[char] = ind return d #return {i:[word.index(i)] for i in word} #return {v:index for index,v in enumerate(word)}# if print(map_letters("dodo") ) #➞ { "d": [0, 2], "o": [1, 3] } print(map_letters("froggy")) #➞ { "f": [0], "r": [1], "o": [2], "g": [3, 4], "y": [5] } print(map_letters("grapes")) #➞ { "g": [0], "r": [1], "a": [2], "p": [3], "e": [4], "s": [5] }
268e7db0ec18c1e90988be43cc4df95067fb9f57
bferrari0617/M013-Project2-Group7
/Simulation.py
8,143
4.0625
4
#ECS 101 Project 2 Group 7 #Simulation.py #made by Bennett Ferrari, Eddie Garcia, Junjie Zheng, and Timothy Liu import random #Bennett Ferrari's part def explore_only() -> int: # creates variable to store happiness values of the three cafes. creates index variable for while loop. h1 = 0 h2 = 0 h3 = 0 i = 0 # visits cafe 1, 2, 3 for 100 days each, generating a new happiness value and adding it to the sum. while i < 100: h1 += random.normalvariate(9, 3) i += 1 while i < 200: h2 += random.normalvariate(7, 5) i += 1 while i < 300: h3 += random.normalvariate(11, 7) i += 1 # returns sum of total happiness of the three cafes across 300 days return int(h1 + h2 + h3) #Eddie Garcia's part def exploitOnly() -> float: # list with three different normal distributions based on given mean and standard deviation, simulating visits to three different cafes on three different days h = [random.normalvariate(9, 3), random.normalvariate(7, 5), random.normalvariate(11, 7)] result = 0 #finds index of the highest happiness value among the three cafes best = h.index(max(h)) # saves of the mean and standard deviation of the best cafe by using the index of the highest happiness value in 'h' if best == 0: m, d = 9, 3 elif best == 1: m, d = 7, 5 else: m, d = 11, 7 # adds happiness values from first three days to result for item in h: result += item # visits the best cafe for 297 days, saving it to result for i in range(297): result += random.normalvariate(m, d) # returns total happiness return result #!/usr/bin/env python3 #ECS 101 #Project 2 part 3 #Timothy Liu‘ #The number provided from class: c1avg = 9 c1std = 3 c2avg = 7 c2std = 5 c3avg = 11 c3std = 7 #Some helper function, return the happiness value each time by using the given num def c1(): return random.normalvariate(c1avg, c1std) def c2(): return random.normalvariate(c2avg, c2std) def c3(): return random.normalvariate(c3avg, c3std) #eGreedy(e) starts here, input: e -> is percentage, e% def eGreedy(e): # First Three day, go to each cafeteria and get the happiness value result = 0 # Result happiness = [] # Empty list to put happy score in happiness.append(c1()) # append happiness into the list happiness.append(c2()) happiness.append(c3()) result += sum(happiness) # add three days' happyiness point # initial int visit times. Initial from one because you already viisted each cafeteria onece c1n = 1 c2n = 1 c3n = 1 # The rest 297 days for i in range(297): # Loop starts here # Generate a random number 0 to 100 r = 100 * random.random() # Generate a random number 0 to 2(0,1,2,3) x = random.randrange(3) # If the random number r is smaller than e, pick a random cafeteria if (r < e): # according the random number x, if x is 0 go to cafeteria one if (x == 0): c1n += 1 # add visit times c1h = c1() # get happiness core using helper function happiness[0] = (happiness[0] + c1h) # modify the happiness score for this cafeteria so far result += c1h # add the happiness score to the total result elif (x == 1): # if random num x is 1, go to the cafeteria two c2n += 1 c2h = c2() happiness[1] = (happiness[1] + c2h) result += c2h else: # the last situation is random num x is three, go to the cafeteria three c3n += 1 c3h = c3() happiness[2] = (happiness[2] + c3h) result += c3h else: # Otherwise, go to the cafeteria earn the best happiness so far y = (max(happiness[0]/c1n,happiness[1]/c2n,happiness[2]/c3n)) # from the happiness list, get the index has the highest number is the best happiness cafeteria so far # If first number is the highest, go to the cafeteria one if (y == happiness[0]/c1n): c1n += 1 # add visit time c1h = c1() # get happiness score by using helper function happiness[0] = (happiness[0] + c1h) # update the happiness score result += c1h # add to result # if the second number is the highest, go to the cafeteria two elif (y == happiness[1]/c2n): c2n += 1 c2h = c2() happiness[1] = (happiness[1] + c2h) result += c2h # The last situation, the last num is the highest in the list, go to the cafeteria three else: c3n += 1 c3h = c3() happiness[2] = (happiness[2] + c3h) result += c3h # Return the happiness score return result #Junjie Zheng's part #simulation(t,e) int t -> is the times of trail; int e -> is the given percentage(0-100) use for eGreedy(e) def simulation(t,e): #The given number for the project, avg num & std diviation c1a = 9 c2a = 7 c3a = 11 c1s = 3 c2s = 5 c3s = 7 # calculate the expect total happiness # n is the times go to each cafeteria during the 300 days n = 300 * (e/100/3) #Optimum happiness Op_happy = 300*(max(c1a,c2a,c3a)) #Calculate the expect total happiness score from given average happiness score ex_explore = 100*c1a + 100*c2a + 100*c3a ex_exploit = c1a + c2a + c3a + 297*(max(c1a,c2a,c3a)) ex_eGreedy = (100-e)/100 * 300 * (max(c1a,c2a,c3a)) + c1a * n + c2a * n + c3a * n #Calculate the regreat by deduct optimum happiness with expect happiness score regret_explore = Op_happy - ex_explore regret_exploit = Op_happy - ex_exploit regret_eGreedy = Op_happy - ex_eGreedy #initial the some integer, initial value is 0 total_explore = 0 total_exploit = 0 total_eGreedy = 0 #initial another integers here, initial value is 0 total_regret1 = 0 total_regret2 = 0 total_regret3 = 0 #for loop #loop runs t times, t is the input value of this function for i in range (0,t): #runs the function wrote by other teamate h1 = explore_only() h2 = exploitOnly() h3 = eGreedy(e) #Add the happiness return by each function to the total num total_explore += h1 total_exploit += h2 total_eGreedy += h3 #Add the regreat total_regret1 += (Op_happy - h1) total_regret2 += (Op_happy - h2) total_regret3 += (Op_happy - h3) #The end of for loop #calculate the average happiness score aver_explore = total_explore / t aver_exploit = total_exploit / t aver_eGreedy = total_eGreedy / t #calculate the average regret score aver_regret1 = total_regret1 / t aver_regret2 = total_regret2 / t aver_regret3 = total_regret3 / t #print results: print("Optimum happiness: ",Op_happy); print("Expected total happiness for Exploit Only: ",round(ex_exploit)); print("Expected total happiness for Explore Only: ", round(ex_explore)); print("Expected total happiness for eGreedy: ", round(ex_eGreedy)); print("Expected regret for Exploit Only: ", round(regret_exploit)); print("Expected regret for Explore Only: ", round(regret_explore)); print("Expected regret for eGreedy: ", round(regret_eGreedy)); print("Average total happiness for Exploit Only: ", round(aver_exploit)); print("Average total happiness for Explore Only: ", round(aver_explore)); print("Average total happiness for eGreedy: ", round(aver_eGreedy)); print("Average regret for Exploit Only: ", round(aver_regret2)); print("Average regret for Explore Only: ", round(aver_regret1)); print("Average regret for eGreedy: ", round(aver_regret3)); print() #The end of simulation() #Print Results: print("trials: 100; e: 12%") simulation(100,12) print("trials: 1000; e: 12%") simulation(1000,12) print("trials: 10,000; e: 12%") simulation(10000,12) print("trials: 100,000; e: 12%") simulation(100000,12)
5ff2cb13285546913201ed48d1d36fd54a9d1def
uncleyao/Leetcode
/009 Palindrome Number.py
510
3.890625
4
""" Determine whether an integer is a palindrome. Do this without extra space. """ class Solution(object): def isPalindrome(self, x): """ :type x: int :rtype: bool """ if x <0: return False div =1 while x/div>= 10: div*=10 while x> 0: l = x//div val = x%10 if l != val: return False x %= div x//=10 div /= 100 return True