blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
1ca46ad068f21f59e39e08836cecd1ef58ed1cad
myoder020/Projects
/Python/Rock, Paper, Scissors/Input.py
917
3.890625
4
import random from collections import defaultdict acceptable = ['r','s','p'] lkp = defaultdict() decision = defaultdict() lkp['s'] = 'Scissors' lkp['r'] = 'Rock' lkp['p'] = 'Paper' decision[('r','s')] = 'Rock beats Scissors' decision[('p','r')] = 'Paper beats Rock' decision[('s','p')] = 'Scissors beat paper' tie = False while True: player = input("rock (r), paper (p), or scissors (s)? ") if player in acceptable: print(player) break else: print('That was not an acceptable choice, Please enter r, p, or s') computer = random.choice(['r','s','p']) print(lkp[player], 'vs', lkp[computer]) if player == computer: print("It's a tie") tie = True result = None if tie == False: try: result = decision[(player, computer)] except KeyError: result = decision[(computer, player)] print(result) #r b s #s b p #p b r
39c7519638942ca0c574768ed1a478f7cdc27295
vandanagarg/practice_python
/learning_python/classes/Cylinder.py
416
3.84375
4
class Cylinder: def __init__(self, radius= 1, height = 1): self.radius = radius self.height = height def volume(self): return self.height * 3.14 * (self.radius**2) def surface_area(self): circle_area = 3.14 * (self.radius**2) return (2* circle_area) + (2* 3.14 * self.radius * self.height) cyl1 = Cylinder(3,2) print(cyl1.volume()) print(cyl1.surface_area())
89a5617c07129da1254d21bcfc142079cda35695
joecai6/lib-search
/parse/parsing.py
3,332
3.71875
4
""" Author: Joe Cai parsing.py parses the inital file containing all the records from the Hathitrust database The whole program only needs certains columns of the records so it parses into another txt file with seven columns instead of 26. This file is only ran once to parse the initial file and from there we create a data frame off of the parsed file. """ import csv import sys catalogSize = 20000000 csv.field_size_limit(catalogSize) print("Hello World. Parsing the inital dataset.") # opens the parsed file to be written to with open('../parsed_data/parsed_file.txt', encoding="utf8", mode='w', newline='') as parsed: # initialize the writer to write to file parsed_writer = csv.writer(parsed, delimiter='\t', quoting=csv.QUOTE_NONE, escapechar='\\') parsed_writer.writerow(['Record #', 'Title', 'Publisher', 'Place', 'Date', 'Author', 'Edition']) # opens the Hathitrust file downloaded from the digital library with open('../parsed_data/hathi_full_20200701.txt', encoding="utf8") as ts_file: # reader that replaces all null values with a empty string, this prevents access null error ts_reader = csv.reader((line.replace('\0','') for line in ts_file), delimiter='\t', quotechar=' ') line = 0 for row in ts_reader: # go through each row of the file if row is None: break # initialize all values to NONE to be detected when searching record = "NONE" title = "NONE" author = "NONE" place = "NONE" edition = "NONE" date = "NONE" publisher = "NONE" accessible = False # Checks if the column exists and if it is non empty for each data if len(row) > 25 and row[25].strip() != "": author = row[25] author = author.replace('\t',' ') if len(row) > 17 and len(row[17]) <= 3 and row[17].strip() != "": place = row[17] place = place.replace('\t',' ') if len(row) > 4 and row[4].strip() != "": edition = row[4] edition = edition.replace('\t',' ') if len(row) > 3 and row[3].strip() != "": record = row[3] record = record.replace('\t',' ') if len(row) > 11 and row[11].strip() != "": title = row[11] title = title.replace('\t',' ') if len(row) > 12 and row[12].strip() != "": publisher = row[12] publisher = publisher.replace('\t',' ') if len(row) > 16 and row[16].strip() !="": date = row[16] date= date.replace('\t',' ') # accessible is true when it can be accessed publicly in the digital library if len(row) > 1 and row[1] == 'allow': accessible = True if accessible: parsed_writer.writerow([record, title, publisher, place, date, author, edition]) line+=1 print("Sucessfully parsed the file\t", "Number of lines:", line) ts_file.close() parsed.close() # add other parsing methods here
698338f26cebe8e06c8bfb1fa0b2e888bc9373f6
baharbrl/basic_python
/hello_ai_101.py
1,217
4.15625
4
#PYTHON101 print("hello ai era") type(9.2) print('hello ai era') "hello ai era" 'hello ai era' type("deneme") #STRINGLERE GIRIS 123 type("123") #tirnak icine alinca bunu strkabul eder. type(123) "a"+"b" #+biraraya getirme anlamindadir. "a"-"b" print("a"+"-b") "a" " b" "a"*3 #cogaltmak anlaminda * kullan. "a"/3 #calismaz #STRING METODLARI = fonksiyon giris #len() gel_yaz= "gelecegi yazanlar" mvk="gelecegi yazanlar" #del mvk len(gel_yaz) len("gelecegi yazanlar") a = 9 b = 10 a*b #upper() lower() isupper() islower() gel_yaz.upper() B=gel_yaz.upper() #GELECEGİ YAZANLAR olarak B degerine atadim. B.islower() #B kucuklerden mi olusuyor sorduk False cikti verdi. #replace() gel_yaz.replace("e","a") A=gel_yaz.replace("e","a") print(A) #strip() gel_yaz.strip() #kirpti bosluga gore X= "*gelecegi yazanlar*" X.strip("*") #kirpti *a gore *lari kirpti. #SUBSTRING gel_yaz[0] gel_yaz[3:7] #3.indeksten basla 7.ye kadar al #TYPE DONUSUMU top_bir=input() top_iki=input() sonuc=int(top_bir)+int(top_iki) print(sonuc) int(11.2) float(12) str(12) #PRINT KULLANIMI print("gelecegi" , "yazanlar" , sep="-") # ?print #fonksiyon hakkinda bilgileri gosterir.
f757d2c37f2aa34aecddc1a867bfc71c6aed57fe
truas/kccs
/python_overview/python_parallel/thread_module_02.py
1,333
4.25
4
import threading class MyThread(threading.Thread): ''' Let us have a proper class to initialize our threads ''' def __init__(self, number): threading.Thread.__init__(self) self.number = number def run(self): """Run the thread""" print(self.getName(), ' Calling doubler') doubler(self.number) def doubler(number): """A function that can be used by a thread""" print('\tdoubler function executing for: %d' %number) result = number * 2 print('\tdoubler function ended with: {}'.format(result)) if __name__ == '__main__': # We are giving names to our threads to identify them thread_names = ['Mike', 'George', 'Wanda', 'Dingbat', 'Nina'] for i in range(5): thread = MyThread(i) # for each value in the range we create a thread thread.setName(thread_names[i]) # name that thread accordingly thread.start() # execute our thread ''' run() … specifies the threads activity, i.e. the instructions it should execute start() … starts the thread’s activity specified in run() join() … blocks the calling thread (typically the main thread) until the thread whose join() method is called terminates ''' #Reference for the code: https://www.blog.pythonlibrary.org/2016/07/28/python-201-a-tutorial-on-threads/ from Michael Driscoll
5dbafcefff627b8c69e15ae50c20b5fa49d9b40b
eronekogin/leetcode
/2021/least_operators_to_express_number.py
1,250
3.578125
4
""" https://leetcode.com/problems/least-operators-to-express-number/ """ class Solution: def leastOpsExpressTarget(self, x: int, target: int) -> int: """ 1. pos[k] stands for the number of opeartors needed to get target % (x ^ (k + 1)), suppose r is the result, then we could add r times (x/x) to achieve that, the number of operators needed will be r * 2, this is because each add will need one plus operator and one divide operator. 2. neg[k] stands for the number of operators needed to get x ^ (k + 1) - (target % (x ^ (k + 1))), suppose r is the result, then we could subtract r times (x/x) to achieve that, the number of opeartor will be r * 2 as each subtract need one subtract operator and one divide operator. """ pos = neg = k = 0 y = target while y: y, r = divmod(y, x) if k: pos, neg = min(r * k + pos, (r + 1) * k + neg), min((x - r) * k + pos, (x - r - 1) * k + neg) else: pos = r << 1 neg = (x - r) << 1 k += 1 return min(pos, k + neg) - 1
d0a2acf109a57ab7841728ccbdfa1909fbe35eb7
anukanab/DataanalysisPythonCodes
/filtercolumns2.py
729
3.515625
4
''' this file filetrs columns of a file based on columns from another file''' import pandas as pd import csv import numpy as np import sys data=pd.read_csv('/data/salomonis2/NCI-R01/TCGA-BREAST-CANCER/Anukana/UO1analysis/tcga_rsem_gene_tpm.txt', sep='\t', index_col=1) print data.head() df=pd.read_csv('/data/salomonis2/NCI-R01/TCGA-BREAST-CANCER/Anukana/patientID_tcga.txt', sep='\t', index_col=0) #print df.head() my_list=df.columns.values.tolist() #converts column headers to list #my_list=list(df) data=data.filter(my_list) print data.shape #data=data[data.iloc[:,2:].isin(my_list)] #print data.shape data.to_csv('/data/salomonis2/NCI-R01/TCGA-BREAST-CANCER/Anukana/UO1analysis/tcga_rsem_gene_tpm_filtered.txt', sep='\t')
117f241a88b4438e56a961a36827c71a50f903a1
fxdgear/dogleg
/dogleg/core/__init__.py
646
3.78125
4
import csv from survey import Survey def load_data(path): """ Given a CSV of data, return a list of dictionaries """ csv_data = csv.reader(open(path, 'rb')) header = csv_data.next() row = csv_data.next() d = dict(zip(header, [float(x) for x in row])) s0 = Survey(d['Depth'], d['Inc'], d['Azi'], d['TVD'], d['EW'], d['NS'], d['Dogleg']) survey_list = [s0] data = [row for row in csv_data] for row in data: d = dict(zip(header, [float(x) for x in row])) sn = survey_list[-1] sn1 = sn.next(d['Depth'], d['Inc'], d['Azi']) survey_list.append(sn1) return survey_list
42fea5b91897d4e847223ae8c8cd24db6a8e50e2
Icedomain/LeetCode
/src/Python/25.k-个一组翻转链表.py
1,101
3.609375
4
# # @lc app=leetcode.cn id=25 lang=python3 # # [25] K 个一组翻转链表 # # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverseKGroup(self, head: ListNode, k: int) -> ListNode: if head is None or k < 2: return head dummy = ListNode(-1) dummy.next = head start , end = dummy, dummy.next count = 1 while end: if count % k == 0: # 返回为新一轮的头 start = self.reverse(start, end.next) end = start.next else: end = end.next count += 1 return dummy.next def reverse(self, start, end): # 输入一个是前驱,一个后驱 prev, cur = start.next, start.next first = cur while cur != end: temp = cur.next cur.next = prev prev = cur cur = temp start.next = prev first.next = end return first
3a3a12cad9a1ec98d88e3114525b3b1467940655
lucasbbs/URI
/1017 - Fuel Spent.py
94
3.515625
4
tripHours = int(input()) averageSpeed = int(input()) print(f'{averageSpeed/12*tripHours:.3f}')
0cd212eb03830cf8bcabc790072ed5185cc6c015
jared10ant/cti110
/P2HW2_TipTaxTotal_TennantJared.py
302
4.09375
4
#CTI-110 #P2HW21 - Tip Tax Total #Jared Tennant #02/12/18 cost = int(input("How much did your meal cost? $")) tip = cost * .18 tax = cost * .07 total = cost + tax print("Based on the cost, you should leave $", tip, "as a tip.") print("The total cost of your meal including sales tax is $", total)
62c6a5c5779cc7d9e3c34254c316a927dfdc583a
MrHamdulay/csc3-capstone
/examples/data/Assignment_3/smtjer002/question3.py
716
4.125
4
# A program to print an input message repeatedly and contain it within a box # Author: Jeremy Smith # Student Number: SMTJER002 message=(input("Enter the message:\n")) length=len(message) count=0 repeat=eval(input("Enter the message repeat count:\n")) framethick=eval(input("Enter the frame thickness:\n")) for i in range(framethick): print("|"*count,"+","-"*(length+2*framethick),"+","|"*count, sep="") if i == framethick - 1: continue count+=1 length-=2 for i in range(repeat): print("|"*framethick, message, "|"*framethick) for i in range(framethick): print("|"*count,"+","-"*(length+2*framethick),"+","|"*count, sep="") count-=1 length+=2
c1b6affd95a86eded70c438d6529deee36c80741
carvillac/PracticasMasterPython
/4_BPP/BPP_Doc/code/dao/CarsDAO.py
2,300
4.09375
4
""" Clase que de acceso a la BD para trabajar con el objeto coche """ import sqlite3 from sqlite3 import Error from model.Car import car class cars_dao: def create(conn): """ Metodo que crea la tabla de coches en BD """ try: sql = """ CREATE TABLE IF NOT EXISTS Cars ( id integer PRIMARY KEY, brand text NOT NULL, model text NOT NULL ); """ c = conn.cursor() c.execute(sql) except Error as e: print(e) def insert(conn, car): """ Metodo que inserta un coche en BD """ sql = """ INSERT INTO Cars (brand, model) VALUES(?,?); """ try: cur = conn.cursor() params = (car.brand, car.model) cur.execute(sql, params) conn.commit() print("DB Message: Car has been added ") return cur.lastrowid except Error as e: print(e) def update(conn, car): """ Metodo que actualiza un coche en BD """ sql = """ UPDATE Cars SET brand = ?, model = ? WHERE id = ? """ try: cur = conn.cursor() params = (car.brand, car.model, car.id) cur.execute(sql, params) conn.commit() print("DB Message: Car has been updated ") except Error as e: print(e) def select_all(conn): """ Metodo que busca todos los coches en BD """ try: cur = conn.cursor() cur.execute(" SELECT * FROM Cars") rows = cur.fetchall() for row in rows: print("DB Message: " + str(row)) except Error as e: print(e) def delete(conn, car): """ Metodo que borra un ccohe en BD """ try: cur = conn.cursor() sql = " DELETE FROM Cars WHERE id = ? " params = (car.id,) cur.execute(sql, params) conn.commit() print("DB Message: Car has been deleted ") except Error as e: print(e)
bfbff93c61864d569edb04155bdbd28e23c64bc5
SkewwG/Python_demo
/demo_magic/demo_get.py
727
4.03125
4
# __get__ 如果class定义了它,则这个class就可以称为descriptor # descriptor作为其他类的属性身份出现的时候,会调用descriptor的__get__ # descriptor实例作为函数调用的时候,触发__call__ class Person: def __get__(self, instance, owner): print("__get__() is called", instance, owner) return '__get__()' def __call__(self, *args, **kwargs): print("__call__() is called") return '__call__()' class Teacher: t = Person() pt = Teacher() print(pt.t) # __get__() is called <__main__.Teacher object at 0x0000000005AEE4E0> <class '__main__.Teacher'> __get__() print(Person()()) # __call__() is called __call__()
d5b9676cbc9cee8d291b6180d23a0a5e806475ca
srmchem/python-samples
/Python-code-snippets-001-100/063-Replace Defined Chars In String.py
543
4.15625
4
''' 63-Replace Defined Chars In String Using Maketrans and translate to replace parts of strings. By Steve Shambles March 2019. For more incompetent code visit: https://stevepython.wordpress.com ''' # Example, make all vowels uppercase. # Change these to anything you want, # but must be same length. replace_these = "aeiou" with_these = "AEIOU" tranny = str.maketrans(replace_these, with_these) text_string = "You can replace any character with any other using maketrans." print(text_string.translate(tranny))
04f819a1abd560f20fd8c1733a8f8b464ba69ef9
guigovedovato/udacity
/Projects/movie_trailer/media.py
1,004
3.796875
4
from imdb import IMDb class Movie(): """This class provides a way to store movie related information""" def __init__(self, movie_title, trailer_youtube_url): """ Inits MovieClass with title and trailer_youtube_url. """ # This class uses the library IMDb for retrieving the data # of the IMDb movie database about movies. # The search is based on movie name and after that by movieID to get # the properly movie information sets like title, image and so on. imdb = IMDb() print("Recovering Movie Data {}".format(movie_title)) movies = imdb.search_movie(movie_title) movie = imdb.get_movie(movies[0].movieID) self.title = movie.get('title') self.poster_image_url = movie.get('full-size cover url') self.rating = movie.get('rating') self.director = movie.get('director')[0] self.storyline = movie.get('plot')[0] self.trailer_youtube_url = trailer_youtube_url
641a19507cd03e20523568015f1ab9a3c361ac00
priyanka-N-Murthy/LeetCode_Exercises
/FizzBuzz.py
331
3.984375
4
def fizzBuzz(n): res=[] i=1 while i<=n: if(i%2==0 and i%3!=0): res.append("Fizz") elif(i%3==0 and i%2!=0): res.append("Buzz") elif(i%2==0 or i%3==0): res.append("FizzBuzz") else: res.append(i) i+=1 return res print fizzBuzz(20)
49a182fd15e8d573c0f1bc55a7f3c1b8ea170a8e
jcloward13/Realm-of-the-King
/GoblinKing/game/maze.py
3,754
3.859375
4
#!/usr/bin/env python3 import random import arcade import timeit import os NATIVE_SPRITE_SIZE = 128 SPRITE_SCALING = 0.25 SPRITE_SIZE = NATIVE_SPRITE_SIZE * SPRITE_SCALING SCREEN_WIDTH = 1000 height = 700 SCREEN_TITLE = "Maze Depth First Example" MOVEMENT_SPEED = 8 TILE_EMPTY = 0 TILE_CRATE = 1 MERGE_SPRITES = True VIEWPORT_MARGIN = 200 class Maze(arcade.SpriteList): def __init__(self, width, height): super().__init__() self.setup(width, height) def setup(self, width, height): # Create the maze maze = self.make_maze_depth_first(width, height) # Create sprites based on 2D grid if not MERGE_SPRITES: # This is the simple-to-understand method. Each grid location # is a sprite. for row in range(height): for column in range(width): if maze[row][column] == 1: wall = arcade.Sprite( "local_resources/brick.png", SPRITE_SCALING ) wall.center_x = column * SPRITE_SIZE + SPRITE_SIZE / 2 wall.center_y = row * SPRITE_SIZE + SPRITE_SIZE / 2 self.append(wall) else: for row in range(height): column = 0 while column < len(maze): while column < len(maze) and maze[row][column] == 0: column += 1 start_column = column while column < len(maze) and maze[row][column] == 1: column += 1 end_column = column - 1 column_count = end_column - start_column + 1 column_mid = (start_column + end_column) / 2 wall = arcade.Sprite( "local_resources/brick.png", SPRITE_SCALING, repeat_count_x=column_count, ) wall.center_x = column_mid * SPRITE_SIZE + SPRITE_SIZE / 2 wall.center_y = row * SPRITE_SIZE + SPRITE_SIZE / 2 wall.width = SPRITE_SIZE * column_count self.append(wall) def _create_grid_with_cells(self, width, height): """Create a grid with empty cells on odd row/column combinations.""" grid = [] for row in range(height): grid.append([]) for column in range(width): if column % 2 == 1 and row % 2 == 1: grid[row].append(TILE_EMPTY) elif ( column == 0 or row == 0 or column == width - 1 or row == height - 1 ): grid[row].append(TILE_CRATE) else: grid[row].append(TILE_CRATE) grid[-2][-3] = TILE_EMPTY grid[1][0] = TILE_EMPTY return grid def make_maze_depth_first(self, maze_width, maze_height): maze = self._create_grid_with_cells(maze_width, maze_height) w = (len(maze[0]) - 1) // 2 h = (len(maze) - 1) // 2 vis = [[0] * w + [1] for _ in range(h)] + [[1] * (w + 1)] def walk(x: int, y: int): vis[y][x] = 1 d = [(x - 1, y), (x, y + 1), (x + 1, y), (x, y - 1)] random.shuffle(d) for (xx, yy) in d: if vis[yy][xx]: continue if xx == x: maze[max(y, yy) * 2][x * 2 + 1] = TILE_EMPTY if yy == y: maze[y * 2 + 1][max(x, xx) * 2] = TILE_EMPTY walk(xx, yy) walk(random.randrange(w), random.randrange(h)) return maze
77e97a1c76708999b1601455936a84b5ed379ba9
syzdemonhunter/Coding_Exercises
/Leetcode/743.py
628
3.75
4
# https://leetcode.com/problems/network-delay-time # https://leetcode.com/problems/network-delay-time/discuss/283711/Python-Bellman-Ford-SPFA-Dijkstra-Floyd-clean-and-easy-to-understand # Time: O(VE) # Space: O(N) class Solution: def networkDelayTime(self, times: List[List[int]], N: int, K: int) -> int: dist = [float('inf') for _ in range(N)] dist[K - 1] = 0 for _ in range(N - 1): for u, v, w in times: if dist[u - 1] + w < dist[v - 1]: dist[v - 1] = dist[u - 1] + w return max(dist) if max(dist) < float('inf') else -1
4fa8e9ecb583140029362adca3bcc87f89661116
dtran39/Programming_Preparation
/01_Arrays/419_Battleship_Board/BattleShipInABoard.py
1,581
4.1875
4
''' Problem: - Given an 2D board, count how many battleships are in it. The battleships are represented with 'X's, empty slots are represented with '.'s. You may assume the following rules: You receive a valid board, made of only battleships or empty slots. Battleships can only be placed horizontally or vertically. In other words, they can only be made of the shape 1xN (1 row, N columns) or Nx1 (N rows, 1 column), where N can be of any size. At least one horizontal or vertical cell separates between two battleships - there are no adjacent battleships. ---------------------------------------------------------------------------------------------------- Examples: Example: X..X ...X ...X In the above board there are 2 battleships. ---------------------------------------------------------------------------------------------------- Solution: - Loop through each cell: + If found a cell with 'X': increase count + If cell on the left or above has 'X': -> already count -> decrease count ''' class Solution(object): def countBattleships(self, board): """ :type board: List[List[str]] :rtype: int """ count = 0 for r in range(len(board)): for c in range(len(board[0])): if board[r][c] == 'X': count += 1 # Track up and left (if has X -> this ship is already counted) if (r > 0 and board[r - 1][c] == 'X') or (c > 0 and board[r][c - 1] == 'X'): count -= 1 return count
8067f132029a9166829da7fcac55d5135967601d
chandraharsha4807/PYTHON--CODING-PROBLEMS
/Rock-paper-scissors.py
812
4.0625
4
''' HandGame ROCK-PAPERS-Scissors''' def Outcome_of_the_game(player1_choice, player2_choice): if player1_choice == player2_choice: print("Tie") elif player1_choice == "Rock" and player2_choice == "Scissors": print("Abhinav Wins") elif player1_choice == "Scissors" and player2_choice == "Paper": print("Abhinav Wins") elif player1_choice == "Paper" and player2_choice == "Rock": print("Abhinav Wins") elif player1_choice == "Scissors" and player2_choice == "Rock": print("Anjali Wins") elif player1_choice == "Paper" and player2_choice == "Scissors": print("Anjali Wins") elif player1_choice == "Rock" and player2_choice == "Paper": print("Anjali Wins") player1_choice = input() player2_choice = input() Outcome_of_the_game(player1_choice, player2_choice)
9c07aec0a051ca9df12da6897b200a484c512a11
songminzh/lifeisshort
/py_codes/039debug.py
582
3.78125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import logging # try try: print('try...') r = 10 / 0 print('result:', r) except ZeroDivisionError as e: print('except:', e) finally: print('finally...') # error def foo(s): return 10 / int(s) def bar(s): return foo(s) * 2 def main(): try: bar('0') except Exception as e: logging.exception(e) main() print('END') class FooError(ValueError): pass def foos(s): n = int(s) if n == 0: raise FooError('invalid value: %s', s) return 10 / n foos('0')
e5b2601c2a39083d6cb0744608496b415e8ffd90
coffeecupee/AnomalyDetection
/gui/menubar.py
1,404
4.03125
4
import tkinter # Lots of tutorials have from tkinter import *, but that is pretty much always a bad idea from tkinter import ttk class Menubar(ttk.Frame): """Builds a menu bar for the top of the main window""" def __init__(self, parent, *args, **kwargs): ''' Constructor''' ttk.Frame.__init__(self, parent, *args, **kwargs) self.root = parent self.init_menubar() def on_exit(self): '''Exits program''' quit() def display_help(self): '''Displays help document''' pass def display_about(self): '''Displays info about program''' pass def init_menubar(self): self.menubar = tkinter.Menu(self.root) self.menu_file = tkinter.Menu(self.menubar) # Creates a "File" menu self.menu_file.add_command(label='Exit', command=self.on_exit) # Adds an option to the menu self.menubar.add_cascade(menu=self.menu_file, label='File') # Adds File menu to the bar. Can also be used to create submenus. self.menu_help = tkinter.Menu(self.menubar) # Creates a "Help" menu self.menu_help.add_command(label='Help', command=self.display_help) self.menu_help.add_command(label='About', command=self.display_about) self.menubar.add_cascade(menu=self.menu_help, label='Help') self.root.config(menu=self.menubar)
1e8db0b23947a8a8322d40c9b7c2d1e3123a4088
Franco414/DASO_C14
/Ejercicios_Extras/Unidad5/Ejercicio_5_5.py
902
3.984375
4
""" Ejercicio 5.5. Algoritmo de Euclides a) Implementar en python el algoritmo de Euclides para calcular el máximo común divisor de dos números n y m, dado por los siguientes pasos. 1. Teniendo n y m, se obtiene r, el resto de la división entera de m/n. 2. Si r es cero, n es el mcd de los valores iniciales. 3. Se reemplaza m ← n, n ← r, y se vuelve al primer paso. b) Hacer un seguimiento del algoritmo implementado para los siguientes pares de números: (15,9); (9,15); (10,8); (12,6). """ from mmap import MAP_EXECUTABLE def obtener_mcd(m,n): mcd=0 continuar=True while(continuar): r=m%n if r==0: mcd=n continuar=False else: m=n n=r return mcd m_u =int(input("Ingrese el numero m")) n_u =int(input("Ingrese el numero n")) res=obtener_mcd(m_u,n_u) print("El mcd de %d y %d es ==> %d"%(m_u,n_u,res))
0e9f62e64c15d19d5181447ecfcf46969a79fce3
vasuudevv/Competitive-Programing-and-DSA
/linked list/llist.py
1,173
3.84375
4
class node: def __init__(self,data): self.data = data self.next = None class llist: def __init__(self): self.head = None def addNode(self,newdata): curr = self.head while(curr.next != None): curr= curr.next new = node(newdata) curr.next = new new.next = None def deleteNode(self,value): temp = self.head curr = self.head if(curr.data == value): self.head = curr.next curr = None return curr = curr.next while(curr.data != value): curr = curr.next temp = temp.next temp.next = curr.next def insertBeg(self,value): curr = node(None) curr.data = value curr.next = self.head self.head = curr def print(self): curr = self.head while(curr != None): print(curr.data) curr = curr.next ll = llist() ll.head = node(1) ll.head.next = node(2) ll.head.next.next = node(3) ll.addNode(4) ll.print() print("***") #ll.deleteNode(1) ll.insertBeg(0) ll.print()
2ee3022ce229abeba45affe70fd6db8e2e9ffced
KaneRoot/notes
/python.py
1,166
3.984375
4
#!/usr/bin/env python Le Python str = "Coucou" str * 2 va donner CoucouCoucou str[1] donne o str[1:4] donne ouc str[-1] donne u str[-2:] donne ou // Donne jusqu'à la fin de la chaîne len(str) donne la longueur de la chaîne str = """ Coucou bla gsgegs geg agqqqh gzge """ if a < 0 : print a Tant qu'il y a des tabulations, on est dans la condition, pas d'accolades b = 2 c = 4 b,c = c,b b donne 4 et c donne 2 suite de fibbo: a,b = 0,1 while b < 500: print b a,b = b, a+b Pas de files, pas de Piles, pas de Tableau : que des LISTES l = ['coucou', 'bla'] l[0] donne coucou l * 2 donne ['coucou', 'bla', 'coucou', 'bla'] str[2] = a donne une erreur ajouter un élément dans la liste l[1:1] = ["bien"] Pour ne rien faire : pass exemple : if a < 0 : pass elif ... for elem in l: print elem def dire_kane(n): for i in range(n): print "kane" range(4,100,10) // Début : 4, de 10 en 10 jusqu'à 100 récupérer une frappe de l'utilisateur en lui demandant quelque-chose stru = raw_input("Super prompt de Kane, tape rien :") if stru in ["Coucou", "bla","bidule"] python.org/doc
366d6e573281427d030d5e4ff36dd239d0db82bc
pratheep96/SpartaJSON
/JSON.py
1,192
3.890625
4
#JSON Javascript Object Notation # Person = { # name: "John", # age: 25, # Speak: function(){ # console.log(name) # } # } #Types of Data inside a JSON file #JSON is a key value system or a large dictionary as we know it in Python # "key" : "value" # A string # A number # An object (JSON object) # An array # A boolean # Null # { # "Trainer1" = { # "name": "markson", # "age" : 25, # "job" : "mechanic", # }, # "Trainer2" = { # "name": "william", # "age" : 40, # "job" : "recruitment", # }, # } import json car_data = {"name": "tesla", "engine": "electric"} # json.dumps() and json.dump() car_data_json_string = json.dumps(car_data) print(car_data_json_string) print(car_data) json_file = open("json_out_alternative.json", "w") #This is an alternative to the statement above with open("json_out_alternative.json", "w") as json_file2: json.dump(car_data, json_file) with open('json_out.json') as open_json_file: electric_car = json.load(open_json_file) print(type(electric_car)) print(electric_car['name']) print(electric_car['engine'])
fda4bb37107b31cb9e7cb73e0d9191778b81ab77
funnydog/AoC2016
/day19/day19.py
1,370
3.765625
4
#!/usr/bin/env python3 import sys def steal_left(elfcount): next = [None] + [0] * elfcount for i in range(1, elfcount): next[i] = i + 1 next[elfcount] = 1 cur = 1 while cur != next[cur]: # current elf steals the gifts on the elf in its left next[cur] = next[next[cur]] cur = next[cur] return cur def steal_opposite(elfcount): next = [None] + [0] * elfcount for i in range(1, elfcount): next[i] = i + 1 next[elfcount] = 1 cur = 1 prev = cur + elfcount//2 - 1 # NOTE: element before the opposite while cur != next[cur]: # steal from the opposite next[prev] = next[next[prev]] elfcount -= 1 # go to the elf at the left cur = next[cur] # advance the opposite only if there is an even number of # elements if elfcount & 1 == 0: prev = next[prev] return cur if __name__ == "__main__": if len(sys.argv) < 2: print("Usage: {} <filename>".format(sys.argv[0]), file=sys.stderr) sys.exit(1) try: with open(sys.argv[1], "rt") as f: elfcount = int(f.readline().strip()) except: print("Cannot open {}".format(sys.argv[1]), file=sys.stderr) sys.exit(1) print("Part1:", steal_left(elfcount)) print("Part2:", steal_opposite(elfcount))
b58f0b9aeb2934b3f6c55904cae645cd27e20481
gustavojoteror/UsingPython4Research
/4_lecture_CaseStudies/01_WhiskyClassifying_Pandas/01_Intro2Pandas.py
2,962
4.21875
4
import numpy as np import pandas as pd #Pandas is a python library that provides data structures and functions for working with structured data, primarily # tabular data. Pandas is built unto of numpy. # Pandas datas structures: Series (1D array like) and DataFrames (2D array like). Both objects contain additional # information about the data called metadata ################################################################################ # Panda series # simple contruction x= pd.Series([6, 3 , 8, 6]) #input is a list of arguments print(x) # Data rray is shown in the right column and the index in the left column which is an array data labels # we didn't define any index explicitly so Pandas took the default: sequence of integers starting at 0 increasin one by one x= pd.Series([6, 3 , 8, 6], index=['q','w','e','r']) #specifying the index explicitly print(x) print(x["w"]) #take just the value from index w print(x[["w", "r"]]) # we give a list of index # contruction with a python dictionary age = {"Tim": 29, "Gus": 31, "Daniela": 29, "Ximena": 6, "Fini": 69} x = pd.Series(age) print(x) # the index of the series are the keys of the dictionary in sorted order and the values are the # value objects in the dictionary ################################################################################ # Panda data frames: represent table like data; they have both row and column index # contructing with a dictionary where the value objects are lists or numpy arrays of equal lengths data = {"name": ['Tim', 'Gus', 'Xime', 'Fini'], "age": [29, 31, 6, 69], "address": ['USA','NL', 'PN', 'VZ']} # the keys are: name, age and address, and the values are the lists of either strings of numbers x = pd.DataFrame(data, columns=['name', 'age', 'address']) # first argument is the data (the dictionary we created) and the # second argument are the columns that we would like to include as well as the order in which they should appear print(x) #again we didn't specify the index so it goes from 0 to 3 x = pd.DataFrame(data, columns=['name', 'age', 'address'], index=['e', 'b', 'x', 'a']) print(x) # retriving data: # 1: By using dictionary like-notation print(x['name']) # 2. We can specify the name of the column as an attritube print(x.age) print(x.index) # re indexing the data ind= sorted(x.index) # alphabetical index print(x.reindex(ind)) ################################################################################ # PArithmetic operations: Series and dataframes # add two series objects together: the data allignment happens by index: entries in the series that have the same # index are added together in the same way as you add twp numpy arrays # IF THE INDICES DO NOT MATCH: NAN will be the result x= pd.Series([6, 3 , 8, 6], index=['q','s','e','r']) y= pd.Series([7, 3 , 5, 2], index=['q','t','e','s']) print(x) print(y) print(x+y)
50b9e75d3637e44cc163d33a440dd5b9b46e74d6
YudinYury/Question_by_HackerRank
/python_functionals.py
6,538
3.90625
4
''' Python question by HackerRank TODO 1: "Validating Email Addresses With a Filter" You are given an integer N followed by N email addresses. Your task is to print a list containing only valid email addresses in lexicographical order. Valid email addresses must follow these rules: It must have the username@websitename.extension format type. The username can only contain letters, digits, dashes and underscores. The website name can only have letters and digits. The maximum length of the extension is 3. Input Format The first line of input is the integer N, the number of email addresses. N lines follow, each containing a string. Constraints: Each line is a non-empty string. Output Format: Output a list containing the valid email addresses in lexicographical order. If the list is empty, just output an empty list, []. # TODO 2: "Reduce Function" Given a list of rational numbers,find their product. Input Format: First line contains N, the number of rational numbers. The i_th of next N lines contain two integers each, the numerator(N_i ) and denominator( D_i ) of the rational number in the list. Constraints: 1 <= N <= 100 1 <= N_i,D_i <= 10**9 Output Format Print only one line containing the numerator and denominator of the product of the numbers in the list in its simplest form, i.e. numerator and denominator have no common divisor other than 1. # TODO 3: "Matrix Script" Neo has a complex matrix script. The matrix script is a N x M grid of strings. It consists of alphanumeric characters, spaces and symbols (!,@,#,$,%,&). To decode the script, Neo needs to read each column and select only the alphanumeric characters and connect them. Neo reads the column from top to bottom and starts reading from the leftmost column. If there are symbols or spaces between two alphanumeric characters of the decoded script, then Neo replaces them with a single space '' for better readability. Neo feels that there is no need to use 'if' conditions for decoding. Alphanumeric characters consist of: [A-Z, a-z, and 0-9]. Input Format The first line contains space-separated integers N (rows) and M (columns) respectively. The next N lines contain the row elements of the matrix script. Constraints: 0 < N,M < 100 Note: A 0 score will be awarded for using 'if' conditions in your code. Output Format Print the decoded matrix script. ''' from fractions import Fraction from functools import reduce import re # TODO 1: "Validating Email Addresses With a Filter" def test_email_consist(s): if s.count('@') == 1 and s.find('@') > 1 and s.find('@') < s.find('.') and s.find('.') < len(s) - 1 and s.find( '.') > len(s) - 5: return True else: return False def test_email_user_name(s): user_name = s[:s.find('@')] test_s = list(filter(lambda x: not (x.isalnum() or x == '-' or x == '_'), user_name)) if test_s: return False else: return True def test_email_host_name(s): host_name = s[s.find('@') + 1:s.find('.')] # print(host_name) test_s = list(filter(lambda x: not x.isalnum(), host_name)) # print(test_s) if test_s: return False else: return True def fun(s): if not test_email_consist(s): return False if not test_email_user_name(s): return False if not test_email_host_name(s): return False return True def filter_mail(emails): return list(filter(fun, emails)) # TODO 2: "Reduce Function" def product(fracs): t = reduce(lambda x, y: x * y, fracs) # complete this line with a reduce statement, [1 2], [3 4], [10 6] # a = Fraction(*[int(x) for x in input().lstrip().rstrip().split()]) # b = Fraction(*[int(x) for x in input().lstrip().rstrip().split()]) # c = a*b # print(c.numerator, c.denominator) return t.numerator, t.denominator # TODO 3: "Matrix Script" def list_to_row_column_and_reverse(source_list, row, column): new_matrix = [] # for i in (range(0, column)): # new_matrix.append(source_list[i::column]) new_matrix = [source_list[x::column] for x in [i for i in range(0, column)]] return new_matrix def matrix_to_string(matrix): # new_string = ''.join([''.join(x) for x in matrix]) new_list = [''.join(x) for x in matrix] new_string = ''.join(new_list) return new_string def matrix_script(): matrix = [] result_string = '' number_of_row, number_of_column = list(map(int, input().split())) # print('number_of_column =', number_of_column, ',', 'number_of_row =', number_of_row) for i in range(number_of_row): row = [x for x in input()] for v in row[:number_of_column]: matrix.append(v) # matrix = list_to_row_column_and_reverse(matrix, number_of_row, number_of_column) matrix = [matrix[x::number_of_column] for x in [i for i in range(0, number_of_column)]] # unfiltered_string = matrix_to_string(matrix) new_list = [''.join(x) for x in matrix] unfiltered_string = ''.join(new_list) alnum_list = list(filter(lambda x: x.isalnum(), [x for x in unfiltered_string])) try: first_alnum = alnum_list[0] except IndexError: result_string = unfiltered_string else: last_alnum_index = unfiltered_string.rfind(alnum_list.pop()) first_alnum_index = unfiltered_string.find(first_alnum) template_i = ['$', '#', '%', '!', '@', '&', ' ', ' '] # !,@,#,$,%,& template_for_reduce = list(zip(template_i, [' '] * len(template_i))) result_string = unfiltered_string[first_alnum_index:last_alnum_index + 1:] result_string = reduce(lambda x, y: x.replace(*y), template_for_reduce, result_string) result_string = unfiltered_string[:first_alnum_index] + result_string + unfiltered_string[ last_alnum_index + 1::] finally: print(result_string) def fibonacci(n): # return a list of fibonacci numbers new_list = [] if n == 0: return new_list new_list.append(0) if n == 1: return new_list new_list.append(1) if n == 2: return new_list for _ in range(n - 2): k1 = new_list.pop() k2 = new_list.pop() new_list.append(k2) new_list.append(k1) new_list.append(k1 + k2) return new_list def main(): # matrix_script() cube = list(map(lambda x: x ** 3, fibonacci(int(input())))) # complete the lambda function print(cube) if __name__ == '__main__': main()
8b9b9933ad552fb93e4093f0e3c802878e7cdd2e
elephantebae/PythonStack
/funcationbasic2.py
1,863
4.4375
4
# Print and Return - Create a function that will receive a list with two numbers. Print the first value and return the second. # def countDown(num): # arr = [] # while num >= 0: # arr.append(num) # num -= 1 # print(arr) # countDown(5) # First Plus Length - Create a function that accepts a list and returns the sum of the first value in the list plus the list's length. # Example: first_plus_length([1,2,3,4,5]) should return 6 (first value: 1 + length: 5) # def first_plus_length(a): # for i in a: # return a[0] + (len(a)) # x = first_plus_length([1,2,3,4,5]) # print(x) # Values Greater than Second - Write a function that accepts a list and creates a new list # containing only the values from the original list that are greater than its 2nd value. # Print how many values this is and then return the new list. If the list has less than 2 elements, have the function return False # Example: values_greater_than_second([5,2,3,2,1,4]) should print 3 and return [5,3,4] # Example: values_greater_than_second([3]) should return False # def values_greater_than_second(a): # newa = [] # for num in range(0, len(a), 1): # if (a[num]> a[1]): # newa.append(a[num]) # print(len(newa)) # return newa # print (values_greater_than_second([5,2,3,2,1,4])) # This Length, That Value - Write a function that accepts two integers as parameters: size and value. # The function should create and return a list whose length is equal to the given size, and whose values are all the given value. # Example: length_and_value(4,7) should return [7,7,7,7] # Example: length_and_value(6,2) should return [2,2,2,2,2,2] # def length_and_value(size,value): # newlist = [] # while len(newlist) < size: # newlist.append(value) # return newlist # print (length_and_value(6,2))
3a9ec666ea9397894eaa59c3a75b0153209425af
Mr-ari/Python-Programs
/Name_codechef.py
1,236
4.375
4
"""A name can have at most three parts: first name, middle name and last name. It will have at least one part. The last name is always present. The rules of formatting a name are very simple: Only the first letter of each part of the name should be capital. All the parts of the name except the last part should be represented by only two characters. The first character should be the first letter of the part and should be capitalized. The second character should be ".". """ test = int(input()) for i in range(0,test): string= input() output="" split_name= string.split() if len(split_name) ==1 : output=output+split_name[0][0].upper() for i in range(1,len(split_name[0])): output=output + split_name[0][i].lower() else: for i in range(0,len(split_name)): if i==len(split_name)-1: output=output+split_name[len(split_name)-1][0].upper() for j in range(1,len(split_name[0])): output=output + split_name[0][j].lower() else: output = output+split_name[i][0].upper()+". " print(output)
d7398f61c19bae635c34a9b8551e46762ea5f1a0
codebubb/python_course
/Semester 1/Project submissions/Lee Eldridge/Excercise Weeks 1-9 - Lee Eldridge/Week 3/times_tables.py
770
4.0625
4
print "Welcome to the times table generator! \n" def p(): times_table = raw_input("Which times tables would you like to see? ") if times_table.isdigit() == False: print "Please enter a number." p() else: times_table = int(times_table) total = raw_input("Okay, What would you like your times tables to go up to? ") if total.isdigit() == False: print "Please enter a number." p() else: total = int(total) print "" for x in range(1, total +1): print x, "x", times_table, " = ", x * times_table print "" print "This is the %s times tables which go up to %s." % (times_table, total) print "" print "Now choose your next times tables..." p() p()
f6ce9c4fe2aede9cf5a2c0aae33d84490ab1a150
MiguelChichorro/PythonExercises
/World 2/For/ex054 - Majority Group.py
694
3.859375
4
from datetime import date colors = {"clean": "\033[m", "red": "\033[31m", "green": "\033[32m", "yellow": "\033[33m", "blue": "\033[34m", "purple": "\033[35m", "cian": "\033[36m"} today = date.today().year old = 0 new = 0 for c in range(1, 8): major = int(input("Enter seven birthday yeras: ")) age = today - major if age >= 21: old += 1 else: new += 1 print("{}In the ages you enter {} {} minor and {} {} older{}" .format(colors["purple"], new, "person is" if new == 1 else "people are", old, "person is" if old == 1 else "people are", colors["clean"]))
065c45240f707f68843ecc87d834827e28e55be9
lly102799-git/python-cookbook
/第2章 字符串和文本/2.2 在字符串的开头或结尾处做文本匹配/string_start_end_match.py
1,265
3.609375
4
# -*- coding: utf-8 -*- """ @project: Python Cookbook @date: 2020-10-20 18:57 @author: Li Luyao """ # 在字符串的开头或结尾按照指定的文本模式做检查,比如检查文件的扩展名 # str.startswith()、str.endswith() filename = 'spam.txt' print(filename.endswith('.txt')) print(filename.startswith('file:')) url = 'http://www.python.com' print(url.startswith('http:')) # 针对多个选项做检查,需要提供包含可能选项的元组; 如果多个备选项不是元组,要确保使用tuple()将其转换为元组 import os filenames = os.listdir('F:\规划设计运营管理-李路遥\数据、程序及仿真结果\工商居负荷评估小工具') docs = [name for name in filenames if name.endswith(('.m', '.txt'))] print(docs) print(any(name.endswith('.py') for name in filenames)) from urllib.request import urlopen def read_data(name): if name.startswith(('http:', 'https:', 'ftp')): return urlopen(name).read else: with open(name) as f: return f.read() # 和其他操作结合使用 from os import listdir dirname = r'F:\规划设计运营管理-李路遥\数据、程序及仿真结果\工商居负荷评估小工具' any(name.endswith(('.c', '.py', '.m')) for name in listdir(dirname))
a9111fc2fcff15bbefd5a2b7def6761867f7273f
ananiastnj/PythonLearnings
/LearningPrograms/RemoveDupListObj.py
510
3.6875
4
l1 = [] n = int(input("Enter list length : ")) for i in range(n): l1.append(int(input("Enter a number : "))) print(l1) for i in l1[:]: print(" I : ", i) count = l1.count(i) print("Count : ",count) if count > 1 : del l1[] print(l1) ''' for i in range(n): for j in range(1,n-i): print("l1[", i, "] == [", j, "] : ",l1[i], "== ",l1[j]) if l1[i] == l1[j]: l1.pop(j) print(l1) ''' #Method 1 dict1={} l2 = dict1.fromkeys(l1).keys() print(l2)
6ee49b29a7ce70958f9b0f677b756a1b898aaba3
vijay-guntireddy/OOP_Using_Python
/Text and Log Parsing/example.py
308
4.125
4
import re regex = input("Enter Pattern :") pattern = re.compile(regex) while True: data = input("Enter String:") m = pattern.search(data) # searches entire string for the pattern if m: print("match found") print(" ",m.span(),m.group()) else: print("match not found")
01faf60ac7ad25952a81b888db54855933488775
karthicwin/Python
/Test.py
1,254
3.5625
4
import requests import time from bs4 import BeautifulSoup # Set the URL you want to webscrape from url = 'http://web.mta.info/developers/turnstile.html' # Connect to the URL response = requests.get(url) # Parse HTML and save to BeautifulSoup object¶ soup = BeautifulSoup(response.text, "html.parser") # To download the whole data set, let's do a for loop through all a tags for i in range(1,len(soup.findAll('a'))+1): #'a' tags are for links one_a_tag = soup.findAll('a')[i] link = one_a_tag['href'] response1 = requests.get(link) soup1 = BeautifulSoup(response.text, "html.parser") for i in range(1,len(soup1.findAll('a'))+1): #'a' tags are for links one_a_tag1 = soup1.findAll('a')[i] link1 = one_a_tag1['href'] download_url1 = one_a_tag1['href'] #link = one_a_tag['href'] # download_url = 'http://web.mta.info/developers/'+ link x = requests.get(download_url1,'./'+link1[link1.find('/turnstile_')+1:]) print(x.text) time.sleep(1) #pause the code for a sec #https://towardsdatascience.com/how-to-web-scrape-with-python-in-4-minutes-bc49186a8460
bb4cb383133ee36ddbb53c5640176f8e4660ca83
MrNullPointer/AlgoandDS
/Udacity_NanoDegree/Data_structures_Revisited/PascalsTriangle.py
1,027
3.734375
4
def nth_row_pascal(n): # base case if n < 2: return [1 for _ in range(n+1)] curr_list = [1 for _ in range(n+1)] prev_list = nth_row_pascal(n-1) first = 0 second = first + 1 for value in range(1,n): curr_list[value] = prev_list[first] + prev_list[second] first = first+1 second = second + 1 return curr_list pascal_triangle = nth_row_pascal(180) print(pascal_triangle) def test_function(test_case): n = test_case[0] solution = test_case[1] output = nth_row_pascal(n) if solution == output: print("Pass") else: print("Fail") n = 0 solution = [1] test_case = [n, solution] test_function(test_case) n = 1 solution = [1, 1] test_case = [n, solution] test_function(test_case) n = 2 solution = [1, 2, 1] test_case = [n, solution] test_function(test_case) n = 3 solution = [1, 3, 3, 1] test_case = [n, solution] test_function(test_case) n = 4 solution = [1, 4, 6, 4, 1] test_case = [n, solution] test_function(test_case)
93a73ac9925ec1bba733058350332ca09036e3a8
nkyono/PE
/lvl_02/prob_057/prob57.py
1,930
3.84375
4
''' It is possible to show that the square root of two can be expressed as an infinite continued fraction. In the first one-thousand expansions, how many fractions contain a numerator with more digits than the denominator? ''' import fractions # long division?, gives different expansions def calcIterLong(lim): exp = 1 strRes = "1" remain = 100 num = 0 denom = 0 for x in range(lim): curr = str(int(strRes) * 2) i = 1 print("Exp: ", x) print("Numerator: ", remain) num = remain while(i < 10): prod = int(curr+str(i)) * i if prod < remain: i = i + 1 else: i = i - 1 prod = int(curr+str(i)) * i print("Denominator: ", prod) denom = prod remain = int(str(remain - prod) + "00") strRes = strRes + str(i) break i = 1 print("Decimal: ", num/denom) print("Fraction: ", float.as_integer_ratio(num/denom)) print("---------") # recursive hits depth limit def recurv(n): if (n == 0): return (1.0/(2 + 1/2)) else: return (1.0/(2 + recurv(n-1))) # noticed pattern of (n-1)*2 + (n-2) def calcIterFracs(lim): total = 0 res = 1.0 base = 1.0/(2 + 1/2) fracs = {} fracs[1] = [3,2] fracs[2] = [7,5] for x in range(3,lim): fracs[x] = [(fracs[x-1][0] * 2 + fracs[x-2][0]), (fracs[x-1][1] * 2 + fracs[x-2][1])] if len(str(fracs[x][0])) > len(str(fracs[x][1])): total = total + 1 for x in fracs: print("Expansion:",x) print("Fraction:",fracs[x]) print("total:", total) def test(): # calcIterLong(10) calcIterFracs(1000) if __name__ == '__main__': import time start = time.time() test() print("time recursive:",time.time()-start)
bdf2aa41959bfc4c563efebaccdbd76e82b3938e
lbhsos/AlgoStudy
/백준/Silver/1182. 부분수열의 합/부분수열의 합.py
356
3.5
4
from itertools import combinations N, S = map(int, input().split(" ")) numbers = list(map(int, input().split(" "))) answer = 0 def get_combination(count): global S, answer for combination in list(combinations(numbers, count)): if sum(combination) == S: answer += 1 for i in range(1,N+1): get_combination(i) print(answer)
33850c8944adc6faa72c576707201e851914e39a
Ayu-99/python2
/session10(d).py
305
3.5
4
file = open("session10.py","r") line = file.readline() print(line) line = file.readline() print(line) line = file.readline() print(line) line = file.readline() print(line) lines = file.readlines() print(lines) print(type(lines)) # List of all the lines in a file for line in lines: print(line)
13bb0d8ad79fd7af4c5fe4e18461568a657f53f9
fs2600/minihcc4
/minihcc4.py
619
3.953125
4
#!/usr/bin/env python # 3***00 numbers = [6,5,1987] multnumbers = [] for number in numbers: #print number * numbers[0] multnumbers.append(number * numbers[0]) multnumbers.append(number * numbers[1]) multnumbers.append(number * numbers[2]) nodupNumbers = list(set(multnumbers)) productListSum = 0 for number in nodupNumbers: productListSum += number catNumbers = 651987 answer = ((productListSum * catNumbers * (25*12)) / 549932400) * 2600 print "answer" print answer #find product of the productlist sum * the new integer * <the number of meetings in 25 years> #divide by 549932400 #multiply that by 2600
670f3ad1e7ee45e654703e4dc922bc65814a4f29
dhirwa/Programming-Problems
/prob6/prob6.py
555
3.8125
4
from random import randrange def generateList(num): arrayy=[] array=[] if num > 40: for i in range(40, num+1): if i % 2 !=0: arrayy.append(i) return arrayy else: for i in range(0,num+1): if i % 2 !=0: array.append(i) return array def reverse(lst): reverse_list = [] for i in reversed(lst): reverse_list.append(i) return reverse_list numb = randrange(100) print("number is {0}".format(numb)) print(reverse(generateList(numb)))
c99ca5bc87c61542ae374831c8f5c79c2190c12a
vishalpmittal/practice-fun
/funNLearn/src/main/java/dsAlgo/sort/InsertionSort.py
537
3.90625
4
""" Tag: sort """ from typing import List class Solution: def insertion_sort(self, A: List[int]) -> List[int]: """ Just like sorting playing cards in our hands """ for i in range(1, len(A)): key = A[i] j = i - 1 while j >= 0 and key < A[j]: A[j + 1] = A[j] j -= 1 A[j + 1] = key return A assert Solution().insertion_sort([3, 2, 9, 3, 5, 7, 1, 8]) == [1, 2, 3, 3, 5, 7, 8, 9] print("Tests Passed!")
0d3353877d9da692cbdd0feb0b5f17afcd98ae9c
Sanglm2207/python-sample
/main6.py
245
3.9375
4
str = str(input()) # def longstr(str): # lst = [] # for v in str.split(" "): # if len(v) > 3: # lst.append(v) # return lst def longstr(str): print([i for i in str.split(" ") if len(i) > 3]) longstr(str)
282f1eedd28aab7a81781fa9f83aea34f082b626
ilnesterenko/G117.DZ
/dz3/2.py
261
3.96875
4
A = int(input("A: ")) B = int(input("B: ")) while A < B: A = A + B print('Значение A:', A) if A < B: print('Пока что нет') else: print('Дождались') print('Финальный А:', A)
f975429c8bbb42061fffdfc1cae249e50b54fbdf
wpj-cz/Spritemapper
/spritecss/stitch.py
3,522
3.5625
4
"""Builds a spritemap image from a set of sprites.""" from array import array from itertools import izip, chain, repeat from .image import Image class StitchedSpriteNodes(object): """An iterable that yields the image data rows of a tree of sprite nodes. Suitable for writing to an image. """ def __init__(self, root, bitdepth=8, planes=3): bc = "BH"[bitdepth > 8] self.root = root self.bitdepth = bitdepth self.planes = planes self._mkarray = lambda *a: array(bc, *a) def __iter__(self): return self.iter_rows(self.root) def _trans_pixels(self, num): return self._mkarray([0] * self.planes) * num def _pad_trans(self, rows, n): padded_rows = chain(rows, repeat(self._trans_pixels(n.width))) for idx, row in izip(xrange(n.height), padded_rows): yield row + self._trans_pixels(n.width - (len(row) / self.planes)) def iter_empty_rows(self, n): return (self._trans_pixels(n.width) for i in xrange(n.height)) def iter_rows_stitch(self, a, b): (rows_a, rows_b) = (self.iter_rows(a), self.iter_rows(b)) if a.x1 == b.x1 and a.x2 == b.x2: return chain(rows_a, rows_b) elif a.y1 == b.y1 and a.y2 == b.y2: return (a + b for (a, b) in izip(rows_a, rows_b)) else: raise ValueError("nodes %r and %r are not adjacent" % (a, b)) def iter_rows(self, n): if hasattr(n, "children"): num_child = len(n.children) if num_child == 1: return self._pad_trans(self.iter_rows(*n.children), n) elif num_child == 2: return self.iter_rows_stitch(*n.children) else: # we can't sow together more than binary boxes because that would # entail very complicated algorithms :< raise ValueError("node %r has too many children" % (n,)) elif hasattr(n, "box"): return self._pad_trans(n.box.im.pixels, n) else: return self.iter_empty_rows(n) def stitch(packed, mode="RGBA", reusable=False): assert mode == "RGBA" # TODO Support other modes than RGBA root = packed.tree bd = max(sn.im.bitdepth for (pos, sn) in packed.placements) meta = {"bitdepth": bd, "alpha": True} planes = 3 + int(meta["alpha"]) pixels = StitchedSpriteNodes(root, bitdepth=bd, planes=planes) if reusable: pixels = list(pixels) return Image(root.width, root.height, pixels, meta) def _pack_and_stitch(smap_fn, sprites, conf=None): import sys # pack boxes from .packing import PackedBoxes, dump_placements, print_packed_size print >>sys.stderr, "packing sprites for map", smap_fn packed = PackedBoxes(sprites) print_packed_size(packed, out=sys.stderr) dump_placements(packed) # write map img_fname = smap_fn + ".png" print >>sys.stderr, "writing spritemap image", img_fname im = stitch(packed) with open(img_fname, "wb") as fp: im.save(fp) def main(fnames=None): import sys import json from .packing.sprites import open_sprites if not fnames: fnames = sys.argv[1:] or ["-"] for fname in fnames: with sys.stdin if (fname == "-") else open(fname, "rb") as fp: for (smap_fn, sprite_fns) in json.load(fp): with open_sprites(sprite_fns) as sprites: _pack_and_stitch(smap_fn, sprites) if __name__ == "__main__": main()
9227a67b5c048f029a85a0a64b5fc3e8b052e70d
zaid-sayyed602/Python-Basics
/if else_9.py
434
3.71875
4
no1=int(input("enter the value for no1 :")) no2=int(input("enter the value for no2 :")) print("1.ADD2.SUB3.MUL4.DIV") choice=int(input("enter your choice")) if(choice==1): c=no1+no2 print("addition is ",c) if(choice==2): c=no1-no2 print("substraction is ",c) if(choice==3): c=no1*no2 print("multipication is ",c) if(choice==4): c=no1/no2 print("division is ",c)
f8387e717cd78b99023a89b2ffd40c173c30d927
trungtaba/leetcode
/Count Sorted Vowel Strings/main.py
449
3.5625
4
# https://leetcode.com/problems/count-sorted-vowel-strings/description/ def countVowelStrings(n): result = {0: [0], 1: [5], 2: [1, 2, 3, 4, 5]} def dfs(k): if k in result: return result.get(k) prev = dfs(k - 1) print(prev) for i in range(1, len(prev)): prev[i] += prev[i - 1] print(prev[i - 1]) return prev return sum(dfs(n)) print(countVowelStrings(3))
0d8d488b8f6f6b108aef46c6fb6b4737395b5f75
kamvegwij/KamveGwij-PersonalProj
/better_range.py
831
4.125
4
def my_range(n, e, s, m=1, view='No'): # m means it'll multiply each value by given value: my_range(0, 11, 1, 2) --> 0*2..1*2..2*2... list1 = [] # m = 1 and view = 'No' because if not given when calling list2 = [] # the program won't crash as these are their default values start = n while start < e: list1.append(start) result = start * m # new positional arg "m" start += s list2.append(result) if view == 'Yes': for i in list1: print(i) for k in list2: print("\t", "\t", "Multiples are as follows: {}.".format(k)) else: pass return list1, list2 the_view = input("Do you want to view the list in a ordered way?: ") print(my_range(0, 11, 2, 2, the_view.capitalize()))
4d576b4e47ff46fbaec49cf0f144b23eb8333a0a
alonShevach/introduction-to-CS
/ex5/wordsearch.py
10,501
4.15625
4
################################################################# # FILE : wordsearch.py # # EXERCISE : intro2cs1 ex5 2018-2019 # # DESCRIPTION: A program that runs the known word search on a # # matrix chosen by user, and that is running from commandline # ################################################################# import sys import os.path THE_CORRECT_DIRECTIONS = 'udlrwxyz' BAD_NUMBER_OF_ARGS = 'the function did not recieve the right ' \ 'amount of arguments, reviewed more than 4, or less than 4' EXPECTED_NUM_OF_ARGS = 4 BAD_DIRECTIONS = "directions should be one or more of " \ "the following letters:" \ "'u','d','l','r','w','x','y','z', the " \ "choice was not a combination of those letters." BAD_WORD_FILE_INPUT = "file missing :the word_list file " \ "is missing, or his name or path are not spelled right. " BAD_MATRIX_FILE = "file missing :the matrix file " \ "is missing, or his name or path are not spelled right. " UP = 'u' DOWN = 'd' LEFT = 'l' DOWN_RIGHT = 'y' DOWN_LEFT = 'z' UP_RIGHT = 'w' UP_LEFT = 'x' def main(args): """The main function that runs all the other functions for the word search the function is getting the 'args' which the user printed in the shell/cmd""" msg = check_input_args(args) # Msg is None when all the args are as we expected, if not, we cant play the game. if msg is not None: return word_list_filename = args[0] mat_filename = args[1] output_filename = args[2] directions = args[3] matrix = read_matrix_file(mat_filename) word_list = read_wordlist_file(word_list_filename) results = find_words_in_matrix(word_list, matrix, directions) write_output_file(results, output_filename) def check_input_args(args): """A function to check the input args that the user printed in the shell/cmd. the expected args are 2 existing files, name of a newfile to create, and 1 or more from the 'direction' letters 'THE_CORRECT_DIRECTIONS'""" if len(args) != EXPECTED_NUM_OF_ARGS: return BAD_NUMBER_OF_ARGS # This function checks if the file exists, if not, the game stops and giving the # Bad file note if not os.path.isfile(args[0]): return BAD_WORD_FILE_INPUT if not os.path.isfile(args[1]): return BAD_MATRIX_FILE for i in range(len(args[3])): # Directions must be 1 of the 8 if not args[3][i] in THE_CORRECT_DIRECTIONS: return BAD_DIRECTIONS return None def read_wordlist_file(filename): """A function for reading the given wordlist file.""" f = open(filename) word_list = f.read().splitlines() f.close() return word_list def read_matrix_file(filename): """A function to read the given matrix file""" f = open(filename) matrix = [] file_input = f.read().splitlines() for word in file_input: letter_lst = word.split(',') # Creating the matrix without the ',' matrix.append(letter_lst) f.close() return matrix def find_words_in_matrix(word_list, matrix, directions): """The function finds the words in the matrix, using another function which runs the search with given directions, this function returns the results of the searches.""" results = [] word_count = 0 # Remove duplicates by inserting the list to set, and converting it back to list no_duplicates_directions = list(set(directions)) if (not matrix) or (not word_list) or (not no_duplicates_directions): return results for word in word_list: for direction in no_duplicates_directions: # The "find_words_with_direction function will count # The number of times a 'word' appeared in the given directions. word_count += find_word_with_direction(word, matrix, direction) # If this is the last direction given, we would like to add the # Number of times he appeared in all the directions to the results list. if direction == no_duplicates_directions[-1]: # If he did not find we should not add anything to the list. if word_count == 0: continue results.append((word, word_count)) # Resetting the count for the new word. word_count = 0 return results def write_output_file(results, output_filename): """A function to create and write an output file with all the results of the word search""" f = open(output_filename, 'w') if not results: f.close() return for word, count in results: f.write(word + ',' + str(count) + '\n') f.close() def find_word_with_direction(word, matrix, direction): """Finding the word from the matrix with the given directions. diverting the matrix to the right angle for the direction to become like it is from left to right. i used all the functions to rotate the matrix into the right position.""" count = 0 new_matrix = matrix[:] if direction == DOWN: new_matrix = create_line_for_downwards(matrix) elif direction == LEFT: new_matrix = reverse_matrix_lines(matrix) elif direction == UP: new_matrix = matrix_turn_upside_down(matrix) new_matrix = create_line_for_downwards(new_matrix) elif direction == DOWN_RIGHT: new_matrix = create_full_diagonal_matrix(matrix) elif direction == UP_LEFT: new_matrix = reverse_whole_matrix(matrix) new_matrix = create_full_diagonal_matrix(new_matrix) elif direction == UP_RIGHT: new_matrix = matrix_turn_upside_down(matrix) new_matrix = create_full_diagonal_matrix(new_matrix) elif direction == DOWN_LEFT: new_matrix = reverse_matrix_lines(matrix) new_matrix = create_full_diagonal_matrix(new_matrix) # Counting the times a word occurs from the new matrix(all direction become # From left to right count += find_word_from_left_to_right_in_matrix(word, new_matrix) return count ### Helper Functions ### def create_line_for_downwards(matrix): """The function creates a list of the downwards line of the matrix.""" downwards_lines = [] temporary_list = [] for i in range(len(matrix[0])): for line in matrix: temporary_list.append(line[i]) if len(temporary_list) == len(matrix): downwards_lines.append(temporary_list) temporary_list = [] return downwards_lines def reverse_matrix_lines(matrix): """A function to reverse all the lines in the matrix""" reversed_matrix = [] for line in matrix: reversed_matrix.append(line[::-1]) return reversed_matrix def matrix_turn_upside_down(matrix): """A simple function to turn the matrix upside down""" # This could be simplified not to be a function, but to remain consistent # with all the other functions and to create a clean code, i made it a function. return matrix[::-1] def reverse_whole_matrix(matrix): """A function to turn the matrix upside down, then to reverse every line too.""" new_matrix = matrix_turn_upside_down(matrix) reversed_matrix = reverse_matrix_lines(new_matrix) return reversed_matrix def create_full_diagonal_matrix(matrix): """A function that creates a list of all the diagonal lines in the matrix using the 'down right' direction (from top left to down right) we will use this function to create all kinds of diagonal lines.""" # Creating half of the diagonal line half_diagonal_matrix = create_half_diagonal_matrix(matrix) new_matrix = create_line_for_downwards(matrix) # Turning the matrix upside down so the other half will be in the same place complete_diagonal_matrix = create_half_diagonal_matrix(new_matrix) for i in range(len(half_diagonal_matrix)): if half_diagonal_matrix[i] in complete_diagonal_matrix: # adding both list together, without the 1 line that is common # to both of them continue complete_diagonal_matrix.append(half_diagonal_matrix[i]) return complete_diagonal_matrix def create_half_diagonal_matrix(matrix): """This function creates a list of a part of diagonal lines the part which is from the primary matrix diagonal and down (not include the diagonals that are above the primary diagonal line.)""" # I created a temporary list to bond every diagonal line at once, # If i would not do it the list was with 1 object, i found it more efficient diagonal_list = [] temporary_list = [] for i in range(len(matrix)): # Not doing it on the first run, reset it for each line if i > 0: diagonal_list.append(temporary_list) temporary_list = [] for index, line in enumerate(matrix[i:]): # Not passing the indexes of the line if index >= len(matrix[0]): continue temporary_list.append(line[index]) diagonal_list.append(temporary_list) return diagonal_list def find_word_from_left_to_right_in_matrix(word, matrix): """This is the function that searches the words in the lines, it searches from left to right only. uses another function to find words in a single matrix line""" word_count = 0 for line in matrix: # Running for indexes, to find a letter that fits the first letter of the word, # When it finds, run the other function to see if the word is in the line. for i in range(len(line)): # If the word is in the line. if line[i] == word[0] and (find_word_from_left_to_right_in_line(word, line[i:])): word_count += 1 return word_count def find_word_from_left_to_right_in_line(word, line): """A function to find the word in a single line.""" count = 0 # The word cant be in the line if it is longer than the line. if len(word) > len(line): return False for j in range(len(word)): if line[j] == word[j]: # Counting the number of letters that are in the line and in the word. count += 1 # If all the letters are the same, the word is in the line. if count == (len(word)): return True return False if __name__ == "__main__": main(sys.argv[1:])
42630fd5c1015781dfd0de24397e5d0471081f38
UnsupervisedDotey/Leetcode
/数组/217_ContainsDuplicate.py
366
3.734375
4
class Solution(object): def containsDuplicate(self, nums): """ :type nums: List[int] :rtype: bool """ if nums is None: return None dup = set(nums) if len(dup) < len(nums): return True else: return False sol = Solution() print(sol.containsDuplicate([1,2,3,1]))
e6de12ac9276935c9d5c5c85d4ffe9f8dda511d9
mo-op/LeetCode
/easy/Range-Sum-Query.py
292
3.609375
4
''' Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. ''' class NumArray: def __init__(self, nums: List[int]): self.nums=nums def sumRange(self, i: int, j: int) -> int: s=sum(self.nums[i:(j+1)]) return s
e66f15480365da02426df067a1a6224875ef0691
Onotoko/codeforces
/graph/travelling_cost.py
1,017
3.78125
4
"""https://www.spoj.com/problems/TRVCOST/""" from queue import PriorityQueue INF = int(1e9) class Node: def __init__(self, id, dist): self.id = id self.dist = dist def __lt__(self, other): return self.dist <= other.dist def Dijkstra(u): pq = PriorityQueue() pq.put(Node(u,0)) dist[u] = 0 while not pq.empty(): top = pq.get() u = top.id w = top.dist for neighbor in graph[u]: if w + neighbor.dist < dist[neighbor.id]: dist[neighbor.id] = w + neighbor.dist pq.put(Node(neighbor.id, dist[neighbor.id])) path[neighbor.id] = u if __name__ == "__main__": n = int(input()) graph = [[] for _ in range(501)] dist = [INF for _ in range(501)] path = [-1 for _ in range(501)] for _ in range(n): v1,v2,w = list(map(int, input().strip().split(' '))) graph[v1].append(Node(v2,w)) graph[v2].append(Node(v1,w)) u = int(input()) Dijkstra(u) q = int(input()) for _ in range(q): qi = int(input()) cost = dist[qi] if cost == INF: print("NO PATH") else: print(cost)
1198810b544b77c3d8f34728b4407e7665abde8a
xyzhangaa/ltsolution
/BalancedBT.py
525
4.1875
4
###Given a binary tree, determine if it is height-balanced. ###For this problem, a height-balanced binary tree is defined as a binary tree in ###which the depth of the two subtrees of every node never differ by more than 1. #O(n), O(1) def height(root): if root ==None: return 0 return max(height(root.left),height(root.right))+1 def BalancedBT(root): if root == None: return True if abs(height(root.left)-height(root.right)) <= 1: return BalancedBT(root.left) and BalancedBT(root.right) else: return False
43575b2a34e0f5c08327a37cdd7328ac40fc81e2
erikkrasner/Project-Euler
/prob75_solution.py
1,817
3.859375
4
#!/usr/bin/env python # 161667 # from itertools import count # Euclid's formula, which is guaranteed to return all primitive # Pythagorean triples. Longest_wire is the longest a + b + c # such that a, b and c form a pythagorean triple. # m ** 2 + 2 * m + 1 is a lower bound on a + b + c = # (m ** 2 + n ** 2) + 2 * m * n * (m**2 - n**2). # When the lower bound exceeds longest_wire, all subsequent sums # must exceed longest_wire. def euclid_formula(longest_wire): for m in count(1): if m * m + 2 * m + 1 > longest_wire: break for n in count(1): if n >= m: break triple = (m * m - n * n, 2 * m * n, m * m + n * n) if sum(triple) <= longest_wire: yield triple # An extension of Euclid's formula, guaranteed to yield all # Pythagorean triples of wire length up to longest_wire (not # uniquely). def all_triples(longest_wire): def tuple_sum(tuple1, tuple2): return (tuple1[0] + tuple2[0], tuple1[1] + tuple2[1], tuple1[2] + tuple2[2]) for triple in euclid_formula(longest_wire): new_triple = triple while sum(new_triple) <= longest_wire: yield new_triple new_triple = tuple_sum(new_triple, triple) # Counts the number of wire lengths corresponding to only # one triple. Maintains a hash table mapping all wire lengths # previously found to a set of all triples with that wire length. # Counts all wire lenghs whose corresponding set has length 1. def num_wire_lengths_with_unique_triples(longest_wire): triples = {} for triple in all_triples(longest_wire): length = sum(triple) triple = tuple(sorted(triple)) if length not in triples: triples[length] = set() triples[length].add(triple) return len(filter(lambda x: len(triples[x]) == 1, triples)) print num_wire_lengths_with_unique_triples(1500000)
87f49313038daba1051fb4099cc4a98b5026604f
wcsanders1/HackerRank
/EvenTree/Python/EventTree.py
1,605
3.71875
4
#!/bin/python3 class Node: value = 0 total_children = 0 children = [] def __init__(self, value): self.value = value self.children = [] self.total_children = 0 def get_or_create_node(value, nodes_map): if value not in nodes_map: new_node = Node(value) nodes_map[value] = new_node return nodes_map[value] def get_even_subtrees(node): if node is None: return 0 if not node.children: node.total_children = 0 return 0 even_subtrees = 0 total_children = 0 for subnode in node.children: even_subtrees += get_even_subtrees(subnode) for subnode in node.children: children = subnode.total_children + 1 if children > 1 and children % 2 == 0: subnode.total_children = 0 even_subtrees += 1 else: total_children += children node.total_children += total_children return even_subtrees def even_forest(t_nodes, t_edges, t_from, t_to): root = Node(1) nodes_map = {1: root} for i in range(len(t_from)): child = get_or_create_node(t_from[i], nodes_map) parent = get_or_create_node(t_to[i], nodes_map) parent.children.append(child) return get_even_subtrees(root) if __name__ == '__main__': t_nodes, t_edges = map(int, input().rstrip().split()) t_from = [0] * t_edges t_to = [0] * t_edges for i in range(t_edges): t_from[i], t_to[i] = map(int, input().rstrip().split()) res = even_forest(t_nodes, t_edges, t_from, t_to) print(str(res) + '\n')
7e8a7a8253c6229e87ff1fb32d71663a431c56df
sryung1225/PythonStudy_LinearAlgebra
/Assignment 2/assignment2.py
3,434
3.78125
4
def readMatrixFile(fileName): """ (str) -> str 파일의 내용을 읽어서 그 내용을 Python String으로 반환함. """ with open(fileName) as file: """matrix=file.read().split() => ['A','3','3',...]""" """matrix=file.read() => 원본""" matrix=file.read() return matrix def countrow(arr): """ (1차원 배열) -> int 배열의 행 수 구함. """ row=int(arr[1]) return row def countcol(arr): """ (1차원 배열) -> int 배열의 열 수 구함. """ col=int(arr[2]) return col def divideMatrix(arr, row, col): """ (1차원 배열, int, int) -> 2차원 배열 1차원 배열과 행의 수, 열의 수를 받아 2차원 배열로 정렬함. """ M=[] for i in range(row): M.append([]) for j in range(col): num=3+(i*col)+(j%col) M[i].append(int(arr[num])) return M def det_two(arr_two): """ (int) -> int 열과 행의 값이 2인 행렬일 때, determinant 값을 구함 """ res = arr_two[0][0]*arr_two[1][1] - arr_two[0][1]*arr_two[1][0] return res def M(arr,size,num): """ (2차원 배열) -> 2차원 배열 Minor를 계산함 """ M=[] M_tmp=[] for i in range(size-1): for j in range(num-1): M_tmp.append(arr[i+1][j]) for j in range(size-num): M_tmp.append(arr[i+1][j+num]) M.append(M_tmp) M_tmp=[] return M def Big_M(arr, size): """ (2차원 배열) -> 2차원 배열 Minor를 계산함 """ B_M=[] for i in range(size): B_M.append(M(arr,size,i+1)) return B_M def det_three(arr_three): matrix=Big_M(arr_three, 3) cofactor=[arr_three[0][0]*det_two(matrix[0]), arr_three[0][1]*det_two(matrix[1]), arr_three[0][2]*det_two(matrix[2])] result=0 for i in range(3): if(i%2 == 0): result+=cofactor[i] else: result-=cofactor[i] return result def det_four(arr_four): matrix=Big_M(arr_four, 4) cofactor=[arr_four[0][0]*det_three(matrix[0]), arr_four[0][1]*det_three(matrix[1]), arr_four[0][2]*det_three(matrix[2]), arr_four[0][3]*det_three(matrix[3])] result=0 for i in range(4): if(i%2 == 0): result+=cofactor[i] else: result-=cofactor[i] return result def det_five(arr_five): matrix=Big_M(arr_five, 5) cofactor=[arr_five[0][0]*det_four(matrix[0]), arr_five[0][1]*det_four(matrix[1]), arr_five[0][2]*det_four(matrix[2]), arr_five[0][3]*det_four(matrix[3]), arr_five[0][4]*det_four(matrix[4])] result=0 for i in range(5): if(i%2 == 0): result+=cofactor[i] else: result-=cofactor[i] return result print("행렬을 입력하시오. (파일명.확장자)") matrixA=readMatrixFile(input()) arrA=matrixA.split() rowA=countrow(arrA) #A의 행 수 colA=countcol(arrA) #A의 열 수 arrAA=divideMatrix(arrA, rowA, colA) #2차원 배열로 정리한 A if (rowA != colA): print("square matrix가 아니므로 계산을 하지 않습니다.") else: print("파일 속 행렬 : ", arrAA) print("행렬의 determinant : ", end="") if colA == 2: print(det_two(arrAA)) elif colA == 3: print(det_three(arrAA)) elif colA == 4: print(det_four(arrAA)) elif colA == 5: print(det_five(arrAA))
ad2dd9e1b77ba0e5153f9b75bbd7bfb097cec824
matta174/python_practice
/src/Chapter 4/4-1_pizzas.py
181
3.5625
4
pizzas = ['pepperoni','cheese','sausage'] for pizza in pizzas: print('I like ' + pizza.title() + ' pizza!\n') print('Pizza is just very good, I like to eat it all the time.\n')
239d40b8eed120c808de51b94b8aa5cef44d1582
elinapiispanen/lajittelualgoritmit
/src/insertionsort.py
798
3.8125
4
from datetime import datetime startTime = datetime.now() def insertionSort(numeroarray): for i in range(1, len(numeroarray)): key = numeroarray[i] j = i-1 while j >= 0 and key < numeroarray[j]: print(numeroarray, "Luku", key, "on pienempi kuin", numeroarray[j]) numeroarray[j+1] = numeroarray[j] j -= 1 print(numeroarray, "Kopioidaan luku", numeroarray[j+1], "indeksiin", j+2, ",ja jos", key, "on suurempi kuin", numeroarray[j], "asetetaan se indeksiin", j+1) numeroarray[j+1] = key print(numeroarray) numeroarray = [5, 2, 6, 3, 1, 0, 4] insertionSort(numeroarray) time = (datetime.now() - startTime) print("Aikaa kului", time.microseconds / 1000000, "sekuntia")
a29df60531664a708b1e1041c8c9ed44d8ee4947
alhart2015/Webtree
/create_matching.py
2,852
3.640625
4
''' Takes the result MATLAB spits out and turns it into a matching of students and their assigned classes. Author: Alden Hart 3/23/2015 ''' import numpy as np import csv MATLAB_RESULT = 'MATLAB_result_spring-2015.txt' INPUT_DATA = 'processed_data_spring-2015.csv' OUTFILE = 'class_matching_spring-2015.txt' def read_in_result(MATLAB_RESULT): '''Reads in what MATLAB spit out. Returns it as a list.''' text_file = open(MATLAB_RESULT, 'r') lines = text_file.readlines() text_file.close() out = [] for i in lines: out.append(int(i)) return out def read_input_data(INPUT_DATA): '''Reads in what you gave MATLAB so that you can figure out what class is what and what person is who. Parameter: INPUT_DATA - the name of the file you put into MATLAB Returns: a 2-D numpy array of the matrix ''' out = [] with open(INPUT_DATA, 'r') as f: reader = csv.reader(f) for row in reader: out.append(row) return out def class_assignments(results, people, classes): '''Takes the string of 1's and 0's that MATLAB gives you and turns that into an assignment of four classes for each person. Parameter: results - the list of MATLAB results people - the list of student IDs, in order classes - the list of CRNs in order Returns: a dictionary with keys of people and values of the four classes this person got (as a list) ''' assignments = {} num_classes = len(classes) for i in xrange(len(results)): if results[i] == 1: student_index = i / num_classes class_index = i % num_classes student = people[student_index] crn = classes[class_index] if student in assignments: assignments[student].append(crn) else: assignments[student] = [crn] return assignments def write_out(assignments, filename): '''Writes the final assignments to a txt file.''' with open(filename, 'w') as f: for a in sorted(assignments): f.write(str(a) + ' ') for c in assignments[a]: f.write(str(c) + ' ') f.write('\n') def main(): result = read_in_result(MATLAB_RESULT) input_data = read_input_data(INPUT_DATA) print 'Num results', len(result) print 'Total classes assigned', sum(result) crns = input_data[0][1:] print 'Unique classes', len(crns) # print crns[:10] people = [] for row in input_data[2:]: people.append(int(row[0])) # print people[:10] print 'Unique people', len(people) assignments = class_assignments(result, people, crns) # for p in assignments: # print p, assignments[p] write_out(assignments, OUTFILE) if __name__ == '__main__': main()
f8fbd686bf0302ffcba44102f6a092222b92269a
peterhel/pysms
/send_text.py
1,200
3.65625
4
# This is pyserial which is needed to communicate with the dongle import serial import io import binascii import sys port = sys.argv[1] # /dev/tty.HUAWEIMobile-Modem number = sys.argv[2] # +46708123456 message = sys.argv[3] # 'Hi phone!' # Make sure the message is ASCII friendly. Throws error if not. message.decode('ascii') # Set up the connection to the dongle dongle = serial.Serial(port=port,baudrate=115200,timeout=2,rtscts=0,xonxoff=0) print "Connected!" # Wait for response. Must be called after each execution that returns an answer. def getResponse(): sb = [] sb.append(dongle.read()) sb.append(dongle.read(dongle.inWaiting())) return ''.join(sb) # Tell dongle not to echo back commands. dongle.write('ATE0\r') print getResponse() # Put dongle in text mode dongle.write('AT+CMGF=1\r') print getResponse() # Set the telephone number we want to send to dongle.write('AT+CMGS="' + number + '"\r') print getResponse() #### Set the message we want to send try: dongle.write(message) except: print "Unexpected error" # Pass the CTRL+Z character to let the dongle know we're done dongle.write(chr(26)) print getResponse() # Close the connection dongle.close()
3b742b0f02dbde70d1babddf9074466528735d77
johnkle/FunProgramming
/DataStructure/05recursion/recur_basic.py
217
3.84375
4
def sum(arr): return sum1(arr,0,len(arr)-1) def sum1(arr,l,r): # if l > r: # return 0 if l==r: return arr[r] L = arr[l]+sum1(arr,l+1,r) return L arr = [1,2,3,4,5,6] print(sum(arr))
d6e4097a40ea0b2a47a7355c7b2f8af328239b3d
lgrant146/RPS_Python
/Problems/Decimal places/main.py
79
3.578125
4
number = float(input()) decimal = int(input()) print(f'{number:.{decimal}f}')
086d6325d22e77ab67ddbc0b8c1dbd23b9855134
siddharthadtt1/Leet
/IC/08-balanced-binary-tree.py
1,154
3.765625
4
# write code for leetcode water container problem and trapping water problem class TreeNode(object): def __init__(self, value): self.left = None self.right = None self.val = value # this solution is for 'super balanced tree' defined in the IC # problem, which has a different definition for 'balanced' in leetcode 110. # In leetcode 110, the definition for balenced is the same as in an AVL # tree. In an AVL tree, the difference between the depths of two subtrees # of any node should not be bigger than 1, but he diffence bewteen any # two leaf nodes can be any number ( maybe smaller than lg(n)?) class Solution(object): def isBalanced(self, root): if not root: return True node_stack = [(root, 0)] levels = [] while node_stack: node, level = node_stack.pop() if not node: if level not in levels: if len(levels) == 1 and abs(level - levels[0]) > 1: return False if len(levels) == 2: return False levels.append(level) else: node_stack.append((node.left, level + 1)) node_stack.append((node.right, level + 1)) return True
36e47ccd2f16e80e8c97c70b49b771c9618dbbe6
df413/leetcode
/find_bin_ones_in_number/main.py
402
3.578125
4
class Solution(object): def find_all_ones(self, number: int) -> int: res = 0 mask = 1 print("bin repr of number {} is {}".format(number, bin(number))) while mask <= number: if number & mask > 0: res += 1 mask = mask << 1 return res if __name__ == "__main__": sol = Solution() print(sol.find_all_ones(12))
507da2f51cec77c87b07248a5bb7485e713a1d90
L200180039/praktikum-ASD
/MODUL - 1/14.py
315
3.796875
4
#14 def formatRupiah(a) : a = list(str(a)) b = len(a) if b % 3 == 0 : b = int(b/3) - 1 else : b = int(b/3) n = 0 for i in range(b) : x = -3*(i+1) a.insert(int(x)+n,".") n = n - 1 a = "".join(a) print("Rp "+a)
6cc72b9ac2401a19d96d22495e3b0483b953acf3
dryabokon/algo
/recurs_08_triplet_closest_sum.py
665
3.515625
4
# ---------------------------------------------------------------------------------------------------------------------- def triplet_closest_S(A, S=0): A.sort() best_sum = A[0] + A[1] + A[2] for i in range(len(A) - 2): j, k = i + 1, len(A) - 1 while j < k: sum = A[i] + A[j] + A[k] if sum == S: return sum if abs(sum - S) < abs(best_sum - S): best_sum = sum if sum < S: j += 1 elif sum > S: k -= 1 return best_sum # ---------------------------------------------------------------------------------------------------------------------- if __name__ == '__main__': A = [-1,2,1,-4] res = triplet_closest_S(A,1) print(res)
32832e82aa64ed882ed0d9a073902dfd7e15020a
jianminchen/leetcode-8
/spiral_matrixII.py
1,210
3.640625
4
DEBUG = True def log(s): if DEBUG: print s class Solution: ''' Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. [1,2,3] [8,9,4] [7,6,5] ''' def generateMatrix(self, n): if n < 1: return [] if n == 1: return [[1]] m =[ [0 for i in range(n)] for j in range(n) ] # Generate edge first # 1) up edge edge = 0 for i in range(n): edge += 1 m[0][i] = edge # 2) right edge for j in range(1,n): edge += 1 m[j][n-1] = edge # 3) bottome edge for q in reversed( range(n-1) ): edge += 1 m[n-1][q] = edge # 4) left edge for p in reversed( range(1,n-1) ): edge += 1 m[p][0] = edge # Fill inside of matrix recursively inside = self.generateMatrix(n-2) for i in range(1,n-1): for j in range(1,n-1): m[i][j] = inside[i-1][j-1] + edge return m # Testing s = Solution() test = 4 print "Tesing: ",test print "Answers: ",s.generateMatrix(test)
8d77f27bcb468dd52b37559923a048d47d5858b9
ptyork/au-aist2120-20fa
/common/821_branch_loop.py
2,005
4.21875
4
# boolean expression # True or False (also on or off, 1 or 0, yes or no) # Boolean Operators # Must be over 21 and not infected with covid # AND # BOTH OPERANDS MUST BE TRUE IN ORDER FOR THE EXPRESSION TO BE TRUE # C#: && # Python: and print("AND") print(True and True) # True print(True and False) # False print(False and True) # False print(False and False) # False # Must be uninfected or asymptomatic # OR # EITHER (OR BOTH) OPERANDS MUST BE TRUE IN ORDER FOR THE EXPRESSION TO BE TRUE # C#: || # Python: or print("OR") print(True or True) # True print(True or False) # True print(False or True) # True print(False or False) # False # COMPARISON OPERATORS # EQUALITY # = vs == print("==") print(True == False) # False print(True == True) # True # INEQUALITY print("!=") print(True != True) # False print(True != False) # True # GT OR LT # > for Greater Than # < for Less Than # >= for GT or Equal # <= for LT or Equal # C# # if (a > b) # { # DO SOMETHING; # DO SOMETHING; # DO SOMETHING; # } a = 1 b = 2 if a < b: print('yes it is') print('aren\'t I grand') if a == 1: print('a is so boring') print('b is so boring') print('all done') age = 19 iscool = True if age >= 21 and iscool == True: print('come in') else: print('nice try') if age >= 21 and iscool == True: print('come in') elif age >= 21 and iscool == False: print('stand in the dork line') else: print('nice try') # NOT OPERATOR (in C# it was !) # not True ==> False # not False ==> True if age >= 21 and iscool: print('come in') elif age >= 21 and not iscool: print('stand in the dork line') else: print('nice try') age = 12 while age < 21: print('go home little kid') # age = age + 1 age += 1 print('come on in') # break # continue counter = 0 while True: print('hello') counter += 1 if (counter > 5): break # for loop????????? (book give for in range())
629f11d331c0a817ce49c1fb4c56a027c9395bcd
zzz686970/leetcode-2018
/35_searchInsert.py
720
3.875
4
def searchInsert(nums, target): i = 0 while i < len(nums): if target <= nums[i]: return i else: i += 1 return i ## way 2 # return len([x for x in nums if x<target]) assert 2 == searchInsert([1,3,5,6], 5) assert 1 == searchInsert([1,3,5,6], 2) assert 4 == searchInsert([1,3,5,6], 7) assert 0 == searchInsert([1,3,5,6], 0) def searchInsert(nums, target) -> int: l, r= 0, len(nums)-1 while l < r: mid = (l + r) // 2 if nums[mid] == target: return mid elif nums[mid] < target: l = mid + 1 else: r = mid return l if target < nums[-1] else l + 1 print(searchInsert([1,3,5,6], 2)) print(searchInsert([1,3,5,6], 7))
b56efda70d65a9dd33277bae1eac032a6d99b083
Serzol64/mypythonlearntasks1
/task17.py
233
4
4
def sum_digits(num): digits = [int(d) for d in str(num)] return sum(digits) f = input("Введите целое число:") print("Результат сложения цифр целого числа:", sum_digits(int(f)))
2ac2816bec883fe0160c42c9b7bf99f1d358d501
rklabs/pyalgs
/dfs_iterative.py
1,167
3.71875
4
#!/usr/bin/env python from collections import deque from collections import defaultdict class Graph(object): def __init__(self, noOfVertices): self._noOfVertices = noOfVertices self._adjV = defaultdict() self._visited = [] def addEdge(self, vertex, neighbor): self._adjV.setdefault(vertex, []).append(neighbor) def _dfs(self, startV): self._visited[startV] = True vq = deque() vq.appendleft(startV) while vq: vertex = vq.popleft() print vertex for adjV in self._adjV[vertex]: if not self._visited[adjV]: self._visited[adjV] = True vq.appendleft(adjV) def dfs(self): for _ in range(self._noOfVertices): self._visited.append(False) for vertex in range(self._noOfVertices): if not self._visited[vertex]: self._dfs(vertex) if __name__ == '__main__': graph = Graph(5) graph.addEdge(0, 2) graph.addEdge(0, 3) graph.addEdge(1, 0) graph.addEdge(2, 1) graph.addEdge(3, 4) graph.addEdge(4, 0) graph.dfs()
d1bcd0abcb52ee7619a48c81c7e275d4d0a928a6
jzgombic/IS211_Assignment4
/search_compare.py
5,400
4.25
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import time import random def sequential_search(a_list, item): """ The function searches a list and returns a boolean value as to whether an item is present as well as the amount of time the search had taken. Args: a_list (list): List containing data to be searched. item (int): A value to be searched for in the given list. Returns: (Tuple): A tuple containing a boolean value if the value is present and the processing time in seconds. """ start_time = time.time() pos = 0 found = False while pos < len(a_list) and not found: if a_list[pos] == item: found = True else: pos = pos + 1 end_time = time.time() run_time = end_time - start_time return (run_time, found) def ordered_sequential_search(a_list, item): """ The function searches a list and returns a boolean value as to whether an item is present as well as the amount of time the search had taken. Args: a_list (list): List containing data to be searched. item (int): A value to be searched for in the given list. Returns: (Tuple): A tuple containing a boolean value if the value is present and the processing time in seconds. """ a_list = sorted(a_list) start_time = time.time() pos = 0 found = False stop = False while pos < len(a_list) and not found and not stop: if a_list[pos] == item: found = True else: if a_list[pos] > item: stop = True else: pos = pos + 1 end_time = time.time() run_time = end_time - start_time return (run_time, found) def binary_search_iterative(a_list, item): """ The function searches a list and returns a boolean value as to whether an item is present as well as the amount of time the search had taken. Args: a_list (list): List containing data to be searched. item (int): A value to be searched for in the given list. Returns: (Tuple): A tuple containing a boolean value if the value is present and the processing time in seconds. """ a_list = sorted(a_list) start_time = time.time() first = 0 last = len(a_list) - 1 found = False while first <= last and not found: midpoint = (first + last) // 2 if a_list[midpoint] == item: found = True else: if item < a_list[midpoint]: last = midpoint - 1 else: first = midpoint + 1 end_time = time.time() run_time = end_time - start_time return (run_time, found) def binary_search_recursive(a_list, item): """ The function searches a list and returns a boolean value as to whether an item is present as well as the amount of time the search had taken. Args: a_list (list): List containing data to be searched. item (int): A value to be searched for in the given list. Returns: (Tuple): A tuple containing a boolean value if the value is present and the processing time in seconds. """ a_list = sorted(a_list) start_time = time.time() if len(a_list) == 0: found = False else: midpoint = len(a_list) // 2 if a_list[midpoint] == item: found = True else: if item < a_list[midpoint]: return binary_search_recursive(a_list[:midpoint], item) else: return binary_search_recursive(a_list[midpoint + 1:], item) end_time = time.time() run_time = end_time - start_time return (run_time, found) def list_gen(value): """ Generates a list of random values. Args: value (int): An integer representing the number of values in the list. Returns: sample_list (list): A list of integers in random order. The list length is based on the value argument. """ sample_list = random.sample(xrange(1, (value + 1)), value) return sample_list def main(): """ Tests the four search algorithms by generating 100 test lists of three different sizes, calculates the average processing time for each search and returns the result in as a string. Args: None. Returns: (String): The average processing time for each search. """ list_size = [500, 1000, 10000] search = {'Sequential': 0, 'Ordered': 0, 'Binary Iterative': 0, 'Binary Recursive': 0} for t_list in list_size: counter = 0 while counter < 100: list_test = list_gen(t_list) search['Sequential'] += sequential_search(list_test, -1)[0] search['Ordered'] += ordered_sequential_search(list_test, -1)[0] search['Binary Iterative'] += binary_search_iterative(list_test, -1)[0] search['Binary Recursive'] += binary_search_recursive(list_test, -1)[0] counter += 1 print 'For the list containing %s lines:' % (t_list) for st in search: print ('%s Search took %10.7f seconds to run, on average.') % (st, search[st] / counter) if __name__ == '__main__': main() #Author: Johnny Zgombic #Date: September 23, 2019
1406c68ccfa5ec3db4c2d1ee786472049a1daa48
karthik-siru/practice-simple
/trees/inorder.py
1,695
4.03125
4
# question : """ ITERATIVE INORDER TRAVERSAL OF A BINARY TREE . """ # approach : """ -> We use an explicit stack to store the nodes . """ from collections import deque # Data structure to store a binary tree node class Node: def __init__(self, data=None, left=None, right=None): self.data = data self.left = left self.right = right # Iterative function to perform inorder traversal on the tree def inorderIterative(root): # create an empty stack stack = deque() # start from the root node (set current node to the root node) curr = root # if the current node is None and the stack is also empty, we are done while stack or curr: # if the current node exists, push it into the stack (defer it) # and move to its left child if curr: stack.append(curr) curr = curr.left else: # otherwise, if the current node is None, pop an element from the stack, # print it, and finally set the current node to its right child curr = stack.pop() print(curr.data, end=" ") curr = curr.right if __name__ == "__main__": """ Construct the following tree 1 / \ / \ 2 3 / / \ / / \ 4 5 6 / \ / \ 7 8 """ root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.right.left = Node(5) root.right.right = Node(6) root.right.left.left = Node(7) root.right.left.right = Node(8) inorderIterative(root)
2f6a8bf2c8d5e6864a9fdc97bc0fb283065a581a
kbturk/BehindTheWall
/BehindTheWall.py
2,866
3.515625
4
import requests, sys, argparse from bs4 import BeautifulSoup def error_log(s: str) -> bool: print(f'\033[31;1m{s}\033[0m', file=sys.stderr) return False def arg_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser() parser.add_argument('tag_string', help='html tag string', type=str) parser.add_argument('url', help='URL to fetch', type=str) g = parser.add_mutually_exclusive_group() g.add_argument('-c', '--class', dest='class_', help='search for text where tag_string matches HTML class name', action='store_true') g.add_argument('-i', '--id', dest= 'id', help='search for text where tag_string matches HTML id name', action='store_true') return parser def pretty_format(text: str, par_length:int = 5) -> str: ''' create pretty output format by splitting the text into paragraphs based on periods. par_length is an optional paramater. ''' s_list = text.split('.') for i, s in enumerate(s_list): s_list[i] = f"{s}." if i% 5 == 0: s_list[i] = s_list[i] + "\n\n" return "".join(s_list) def scraper(args) -> bool: ''' use requests to stream html from a website URL which is then parsed using beautifulSoup's find_all function. requests is a popular 3rd party open source python library see https://github.com/psf/requests.git for more info beautifulSoup4 is a popular 3rd party os python library that parses html code. ''' r: requests.models.Response = requests.get(args.url, stream=True) r.encoding = 'utf-8' if len(r.text) == 0: return error_log('had issue with requests.get scraper.') #Translate to beautiful soup. soup = BeautifulSoup(r.text, 'html.parser') #find the content you're looking for: if args.id: entries = soup.find_all( id = args.tag_string ) elif args.class_: entries = soup.find_all( class_ = args.tag_string ) else: entries = soup.find_all( args.tag_string ) if len(entries) == 0: return error_log(f'no entries found when searching for: {args.tag_string}') content = [] for entry in entries: try: for text in entry.stripped_strings: content.append(" "+text) except ValueError: return error_log(f'issues scraping text: {entry}') content_string = pretty_format(''.join(content)) with open('website.txt', 'w', encoding = 'utf8') as f: f.write(content_string) print('''\033[32;1msite scraping is complete. To view results, please open website.txt or you can view in the terminal using something like: `fold -s website.txt`\033[0m''') return True def main(argv: list[str]) -> int: scraper(arg_parser().parse_args(argv[1:])) return 0 if __name__ == '__main__': sys.exit(main(sys.argv))
97933a81ea6b86d7dfa02c716ea0fe7db15eaf1b
zhangxinqian/HuaWeiProgramming
/合法IP/ip.py
439
3.546875
4
def is_valid_ip(ipstr): iparr = ipstr.split(".") if len(iparr) != 4: return "NO" for i in iparr: if i.isdigit(): i = int(i) if i < 0 or i > 255: return "NO" else: return "NO" return "YES" if __name__ == '__main__': while True: try: ipstr = raw_input() print is_valid_ip(ipstr) except: break
92957e3677e482885625891104082803b492cb8d
kamal09rumba/hackerrank
/30DaysOfCode/python/Day9-Dictionaries-and-Maps/submitted_ans.py
447
3.71875
4
# Enter your code here. Read input from STDIN. Print output to STDOUT #!/usr/python import sys phoneBook = [] n = int(raw_input('').strip()) for i in range(1,n+1): si=str(raw_input('')) so=si.split() value = so[0],so[1] phoneBook.append(value) phoneBook = dict(phoneBook) for j in range(1,n+1): query = str(raw_input('')) if query in phoneBook: print query+'='+phoneBook[query] else: print 'Not found'
47247afa73a17756391a3655255dd145d324dea1
AlexKaracaoglu/Cryptography
/AutomatedCryptanalysis/automatedCryptanalysis.py
4,427
3.53125
4
# Alex Karacaoglu and Brendan Duhamel # Project 1: Automated Cryptanalysis of Monoalphabetic Substitution Cipher import string import math import random import itertools #Code to set up the text file, open and then get rid of irrelevant stuff def setup(filename): f = open(filename,'rb') s = f.read() s = s.translate(None,string.whitespace) s = s.translate(None,string.punctuation) s = s.translate(None,string.digits) s = s.replace('\x94','') s = s.replace('\x93','') s = s.replace('\x92','') s = s.lower() return s #count number of occuraces of a in the string s def countSets(a,s): return s.count(a) #append string b to the end of a def append(a,b): s = "".join((a,b)) return s #setting up the dictionary that we will be using def setUpDictionary(s1,s2,s3): dictionary = {} for i in range(97,123): for j in range(97,123): iC = chr(i) jC = chr(j) a = append(iC,jC) b1 = float(countSets(a,s1)) + 26 b2 = float(countSets(a,s2)) + 26 b3 = float(countSets(a,s3)) + 26 lis = [] fulList = [] for k in range(97,123): newSub = append(a,chr(k)) countNewSubs1 = countSets(newSub,s1) +1 countNewSubs2 = countSets(newSub,s2) +1 countNewSubs3 = countSets(newSub,s3) +1 freq = (countNewSubs1 + countNewSubs2 + countNewSubs3) / (b1+b2+b3) lis.append(freq) dictionary[a] = lis return dictionary ##### GLOBAL VARIABLES ##### s1 = setup('jane.txt') s2 = setup('tale.txt') s3 = setup('heart.txt') dictionary = setUpDictionary(s1,s2,s3) #generates a random permutation of the 26 letters of the alphabet and can be used to shuffle around the letters of the cipher text def permute(): a = list(string.ascii_lowercase) random.shuffle(a) return a #Used to rearrange the letters so we can make many passes through to find the best decryption def rearrange(text,permutation): new = text for i in range(len(permutation)): new = new.replace(chr(i+97),chr(ord(permutation[i])-32)) new = new.lower() return new #Scoring algorithm def score(text, dictionary): score = 0 for i in range(len(text)-2): a = append(text[i],text[i+1]) b = text[i+2] b = ord(b) - 97 value = dictionary[a][b] value = -1 * math.log(value) score = score + value return score #Takes two letters in a string, and swaps them def swapString(string,a,b): s = string s = s.replace(a,chr(ord(b)-32)) s = s.replace(b,chr(ord(a)-32)) s = s.lower() return s #Iterates through all possible moves and calculates the best one according to the scoring alg def bestSingleMove(text,dictionary): bestScore = score(text,dictionary) bestText = text allCombos = list(itertools.combinations(string.ascii_lowercase,2)) for i in range(len(allCombos)): tempText = swapString(text,allCombos[i][0],allCombos[i][1]) tempScore = score(tempText,dictionary) if tempScore < bestScore: bestText = tempText bestScore = tempScore return (bestText,bestScore) #Keeps doing the best move until you reach a local minimum (smaller = better) score def untilMinimal(text): old_score = 0 new_score = score(text,dictionary) new_text = text while (old_score != new_score): old_score = new_score a = bestSingleMove(new_text,dictionary) new_text = a[0] new_score = a[1] return (new_score,new_text) #Does a series of 200 minimal trials and returns the best score and the best text def manyMinimalTrials(text): best_score = score(text,dictionary) best_text = text for i in range(200): print str(i) new_text = rearrange(text,permute()) a = untilMinimal(new_text) temp_text = a[1] temp_score = a[0] if temp_score < best_score: best_score = temp_score best_text = temp_text return (best_score, best_text) #Takes in a cipher text, no spaces and returns (Hopefully) the correct result def go(text): a = manyMinimalTrials(text) final_text = a[1] return final_text
392ad02291b696997193c31a39e66479a187228f
cyaoyapi/python3_review
/004_fibonacci_function/test_fibonacci.py
312
3.578125
4
import unittest from fibonacci import fibo class TestFibonacci(unittest.TestCase): """Test case for fibonacci function.""" def test_basic(self): """ A basic test on fibonacci function.""" series = fibo(10) self.assertEqual(series, [0, 1, 1, 2, 3, 5, 8]) if __name__ == '__main__': unittest.main()
ad3a5fb76f92903e0ef44b9033670e11ddffa5a0
lu4/chessmoves
/Tools/perft.py
540
3.53125
4
#!/usr/bin/env python import chessmoves import sys def perft(pos, depth): moveList = chessmoves.moves(pos, notation='uci') if depth == 1: return len(moveList) else: return sum( [perft(newPos, depth-1) for newPos in moveList.values()] ) if __name__ == '__main__': if len(sys.argv) == 2: depth = int(sys.argv[1]) assert depth >= 1 else: depth = 1 for line in sys.stdin: print perft(line, depth)
a74259bc0cd1740436368b491d940eb14f368778
Pranay-yanarp/my-python-programs
/conditional statements.py
1,111
4.375
4
# grade the marks using conditional statments marks=int(input("enter marks")) if marks>=50 and marks<60: print("grade = E") elif marks>=60 and marks<70: print("grade = D") elif marks>=70 and marks<80: print("grade = C") elif marks>=80 and marks<90: print("grade = B") elif marks>=90 and marks<=100: print("grade = A ") else: print("grade = fail") # find a given a year is a leap year or not using conditional statments year=int(input("enter a year")) if year%400==0: print("its a leap year") elif year%100==0: print("its not a leap year") elif year%4==0: print("its a leap year") else: print("its not a leap year") # find odd or even using conditional statments nt=int(input("enter a number")) if nt%2==0: print("its even number") else: print("its odd number") # find greatest of 3 numbers using conditional statments n1=int(input("enter a 1st number")) n2=int(input("enter a 2nd number")) n3=int(input("enter a 3rd number")) if n1>n2 and n1>n3: print("%d is greatest"%(n1)) elif n2>n3: print("%d is greatest"%(n2)) else: print("%d is greatest"%(n3))
e4f27377918f110be4d8995a2ec3b355f5da1fc0
LemonPi/lemonpi.github.io
/projects/formatter.py
691
3.578125
4
import sys import os def format_file(infilename): """format a file to be compatible with the current version of markdown (or strip down to HTML)""" temp = ".temp" with open(infilename, "r") as inf, open(temp, "w") as outf: for l in inf: # first rule, eliminate -----* after headers if l.startswith("<h2") or l.startswith("<h3"): outf.write(l) nl = inf.readline() if nl.startswith("---"): continue # don't copy this line over else: outf.write(l) # replace the original file try: os.remove(infilename) except OSError: pass os.rename(temp, infilename) if __name__ == "__main__": print("formatting {}".format(sys.argv[1])) format_file(sys.argv[1])
3ff6ed1848b4644b07e96e1b2f5188d465833122
kurozakizz/learnpy
/05-func.py
463
4.03125
4
def say_hi(first = 'Jane', last = 'Doe'): """Say hello to there name.""" print('Hi! {} {}'.format(first, last)) say_hi() say_hi(first='Nuttawoot', last='Singhathom') def odd_or_even(num): """Determine number is odd or even""" if num % 2 == 0: return 'Even' else: return 'Odd' print(odd_or_even(2)) print(odd_or_even(1)) def is_even(num): """Is number even""" return num % 2 == 0 print(is_even(1)) print(is_even(2))
f77be0c0904dd477262e75f1611ea61f66f602bf
ethanbar11/haskal_28_6_21
/lecture_2/for_loop_examples.py
68
3.921875
4
print('Hello') x = 5 for i in range(0, 10): print(i) x += 5
63268766dfd82f79d2905e7a946db7987adb5e88
chinnuz99/luminarpython
/functionalprogramming/reduce.py
231
3.921875
4
#reduce # import functools from functools import * arr=[1,2,3,4,5,6] total=reduce(lambda num1,num2:num1+num2,arr) print(total) #print highest number highest=reduce(lambda num1,num2:num1 if num1>num2 else num2,arr) print(highest)
3dd8a711e5f647ad6707c73a86a95c218e55157d
ar95314/naagini3
/player55.py
116
3.71875
4
s1,s2=map(str,raw_input().split()) s11=s1.upper() s21=s2.upper() if(s11==s21): print "yes" else: print "no"
f3095b882c5f3eaf31ea847db0b99609fc31fd9e
Vages/python_algorithms
/chapter04/centralNodes.py
1,663
3.84375
4
''' A solution to task 4-4 in the book: A node is called central if the greatest (unweighted) distance from that node to any other in the same graph is minimum. That is, if you sort the nodes by their greatest distance to any other node, the central nodes will be at the beginning. Explain why an unrooted tree has either one or two central nodes, and describe an algorithm for finding them. ''' def centralNodes(G): 'Lists the central nodes of the graph G.' count = dict((u, 0) for u in G) # Create an empty count dictionary for u in G: for v in G[u]: count[u] += 1 # Count the number of neighbors each node has Q = [u for u in G if count[u] == 1] # A dictionary of all nodes that are leaf nodes S = [u for u in G] # A copy of all nodes in the original G dictionary; the solution set if len(S) <= 2: return S hasLeafNodes = True while hasLeafNodes: R = [] # A list of candidates for the next round while Q: # As long as there are unprocessed nodes with too few friends u = Q.pop() # Take a node that has too few friends S.remove(u) # Remove it from the solution set for v in G[u]: # For each friend v, decrease their friend count, now that u is gone. count[v] -= 1 if count[v] == 1: # Should a node reach a count below K, add this to Q R.append(v) if len(S) > 2: Q = R[:] else: hasLeafNodes = False return S def main(): x, y = range(2) H = {y:[x], x:[y]} print(centralNodes(H)) a, b, c, d, e, f, g, h, i = range(9) G = {a:[d], b:[d], c:[d], d:[a, b, c, g], e:[g, i], f:[g], g:[d, e, f, h], h:[g], i:[e]} print(centralNodes(G)) if __name__ == '__main__': main()
8373d70eea59480a3c0d55f3ea288c2c88db045d
kluitel/codehome
/src/input.py
412
3.859375
4
lb = int(input("Enter lower bound: ")) ub = int(input("Enter upper bound: ")) print("\nYou chose {0} as your lower bound,\ and {1} as your upper bound.".format(lb,ub)) verify = raw_input("\nProceds? (y/n): ") response = verify.lower() if response == 'y': for multiplier in range(lb, (ub+1)): for i in range(1,11): print(multiplier,'x',i, '=', i * multiplier); else: print "asfdasfd"
cd761708ffb407b389787428d3f170e8e7e7d95b
AndresDGuevara/platzi_intermedio
/lists_and_dicts.py
893
3.9375
4
def run(): # my_list = [1, "Hello", True, 4.5] # my_dict = {"firstname": "Andres", "lastname": "Guevara"} # Lista de diccionarios super_list = [ {"firstname": "Cristian", "lastname": "Guevara"}, {"firstname": "Stella", "lastname": "Aguirre"}, {"firstname": "Carlos", "lastname": "Santana"}, {"firstname": "Max", "lastname": "Cavalera"}, {"firstname": "Dave", "lastname": "Grol"}, ] # Diccionario de listas super_dict = { "natural_nums": [1, 2, 3, 4, 5], "integer_nums": [-1, -2, 0, 1, 2], "floating_nums": [1.1, 4.5, 6.43], } for key, value in super_dict.items(): print(key, "-", value) # for value in super_list: # print the list as it is # print(value) for i in super_list: print(i["firstname"], ",", i["lastname"]) if __name__ == '__main__': run()
30374a4e6ad201bdba117f0eee910313e890c16d
gandhikush25/format_method
/format.py
672
4.375
4
#Format methods name = "Hello" age = 20 #type1 detail = "My name is {0} My age is {1}" .format(name,age) print(detail) #type2 detail = "My name is {} My age is {}" .format(name,age) print(detail) #type3 print("You are trying {info} and Testing the {meth} method".format(info="python" , meth = "Format")) # three digits allowed after point in .3f print("{0:.3f}".format(1.0/3)) #here in below example from 0-5 it will scan Hello word, then after that from 6th position 1 ( _ ) # will be inserted after Hello then at 7th position another( _ ) will be inserted before Hello and then so on. print("{0:_^11}".format("Hello"))
3c0e060441e4e2d5eb528c82f62c756b8a93fd38
JoshuaSamuelTheCoder/Quarantine
/Disk_Space_Analysis/main.py
2,250
4.625
5
""" Choose a contiguous segment of a certain number of computers, starting from the beginning of the row. Analyze the available hard diskspace on each of the computers. Determine the minimum available disk space within this segment. After performing these steps for the first segment, it is then repeated for the next segment, continuing this procedure until the end of the row (ie if the segment size is 4 computers 1 to 4 would be analyzed, then 2 to 5 etc.) Given this analysis, write an algorithm to find the maximum available disk space among all the minima that are found during the analysis. Input: numComputer: an integer representing the number of computers hardDiskSpace: a list of integers representing the hard disk space of the computers. segmentLength: an integer representing the length of contiguous segment of computers to be considered in each iterations. Output: An integer representing the maximum available disk space among all the minima that are found during the analysis. Constraints: 1 <= numComputer <= 10^6 1 <= segmentLength <= numComputer 1 <= hardDiskSpace[i] <= 10^9 0 <= i <= numComputer Example: Input: numComputer = 3 hardDiskSpace = [8,2,4] segmentLength = 2 Output: 2 Explantion: In this array of computers, the subarrays of size 2 are [8,2] and [2,4]. Thus, the initial analysis returns 2 and 2 because those are the minima for the segments. Finally, the maximum of these values is 2. TestCase 1: Input: 5, [1,2,3,1,2], 1 Output: 3 TestCase 2: Input: 8, [10,20,30,40,25,81,98,45],8 Output: 10 """ def maxOfAllMin(numComputer, hardDiskSpace, segmentLength): #WRITE YOUR CODE HERE l,r, = 0,0 subst = hardDiskSpace[:segmentLength] minSpace = min(subst) r = segmentLength - 1 while l < len(hardDiskSpace)-1 and r < len(hardDiskSpace)-1: toRemove = hardDiskSpace[l] l += 1 r += 1 if toRemove <= minSpace: ans = hardDiskSpace[l:r+1] minSpace = max(minSpace, min(ans)) else: ans = min(minSpace, hardDiskSpace[r]) minSpace = max(minSpace, ans) return minSpace if __name__ == "__main__": print(maxOfAllMin(6,[3, 2, 1, 4, 2, 2],3))
1b841bbb710f2d5521330c5be001f7a631e7d8b4
karen15555/Intro-to-Python
/Lecture4/Homework4/problem5.py
261
3.984375
4
menu = ["ice cream", "chocolate", "apple crisp", "cookies"] desert = input() while True: if desert in menu: print("Your desert will arrive in 10 minutes") break else: print("Please choose another desert") desert=input()
45ab33c4838a72777f4d5988858829b07b6a5b09
cassiocamargos/Python
/learn-py/python-15h/listas.py
1,682
4
4
'''cidades = ['Rio de Janeiro', 'sao paulo', 'salvador'] cidades[0] = 'brasilia' cidades.append('santa catarina') cidades.remove('salvador') cidades.insert(1, 'salvador') cidades.pop(1) cidades.sort() print(cidades)''' '''numeros = [2, 3, 4, 5] letras = ['a', 'b','c', 'd'] final = numeros + letras print(final) numeros = [2, 3, 4, 5] letras = ['a', 'b','c', 'd'] numeros.extend(letras) print(numeros)''' '''itens = [['item1','item2'], ['item3','item4']] print(itens[0]) print(itens[0][0]) print(itens[0][1]) print(itens[1]) print(itens[1][0]) print(itens[1][1])''' """produtos = ['arroz', 'feijao', 'laranja','banana'] item1, item2, item3, item4 = produtos '''item1 = produtos[0] item2 = produtos[1] item3 = produtos[2] item4 = produtos[3]''' print(item1) print(item2) print(item3) print(item4)""" '''produtos = ['arroz', 'feijao', 'laranja','banana', 5, 6, 7, 8] item1, item2, *outros, item8 = produtos print(item1) print(item2) print(outros) print(item8)''' '''valores = [50, 80, 110, 150, 170] for x in valores: print(f'o valor final do produto é de R${x}')''' '''cor_cliente = input('digite a cor desejada: ') cores = ['amarelo', 'verde', 'azul', 'vermelho'] if cor_cliente.lower() in cores: print('cor em estoque') else: print('nao temos essa cor em estoque')''' '''cores = ['amarelo', 'verde', 'azul', 'vermelho'] valores = [10, 20, 30, 40] x = zip(cores, valores) print(list(x))''' '''frutas_usuario = input('digite o nome das frutas separadas por virgula: ') frutas_lista = frutas_usuario.split(', ') print(frutas_lista)''' cores_lista = ['amarelo', 'verde', 'azul', 'vermelho'] cores_tupla = ('amarelo', 'verde', 'azul', 'vermelho')
ddfc11be87059087a1f8ecd39cd66d25b284b9e8
green-fox-academy/judashgriff
/Week 5/practice2.py
172
3.515625
4
def dig_pow(n, p): k = 0 for i, char in enumerate(str(n)): k += pow(int(char), p + i) return int(k / n) if k % n == 0 else -1 print(dig_pow(46288, 3))
e8201a1aa529016e235589c4a92a38fda15d3b79
ethanzh/ut-search
/util.py
177
3.546875
4
def csv_to_list(file): with open(file) as input: lines = input.readlines() return [line.strip() for line in lines] #print(csv_to_list("listmaker_test.txt"))
6789de82b0e07423012c689a810f8126ad41f018
5362396/AiSD
/cwiczenia6/palindrom.py
490
3.734375
4
#wersja 1 def isPalindrome1(s): return s == s[::-1] #wersja 2 def isPalindrome2(str): for i in xrange(0, len(str)/2): if str[i] != str[len(str)-i-1]: return False return True #wersja 3 def isPalindrome3(s): rev = ''.join(reversed(s)) if (s == rev): return True return False #wersja 4 x = "malayalam" w = "" for i in x: w = i + w if (x==w): print("YES") s = "kamilślimak" ans = isPalindrome1(s) print(ans)
aab0ea81e7ea87ef368ab284b433b5e7026e38d7
Catboi347/python_homework
/digit_calculator.py
101
3.796875
4
number = input("Type in a number ") print ("The amount of digits in the number is", len(str(number)))
de622d9cd39e0939564138f8c3680ee67f39845a
shengchaohua/leetcode-solution
/leetcode solution in python/GroupsOfSpecialEquivlentStrings.py
723
3.609375
4
# -*- coding: utf-8 -*- """ Created on Sat Sep 8 15:46:48 2018 @problem: leetcode 893. Groups of Special-Equivalent Strings @author: shengchaohua """ class Solution: def numSpecialEquivGroups(self, A): """ :type A: List[str] :rtype: int """ return len({tuple(sorted(s[0::2]) + sorted(s[1::2])) for s in A}) def isSpecialEquivlent(s1, s2): if s1 == s2: return True # for i, letter in enumerate(s1): # ind = s2.find(letter) # if ind == -1 or ind % 2 != i % 2:: # return false # else: # pass # # return True