blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
831b7f2ee30d1c3a6502c01d36fe3a4b4121b32a
Yevgen32/Python
/Games/guess the number.py
273
3.84375
4
import random rezult = random.randint(1,100) number = 0 while number != rezult: number = int(input("Number:")) if number > rezult: print("Input less") elif number < rezult: print("Input more") elif number == rezult: print("Winnnn")
9449ffba731f3e23dd5e1f588bfb8040312d13fe
justinchoys/ctc_practice
/Chapter 1/1.4_Palindrome_Perm.py
645
3.71875
4
# -*- coding: utf-8 -*- """ Created on Wed Aug 15 15:06:36 2018 @author: justin """ #check if string is permutation of palindrom #concept: dict of palindrome has all values even, or all even except for one 1 def palinCheck(word): d = {} new_word = word.replace(" ","") for i in new_word: if i not in d.keys(): d[i] = 1 else: d[i] += 1 seen1 = False for key in d.keys(): if d[key] % 2 == 0: continue elif not seen1: seen1 = True else: return False return True s = 'racecar' #hello apple ' print(palinCheck(s))
1d2ca60e8e1aa88f22525a18ba615521b83ffe9e
Akash09-ak/Python-Scripting
/texting script.py
398
3.796875
4
import keyboard import time time.sleep(2) # to give some time for interpreter to execute for i in range(10): # here we are using loop for how many time we need to run our script keyboard.write("hy \n") # write() function take the text as input keyboard.press_and_release("enter") # here press_and_release() function used to enter hotkeys(like enter , shift+@, etc)
ba366bedf93f18b4ae06f90867cd5b44aed450c2
Drewsup123/Algorithms
/stock_prices/stock_prices.py
1,537
3.8125
4
#!/usr/bin/python import argparse def find_max_profit(prices): # min_buy = min(prices) # max_sell = max(prices) # min_buy = 10000 # max_buy = [0, 2] # index = 0 # for i in prices: # # if i > max_buy[0] and index > 0: # max_buy[0] = i # max_buy[1] = index # print("MAX", max_buy[0]) # # if i < min_buy and index < max_buy[1]: # min_buy = i # print("MIN:", min_buy) # index += 1 # # return max_buy[0] - min_buy max_profit = -10 # Yes there was a work around min_buy = 0 sell_price = 0 change_buy_index = True for i in range(0, len(prices) - 1): # this is so i doesn't go out of range on line 31 sell_price = prices[i + 1] if change_buy_index: min_buy = prices[i] if sell_price < min_buy: change_buy_index = True continue else: temp_profit = sell_price - min_buy if temp_profit > max_profit: max_profit = temp_profit change_buy_index = False return max_profit if __name__ == '__main__': # This is just some code to accept inputs from the command line parser = argparse.ArgumentParser(description='Find max profit from prices.') parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer price') args = parser.parse_args() print("A profit of ${profit} can be made from the stock prices {prices}.".format(profit=find_max_profit(args.integers), prices=args.integers))
35c4be29f6527801c194ff92b7d049b6016f400a
hdcsantos/Exercicios_Python_Secao_04
/41.py
295
3.765625
4
print("Salário líquido") ht = float(input("Informe o valor da hora trabalhada R$: ")) h = float(input("Informe o numero de horas trabalhadas no mês H: ")) bruto = h * ht liquido = bruto + (bruto * 0.10) print(f"O valor de hora/trabalho X horas, com a dicional de 10% é de R$ {liquido}")
341cd0976baacba7861ece23d93edb978470a343
theakhiljha/Ultimate-Logic
/Encryption/Reverse Cipher/reverse.py
519
4.15625
4
# an implementation of the ReverseCipher # Author: @ladokp class ReverseCipher(object): def encode(self, message: str): return message[::-1] def decode(self, message: str): return self.encode(message) # Little test program for ReverseCipher class message = input("Enter message to encrypt: ") encryptor = ReverseCipher() encoded_message = encryptor.encode(message) print("Encrypted text: {0}".format(encoded_message)) print("Decrypted text: {0}".format(encryptor.decode(encoded_message)))
53b4c8e1400808b78072f35cadf47b79eed3598e
stefan-toljic/MultipliedNumber
/main.py
771
4.09375
4
""" 1. Multiplied number Ask user to enter three numbers. If first number is > 10 write sum of second and third number to the console. If first number is <=10 write it directly to the console. """ def handle_input(message): while True: try: user_input = int(input(message)) break except ValueError: print("Invalid input: Please enter an integer.\n\t") return user_input num1 = handle_input("Please enter number 1:\n\t") num2 = handle_input("Please enter number 2:\n\t") num3 = handle_input("Please enter number 3:\n\t") if num1 > 10: print("\n- The sum of the 2nd and 3rd numbers is {}.".format(num2 + num3)) else: print(f"\n- The first number is {num1}.") # -------------------------------------------
b3efdc5a252e337daee389132af3ffc472b19931
aishux/March-LeetCode-Challenge
/SwappingNodesInLL.py
869
3.84375
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def swapNodes(self, head: ListNode, k: int) -> ListNode: # record for first kth node, last kth node, and running cursor first_k, last_k, cur = None, None, head # Step #1: locate first_k to corresponding position for _ in range(k-1): cur = cur.next first_k = cur # Step #2: locate last_k to corresponding position last_k, cur = head, cur.next while cur: cur, last_k = cur.next, last_k.next # Step #3: swap value between first kth node and last kth node first_k.val, last_k.val = last_k.val, first_k.val return head
6316e4fc4542d947593a23cece081552b64c15aa
anurag5398/DSA-Problems
/DynamicProgramming/UniquePathInaGrid.py
908
4.03125
4
""" Given a grid of size n * m, lets assume you are starting at (1,1) and your goal is to reach (n, m). At any instance, if you are on (x, y), you can either go to (x, y + 1) or (x + 1, y). Now consider if some obstacles are added to the grids. How many unique paths would there be? An obstacle and empty space is marked as 1 and 0 respectively in the grid. """ class Solution: def uniquePathsWithObstacles(self, A): #@param A : 2D int list #@return int if A[0][0] == 1: return 0 temp = [[0] * (len(A[0])+1) for i in range(len(A)+1)] temp[1][1] = 1 for i in range(1, len(temp)): for j in range(1, len(temp[0])): if A[i-1][j-1] == 0 and i+j > 2: temp[i][j] = temp[i-1][j] + temp[i][j-1] return temp[i][j] t = Solution() A = [[0,0,0], [1,1,1], [0,0,0] ] print(t.uniquePathsWithObstacles(A))
5ab84795cf738df8b76f13d505d9f84cf07ec8f7
lihip94/countingPolyominos
/test.py
2,339
3.734375
4
import unittest from counting_polyominos import counting_poly class TestCounting(unittest.TestCase): def test_sum(self): """ test that it can calculate sum of fixed polyominos from number x """ up_to_1 = counting_poly({(0, 0)}, set(), [], 1) up_to_2 = counting_poly({(0, 0)}, set(), [], 2) up_to_3 = counting_poly({(0, 0)}, set(), [], 3) up_to_4 = counting_poly({(0, 0)}, set(), [], 4) up_to_5 = counting_poly({(0, 0)}, set(), [], 5) up_to_6 = counting_poly({(0, 0)}, set(), [], 6) up_to_7 = counting_poly({(0, 0)}, set(), [], 7) up_to_8 = counting_poly({(0, 0)}, set(), [], 8) up_to_9 = counting_poly({(0, 0)}, set(), [], 9) up_to_10 = counting_poly({(0, 0)}, set(), [], 10) up_to_11 = counting_poly({(0, 0)}, set(), [], 11) up_to_12 = counting_poly({(0, 0)}, set(), [], 12) up_to_13 = counting_poly({(0, 0)}, set(), [], 13) up_to_14 = counting_poly({(0, 0)}, set(), [], 14) fixed_2 = up_to_2 - up_to_1 fixed_3 = up_to_3 - up_to_2 fixed_4 = up_to_4 - up_to_3 fixed_5 = up_to_5 - up_to_4 fixed_6 = up_to_6 - up_to_5 fixed_7 = up_to_7 - up_to_6 fixed_8 = up_to_8 - up_to_7 fixed_9 = up_to_9 - up_to_8 fixed_10 = up_to_10 - up_to_9 fixed_11 = up_to_11 - up_to_10 fixed_12 = up_to_12 - up_to_11 fixed_13 = up_to_13 - up_to_12 fixed_14 = up_to_14 - up_to_13 self.assertEqual(fixed_2, 2, "should be 2") self.assertEqual(fixed_3, 6, "should be 6") self.assertEqual(fixed_4, 19, "should be 19") self.assertEqual(fixed_5, 63, "should be 63") self.assertEqual(fixed_6, 216, "should be 216") self.assertEqual(fixed_7, 760, "should be 760") self.assertEqual(fixed_8, 2725, "should be 2725") self.assertEqual(fixed_9, 9910, "should be 9910") self.assertEqual(fixed_10, 36446, "should be 36446") self.assertEqual(fixed_11, 135268, "should be 135268") self.assertEqual(fixed_12, 505861, "should be 505861") self.assertEqual(fixed_13, 1903890, "should be 1903890") self.assertEqual(fixed_14, 7204874, "should be 7204874") if __name__ == '__main__': unittest.main() print("Everything passed")
0d42b3489badf0f1f416f80b1c060348a08500e4
bkruszewski/Python_Courses_2017-2019
/a140917/While.py
326
3.734375
4
#while True: # print ("Hello") #stan = True #while stan: # print (100) # stan = False #liczba = 1 #while liczba <= 100: # print(liczba) # liczba +=1 liczba = 1 while liczba <= 100: if liczba % 2 == 0: print (liczba, "parzysta") else: print(liczba, "nieparzysta") liczba +=1
1e2a630703c085637f233a54e24e2588a462daa9
jwjenkins0401/Oct-10-lists
/October10.py
1,442
4.21875
4
# This is the grading program we looked at earlier # 4) Grading program - if score is > 90 you get an A, ## > 80 < 90 you get a B ## > 70 < 80 a C ## > 60 < 70 a D ## anything else you flunk grade = 55 if grade >= 90: print("A") elif grade >= 80: print("B") elif grade >= 70: print("C") elif grade >= 60: print("D") else: print("You Flunked!") # We changed it to a Function: def grader(grade): if grade >= 90: return "A" elif grade >= 80: return "B" elif grade >= 70: return "C" elif grade >= 60: return "D" else: return "You Flunked!" g = grader(60) print(g) grades = [75,80,90,60,65,85] def term_grader(grade): term = sum(grade) / len(grade) return grader(term) print(term_grader(grades)) ## Note, I cheated with the sum function: # # Here is a home grown one # def sum_list(items): sum_numbers = 0 for x in items: sum_numbers += x return sum_numbers def term_grader2(grade): term = sum_list(grade) / len(grade) return grader(term) print(term_grader2(grades)) # 1. Write a program to multiply the numbers in a list. ## Hint *= is a thing # 2. Write a program to get the largest number in a list # 3. Assume: law_class = ["Matthew", "Hunter", "Marianna", "Brittany", "Harrison", "James","Bradley"] # Print "Hunter" # 4. Print out each name in law_class # 5. Put the law_class in alphabetical order
38700d8527ea41913a37460a967e8202f59aa27e
AndresFWilT/MisionTIC-2022_C1
/venv/Scripts/reto_4MINTIC2022c1.py
798
3.671875
4
def msjOrigi(m): msj = ""; for i in range(len(m)): msj += m[i] + " "; return msj; def mensajeEncr(d,m): encr = ""; for i in range(len(m)): for j in range(len(d)): if(m[i]== d[j]): try: encr += d[j+1]; except: print(""); return encr + "\n" +msjOrigi(m); def separar(dicc,mensaje): m = mensaje.split(","); d = []; for i in range(len(dicc)): try: if (dicc[i-1] == '"' and dicc[i+1] =='"'): d.extend(dicc[i]); except: print(""); return mensajeEncr(d,m); diccionario = input(str("Ingrese el diccionario: ")); mensaje = input(str("Ingrese el mensaje encriptado: ")); print(separar(diccionario,mensaje));
2d4dba7aad824b47396020996b8a89a8276fa2a3
tylerbrown1857/Week-Three-Assignment
/StarWars/StarWars.py
555
4.125
4
__author__ = "Tyler Brown" __program__ = "StarWarsName" __assignment__ = "WeekThreeLab" def main(): x = 0 while x != 1: #recieve input first = input("Enter your first name: ") last = input("Enter your last name: ") mother = input("Enter your mother's maiden name: ") city = input("Enter the city you were born in: ") #compiles first name starFirst = last[0:3] + first[0:2] starLast = mother[0:2] + city[0:3] #prints new name print(starFirst + starLast) main()
c7e5593464895f2778b0137c258b2f5ec9d8c41e
MaxSaunders/1aDay
/rotateLeft3.py
399
4.3125
4
""" Given an array of ints length 3, return an array with the elements "rotated left" so {1, 2, 3} yields {2, 3, 1}. rotate_left3([1, 2, 3]) → [2, 3, 1] rotate_left3([5, 11, 9]) → [11, 9, 5] rotate_left3([7, 0, 0]) → [0, 0, 7] """ def rotate_left3(nums): temp = nums[0] for i in range (len(nums) - 1): nums[i] = nums[i + 1] nums[len(nums) - 1] = temp return nums
767e34e152a2123d71676f73347631b054230bc5
huahuaxiaoshao/Python
/Algorithm/排序/插入排序.py
471
3.875
4
class Solution: def insertion_sort(self,array): if array == []: return for i in range(len(array)): pre_index = i - 1 current = array[i] while pre_index >= 0 and current < array[pre_index]: array[pre_index + 1] = array[pre_index] pre_index -= 1 array[pre_index + 1] = current return array a = [3,4,2,6,7,1,9,8,0,5] print(Solution().insertion_sort(a))
6c62eedc216fa9aad28489e66e6d55b4bebb5751
Devalekhaa/deva
/set29.py
216
4.125
4
def factorial(num): if num == 1: return num else: return num * factorial(num - 1) num = int(input()) if num < 0: print(num) elif num == 0: print() else: print(factorial(num))
e46ded97444973e5ad8c45b94f1fbd81a2fb46cc
6igsm0ke/Introduction-to-Programming-Using-Python-Liang-1st-edtion
/CH13/EX13.17.py
1,755
3.984375
4
# 13.17 (Process large dataset) A university posts its employee salary at http://cs # .armstrong.edu/liang/data/Salary.txt. Each line in the file consists of faculty first # name, last name, rank, and salary (see Exercise 13.16). Write a program to display # the total salary for assistant professors, associate professors, full professors, and # all faculty, respectively, and display the average salary for assistant professors, # associate professors, full professors, and all faculty, respectively. import urllib from urllib import request #file = open("database.txt", "r") file = urllib.request.urlopen("http://cs.armstrong.edu/liang/data/Salary.txt") data = file.readlines() sumAssistant = 0 countAssistant = 0 sumAssociate = 0 countAssociate = 0 sumFull = 0 countFull = 0 for line in data: line = line.split() if line[2] == "assistant": sumAssistant += eval(line[3]) countAssistant += 1 elif line[2] == "associate": sumAssociate += eval(line[3]) countAssociate += 1 else: sumFull += eval(line[3]) countFull += 1 print("The total salary for assistant professors: ", sumAssistant) print("The total salary for associate professors: ", sumAssociate) print("The total salary for full professors: ", sumFull) print("The total salary for all faculty: ", (sumFull + sumAssociate + countAssistant)) print("The average salary for assistant professors: ", sumAssistant / countAssistant) print("The average salary for associate professors: ", sumAssociate / countAssociate) print("The average salary for full professors: ", sumFull / countFull) print("The average salary for all faculty: ", (sumFull + sumAssociate + countAssistant) / (countAssociate + countFull + countAssistant))
e247b85788d23727fd504ca5d141c1f7317d3bdb
wenima/codewars
/kyu3/Python/src/sudoku_solver_hard_cw_submission.py
10,594
3.84375
4
""" Solution for code-kata https://www.codewars.com/kata/hard-sudoku-solver This version contains less code than the original solution I came up with as implementing the naked pairs/set/quads strategy increased the run time slightly while adding more complexity so it won't be included in the final submission on codewars. For the CW submission, the pre-set version of Python is 2.7.6 so this code targets that version. """ from math import sqrt, ceil from itertools import islice, chain, permutations from operator import itemgetter from collections import defaultdict from functools import reduce from copy import deepcopy def initialize_dicts(m, square_sides): """Return a tuple of dicts for a given matrix and the size of the sudoku.""" rows_missing = defaultdict(list) rows_missing = initialize_d(rows_missing, square_sides) cols_missing = defaultdict(list) cols_missing = initialize_d(cols_missing, square_sides) squares_missing = defaultdict(list) squares_missing = initialize_d(cols_missing, square_sides, 1) return rows_missing, cols_missing, squares_missing def initialize_d(d, square_sides, offset=0): """Return an initialized dict so empty rows or columns in the Sudoku are correctly handled.""" return {key:[] for key in range(offset, square_sides ** 2 + offset)} def populate_dicts(m, square_sides, dicts): """Return dicts holding information about fills in given Sudoku.""" sq_nr = 0 square_coords = {} for row in range(0, square_sides ** 2, square_sides): for col in range(0, square_sides ** 2, square_sides): sq_nr += 1 square = [islice(m[i], col, square_sides + col) for i in range(row, row + square_sides)] dicts, square_coords = fill_given_numbers(square, row, col, sq_nr, dicts, square_coords) return dicts, square_coords def get_candidates(m, dicts, square_coords): """Return a dict of candidates for all starting_spots in the Sudoku.""" starting_spots = get_starting_spots(m, dicts, square_coords) starting_spots.sort(key=itemgetter(2)) rm, cm, sm = dicts c = {} for coordinate in starting_spots: row, col, missing = coordinate c[(row, col)] = [n for n in cm[col] if n in rm[row] and n in sm[square_coords[row, col]]] if not c[(row, col)]: raise ValueError return c def get_starting_spots(m, dicts, square_coords): """Return a list with coordinates as starting point for sudoku solver.""" rm, cm, sm = dicts starting_spots = [] row = 0 col = 0 max = 20 start = -1 for col in range(9): for row in range(9): if m[row][col] == 0: square = square_coords[(row, col)] - 1 missing_numbers = len(cm[col]) + len(rm[row]) + len(sm[1 if square < 1 else square]) starting_spots.append((row, col, missing_numbers)) return starting_spots def setup(m): """ Return a list of candidates, helper_dicts and square_coords Store all starting numbers by looping through the Sudoku square by square Find all missing numbers by subtracting the 2 sets Generate all starting spots and find the one with the least amount of digits missing Generate candidates by finding all possible numbers for a given starting point """ square_sides = int(sqrt(len(m))) dicts = initialize_dicts(m, square_sides) dicts, square_coords = populate_dicts(m, square_sides, dicts) dicts = get_missing(dicts) try: candidates = get_candidates(m, dicts, square_coords) except ValueError as e: raise ValueError(e) return candidates, dicts, square_coords def get_missing(dicts): """Return dictionaries with swapped values from given numbers to missing numbers.""" for d in dicts: for k, v in d.items(): d[k] = set([1, 2, 3, 4, 5, 6, 7, 8, 9]) - set(v) return dicts def sudoku_solver(m, setup_return): """ Return a valid Sudoku for a given matrix, helper dicts, a list of candidates and a lookup for coords matching squares. Fill in simple numbers using scanning technique Find single candidates and fill in Look for naked pairs and eliminate from candidates Look for naked sets and eliminate from candidates """ candidates, dicts, square_coords = setup_return m = scan_sudoku(m, setup(m)) if candidates: single_candidates = single_candidate(setup(m)) else: return m m = fill_fit(m, get_candidates(m, dicts, square_coords), single_candidates=single_candidates) candidates = get_candidates(m, dicts, square_coords) return m def scan_sudoku(m, setup_return): """ Return an updated Sudoku and a list of candidates akin to the scanning technique where obvious fits are filled in. After each fit, list of candidates is rebuild until no further immediate fills are possible. """ candidates, dicts, square_coords = setup_return while True: if len(sorted(candidates.items(), key=lambda x: len(x[1])).pop(0)[1]) > 1: # no longer easily solvable break m = fill_fit(m, get_candidates(m, dicts, square_coords)) starting_spots = get_starting_spots(m, dicts, square_coords) starting_spots.sort(key=itemgetter(2)) candidates = get_candidates(m, dicts, square_coords) if not candidates: break return m def single_candidate(setup_return): """ Return a number which is a single candidate for a coordinate in the list of candidates: Build a dict with square as key and empty fields as value Go through every square and get all missing fields For every missing field in that square, get the possible numbers Look for a number which is only missing in one field in a square. """ candidates, dicts, square_coords = setup_return rm, cm, sm = dicts out = [] coords_missing_in_square = squares_to_missing(square_coords) for k, v in coords_missing_in_square.items(): single_candidates = defaultdict(list) seen = set() for coord in v: pn = set(candidates[coord]) if pn.issubset(seen): continue for n in pn: if n in seen: continue if single_candidates.get(n, 0): seen.add(n) continue single_candidates[n] = coord if len(seen) == len(sm[k]): continue out.append([(k, v) for k, v in single_candidates.items() if k not in seen]) return list(chain.from_iterable(out)) def squares_to_missing(square_coords): """Return a dict of square numbers as key and empty fields in the Sudoku as values.""" squares_missing = defaultdict(list) for k, v in square_coords.items(): squares_missing[v].append(k) return squares_missing def fill_given_numbers(square, row, col, sq_nr, dicts, sq): """Fill dicts with given numbers number for a given square.""" rm, cm, sm = dicts for row_idx, sr in enumerate(square): for col_idx, sv in enumerate(sr): coord = (row + row_idx, col + col_idx) if sv == 0: sq[coord] = sq_nr continue rm[coord[0]].append(sv) cm[coord[1]].append(sv) sm[sq_nr].append(sv) return dicts, sq def fill_fit(m, candidates, single_candidates=[]): """ Return an updated Sudoku by either finding a fit or taking a fit from a provided list of fits and filling it in as long as a fit is found. """ while True: try: if single_candidates: num, coord = single_candidates.pop() fit = (coord[0], coord[1], num) else: fit = find_fit(candidates) except IndexError: return m if fit: m = update_sudoku(fit, m) candidates, dicts, square_coords = setup(m) else: return m def find_fit(candidates): """Return a tuple with coordinate and value to update from a sorted representation of a dict. If no fit can be found, return None.""" fit = sorted(candidates.items(), key=lambda x: len(x[1])).pop(0) row, col = fit[0] n = fit[1].pop() if len(fit[1]) == 0: return row, col, n return None def update_sudoku(fit, m): """Return an updated Sudoku.""" row, col, n = fit m[row][col] = n return m def fill_square(brute_m, candidates, sq_p): """ Return True if all coordinates an be filled with a given permutation without invalidating the sudoku. Else return False. """ for fit in sq_p: coord, n = fit if n not in candidates[coord]: return False row, col = coord brute_m = update_sudoku((row, col, n), brute_m) return True def solver(board): """Return a solved Sudoku for a given Sudoku or raise a ValueError if not solvable.""" m = sudoku_solver(list(board), setup(board)) if valid(m): return m #Sudoku solved after the first run return rec_solver(m) def rec_solver(m): """Return a sudoku by recursively calling itself which triggers the next brute force of a square.""" candidates, dicts, sq = setup(m) rm, cm, sm = dicts square, coords = sorted(squares_to_missing(sq).items(), key = lambda x: len(x[1]), reverse=True).pop() missing = sm[square] for p in permutations(missing): #try all combinations of fields and missing numbers candidates, dicts, square_coords = setup(m) sq_p = tuple(zip(coords, p)) brute_m = deepcopy(m) if not fill_square(brute_m, candidates, sq_p): continue try: brute_m = sudoku_solver(list(brute_m), setup(m)) except ValueError as e: continue if not valid(brute_m): brute_m = rec_solver(brute_m) if not brute_m: continue return brute_m def valid(board): """Retrun True if the given matrix is a valid and solved sudoku.""" sq = int(sqrt(len(board))) size = sq * sq rows = board cols = [map(lambda x: x[i], board) for i in range(9)] squares = [reduce(lambda x, y: x + y, map(lambda x: x[i:(i + sq)], board[j:(j + sq)])) for j in range(0, size, sq) for i in range(0, size, sq)] for clusters in (rows, cols, squares): for cluster in clusters: if len(set(cluster)) != 9: return False return True
7798caaf15ecce933485acdb7d5414119c87d0d1
Pyabecedarian/Data_Sructure-Algorithm__Learning
/excersices/task5/max_depth.py
988
3.765625
4
""" Max depth of btree """ # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def maxDepth(root: TreeNode) -> int: # ugly d = 0 if root: stack = [root] d += 1 while stack: moreLayer = False subNodes = [stack.pop() for _ in range(len(stack))] for subNode in subNodes: if subNode.left: stack.append(subNode.left) moreLayer = True if subNode.right: stack.append(subNode.right) moreLayer = True if moreLayer: d += 1 return d def maxDepth_v2(root: TreeNode) -> int: """DFS method""" if not root: return 0 else: leftHeight = maxDepth_v2(root.left) rightHeight = maxDepth_v2(root.right) return max(leftHeight, rightHeight) + 1
e1b46574c26f06c0f043aaa8cc33582b137f38fe
NMTPythonistas/nmt_python_labs
/labs/lab5/test_lettercount.py
1,153
3.890625
4
""" This test assumes your function is named `count_letters`. This function must take a string and return a dictionary. """ import unittest class TestCountLetters(unittest.TestCase): test_cases = [("", dict()), ("abc", {'a': 1, 'c': 1, 'b': 1}), ("ABC abc", {'a': 2, 'c': 2, 'b': 2}), ("The cat in the hat", {'h': 3, 'i': 1, 'c': 1, 't': 4, 'n': 1, 'a': 2, 'e': 2}), ("A partial solar eclipse will occur on August Third", {'h': 1, 'c': 3, 'o': 3, 'w': 1, 'n': 1, 't': 3, 'd': 1, 'l': 5, 'i': 4, 'p': 2, 'g': 1, 'r': 4, 'a': 5, 's': 3, 'u': 3, 'e': 2} )] def test_validate(self): import lettercount for test_input, test_output in TestCountLetters.test_cases: with self.subTest(i=test_input): print("given", "'{}'".format(test_input), "should output", test_output) self.assertEqual(lettercount.count_letters(test_input), test_output) if __name__ == '__main__': unittest.main()
c89fdcc3fd0b742093a69ddc7dfe209301b25dc1
17621251436/leetcode_program
/匹配/1008 先序遍历构造二叉树.py
609
3.734375
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def bstFromPreorder(self, preorder: List[int]) -> TreeNode: if not preorder: return None root=TreeNode(preorder[0]) i=1 while i<len(preorder): if preorder[i]>root.val: break i+=1 root.left=self.bstFromPreorder(preorder[1:i]) root.right=self.bstFromPreorder(preorder[i:]) return root
f41c2b33f50ac9cc92d0f6f53c92118b28110e05
IsseW/Python-Problem-Losning
/Workshop 3/while.py
681
4.0625
4
""" Uppgift 1 - while-loop Skriv ett program, som frågar efter ett heltal mindre än 100. Programmet ska sedan summera detta tal och alla i ordningen efterföljande heltal tills summan av talen är större än tvåhundra. Skriv ut det sista talet som tas till summan och hela summan. """ should_exit = False sum = 0 while (not should_exit) and sum < 200: input_string = input("Enter a number less than 100: ") if input_string == "q" or input_string == "quit": should_exit = True else: num = int(input_string) if num >= 100: print(num, "is not less than 100.") else: sum += num print("Sum = ", sum)
e270c59c7d4af031d08a00182460deea8963e31f
nuotangyun/qq
/regis.py
1,222
3.703125
4
""" 模拟注册过程 """ import pymysql class Database: def __init__(self): # 连接数据库 self.db = pymysql.connect(host='localhost', port=3306, user='root', password='123456', database='stu', charset='utf8') # 生成游标对象 (操作数据库,执行sql语句) self.cur = self.db.cursor() def close(self): # 关闭游标和数据库连接 self.cur.close() self.db.close() def register(self, name, passwd): # 判断用户名是否重复 sql = "select name from user where name=%s;" self.cur.execute(sql, [name]) result = self.cur.fetchone() if result: print("该用户存在") return try: sql = "insert into user (name,passwd) \ values (%s,%s);" self.cur.execute(sql, [name, passwd]) self.db.commit() except: self.db.rollback() if __name__ == '__main__': db = Database() db.register('zhang', '123') db.close()
80641caf66e52b34e76d838ea1fe73a30180eaa9
itsss/SASA_OOP
/exam01_answer_code/no1.py
493
4.0625
4
''' 다음 Code를 보고, 실행 결과를 작성하시오. ''' my_list = [1,2,3,4,5] print(my_list[-1]) # 5 print(my_list.pop()) # 5 print(my_list.pop(1)) # 2 my_list = [1,2,3,4,5] my_list.remove(3) print(my_list) # [1, 2, 4, 5] my_list = [1,2,3,4,5] my_list.append([4, 5]) print(my_list) # [1, 2, 3, 4, 5, [4, 5]] my_list = [1,2,3,4,5] print(my_list[::-1]) # [5, 4, 3, 2, 1] sasa = "Sejong Academy of Science and Arts" print(sasa[2:6:2]) # jn a=10 b=10 print(id(a) == id(b)) # True
69f775ea5bc117ba1c2462c9cfbc9e5264cff09b
VbaGGz/LeetCode
/Find Numbers with Even Number of Digits/Digits_Count.py
226
3.8125
4
nums = [12,345,2,6,7896] def findNumbers(nums) -> int: count = 0 for num in nums: if len(str(num)) % 2 == 0: count += 1 else: continue return count print(findNumbers(nums))
9f277b181804568cb414139c12eb0885cbbafbd4
meadorjc/PythonLearning
/e_11.py
435
3.828125
4
#Caleb Meador meadorjc at gmail.com print("How old are you?"), age = input() print("How tall are you?"), height = input() print("How much do you weight?"), weight = input() name = input("\n\n\twhat is your name?") age1 = int(input("how old are you again? ")) age2 = int(input("how old is your dog? " )) print("So, you're", age, "old,", height, "tall and", weight, "heavy."); print("Between you,",name,", you are",age1+age2,"years old")
45181ddfeae8837e7399facda86912ed834ecaf2
xiaohuanlin/Algorithms
/Intro to algo/chapter 2/BinarySearch.py
876
3.75
4
import unittest def binary_search(A, v): ''' :param A: sorted int list :param v: target value :return: the index of the value, the complex is O(lgn) ''' if len(A) == 1: return 0 if A[0] == v else None q = len(A) // 2 if A[q] > v: return binary_search(A[:q], v) else: return binary_search(A[q:], v) + q class TestSolution(unittest.TestCase): def test_case(self): examples = ( (([3], 3), 0), (([1,2,3,4,5], 3), 2), (([5,1,3,4,1], 3), 2), (([1,5,2], 3), None) ) for first, second in examples: self.assert_function(first, second) def assert_function(self, first, second): self.assertEqual(binary_search(*first), second, msg="first: {}; second: {}".format(first, second)) unittest.main()
ecbbfd57def8c411b502ad4c0f50883b9194b7ad
thiagofb84jp/python-exercises
/pythonBook/chapter03/exercise3-13.py
196
3.9375
4
""" 3.13. Conversor de Celsius para Fahrenheit """ celsius = float(input("Digite a temperatura em °C: ")) fahrenheit = (9 * celsius / 5) + 32 print(f"{celsius}°C equivale a {fahrenheit}°F.")
944b4f3ceb28868293180214e9d589319680b6da
MasBad/pythonintask
/PMIa/2015/ANDROS_D_A/task_5_49.py
470
3.65625
4
#Задача 5.Вариант 49. #Напишите программу, которая бы при запуске случайным образом отображала название одного из девяти действующих вокзалов Москвы. #Andros D.A. #28.04.2016 import random vokzaly=["Belorusskiy","Kazanskiy","Kievskiy","kurskiy","Leningradskiy","Paveletskiy","Riszkiy","Savelovskiy","Yaroslavskiy"] v=random.choice(vokzaly) print(v)
3befcb2d9b5cc0f829061f22f084b389c4e4760a
mateusguida/ExerciciosPython
/ex068.py
837
3.65625
4
import os os.system("cls") #limpa janela terminal antes da execução from random import randint print("=-" * 15) print("VAMOS JOGAR PAR OU ÍMPAR") vit = 0 while True: print("=-" * 15) num = int(input("Digite um valor: ")) jogador = str(input("Par ou Ímpar? [P/I]")).strip().upper()[0] comp = randint(0,10) soma = num + comp print('-' * 30) print(f'Você jogou {num} e o computador {comp}. ', end="") if soma % 2 == 0: print(f'Total de {soma} DEU PAR') flag = 'P' else: print(f'Total de {soma} DEU ÍMPAR') flag = 'I' print('-' * 30) if jogador == flag: vit += 1 print("Você VENCEU!") print("Vamos jogar novamente...") else: print("Você PERDEU!") break print(f'GAME OVER! Você venceu {vit} vezes.')
42624beed395508a8f1974bbcdb6aba3cefbb4db
s3714217/IOT-GreenhouseMonitor
/data/sqlite_repository.py
1,434
3.59375
4
import sqlite3 ''' Generic SQLite repository ''' class SqliteRepository(): SEPARATOR = ", " INSERT_SQL = "INSERT INTO %s (%s) VALUES (%s)" ONLY_DEFAULT_VALUES_INSERT_SQL = "INSERT INTO %s DEFAULT VALUES" def __init__(self, database): self.__database = database ''' Executes the supplied SQL query ''' def execute(self, sql, args = None): with sqlite3.connect(self.__database) as connection: if (args is not None): return connection.execute(sql, args) else: return connection.execute(sql) ''' Insert an entry into specified table with supplied items dictionary Prone to SQL Injection - But we would realistically use some sort of ORM ''' def insert(self, table, items): # Split out the dictionary into separate lists keys = [] values = [] if items is not None: for key, value in items.items(): keys.append(key) values.append(str(value)) # Join each list into single strings keys_joined = self.SEPARATOR.join(keys) values_joined = self.SEPARATOR.join(values) # Insert into database if (len(keys) > 0): return self.execute(self.INSERT_SQL % (table, keys_joined, values_joined)) else: return self.execute(self.ONLY_DEFAULT_VALUES_INSERT_SQL % table)
2ef12b81aa4b5fc3ef4298b92680251a9bb98a76
gracejansen227/CodingDojoAssignments
/Python Stack/OOP/hospital.py
1,402
3.71875
4
#hospital import random class Patient(object): def __init__(self, name, allergies): self.id = random.randrange(1,501) self.name = name self.allergies = allergies self.bedNum = 0 class Hospital(object): def __init__(self): self.patients = [] self.name = 'Da Hospital Yo' self.capacity = 500 def admit(self, p): if len(self.patients) >= self.capacity: print "The hospital is at capacity. Cannot admit patient" else: self.patients.append(p) for element in self.patients: print element.name, element.id p.bedNum =random.randrange(1,501) print "Admitted patient#", p.id, "Name", p.name, "to bed#",p.bedNum #print self.patients #why isn't self.patients printing out list -- its only printing object instance return self def discharge(self, inputName): self.input = inputName for i in self.patients: if i.name == inputName: index = self.patients.index(i) self.patients.pop(index) i.bedNum = 0 print i.name, i.bedNum, "Has been discharged" return self patient1 = Patient("Grace", "cats") patient2 = Patient("Patricia", "tide") hospital1= Hospital() hospital1.admit(patient1) hospital1.admit(patient2) hospital1.discharge("Patricia")
2c1a05d74485982b8b3ec9e72e788feeb9816b66
KDiggory/pythondfe
/PYTHON/Files/Files.py
1,213
3.828125
4
#help(open) ##opens the help info for the inbuilt method open openedfile = open("README.md") print(openedfile) ## prints metadata - (open file IO type of data). Not the contents of the file! #help(openedfile) ## will then open help for the new variable you've made - can see there is a read function in there. ## help very useful to see what you can do with the file filecontents = openedfile.read() ## makes a variable of the contents of the file filecontents = filecontents + "\nI'm adding some useful contents as a test" # can then add to the file, the \n adds it on a new line filecontents = filecontents + "\nand another new line here" print(filecontents) ## README.md is a read only file so can't save into it! Would need to copy the contents to a new file in order to save it. #writefile = open("README.md.new","w") # this makes a new variable of the README.md file that is a new copy that is writable writefile = open("README.md.new", "a+") writefile.write(filecontents) print(writefile) # prints the metadata for the file - need to read it contentswritefile = writefile.read() print(contentswritefile) openedfile.close() # to close the files writefile.close() print("Finished")
28feba8e0eca7b22fc117ab5ecace6408cb0b72c
villarrealp/sudokuD
/Code/SudokuTXTWriter.py
2,061
3.625
4
""" Author: Pilar Villarreal Date created: 07/18/2013 Description: This class creates a .txt file with a generated unsolved game. Modified: Comments: Revised by: """ import datetime """ Class Name: SudokuTXTWriter Description: This class creates a .txt file with a generated unsolved game. Attributes: matrixGenerated -- Matrix of chars to be stored in a .txt file """ class SudokuTXTWriter: def __init__(self, matrix): """ This method initialize the SudokuTXTWriter class. Keyword string: matrix -- Matrix of chars which contains a generated Sudoku Game """ self.matrixGenerated = matrix def writeToTXTFile(self): """ This method writes the generated matrix to a .txt file using a generated name for the file. """ nameGenerated = self.generateNameForFile() outFile = open(nameGenerated, 'w') for i in range(9): rowString = "" for j in range(9): <<<<<<< HEAD if (self.matrixGenerated[i][j] != "."): rowString += str(self.matrixGenerated[i][j])+"" else: rowString += "0" + "" ======= rowString += str(self.matrixGenerated[i][j])+" " >>>>>>> 332443f231733e534c8d05dedd4093438c9c7692 outFile.write(rowString+'\n') outFile.close() print("File named: %s was created." %nameGenerated) def generateNameForFile(self): """ This method will generate a name for the file which contains generated Sudoku game. The name generated will be based on datetime to avoid duplicates. Return: String of the file name generated. """ basename = "Generated" <<<<<<< HEAD suffix = datetime.datetime.now().strftime("%y-%m-%d_%H%M%S") + ".txt" ======= suffix = datetime.datetime.now().strftime("%y-%m-%d_%H%M%S") >>>>>>> 332443f231733e534c8d05dedd4093438c9c7692 fileName = "_".join([basename, suffix]) return fileName
fde5ab5b780d6c06c55c44e22466b12a5eabe8a5
jaydavey/python-examples
/basic-python/learn-python-in-one-day/ch6/ex_ch6.4_for_loop.py
475
3.734375
4
#python3 pets = ['cats','dogs','rabbits','hamsters'] for i in pets: print(i) for index, i in enumerate(pets): print(index, i) age = {'Peter':5,'John':7} for i in age: print(("Name = %s, Age = %d" %(i, age[i]))) for i,j in list(age.items()): #python2.7 print("Name = %s, Age = %d" %(i,j)) for i in list(range(5)): print(i) j = 0 for i in list(range(5)): j = j + 2 print("\ni = ", i, ", j = ", j) if j == 6: continue print('I will be skipped over if j=6')
0281bf5fabdf0edea90a5f85c5884036d5aff68e
Sabhari-CEG/Python-dataStructures-training
/Trees/Binary_Search_tree.py
4,849
3.828125
4
class Node(): def __init__(self,data = None): self.data = data self.left_child = None self.right_child = None class BinarySearchTree(): def __init__(self): self.root_node = None def find_min(self): current = self.root_node while current.left_child: current = current.left_child return current.data def find_max(self): current = self.root_node while current.right_child: current = current.right_child return current.data def insert(self,data): current = self.root_node parent = None node = Node(data) if current is None: self.root_node = node else: while True: parent = current if node.data <= current.data: current = current.left_child if current is None: parent.left_child = node return else: current = current.right_child if current is None: parent.right_child = node return def get_node_with_parent(self,data): parent = None current = self.root_node if current is None: return (None,None) while True: if current.data == data: return (parent,current) elif data <= current.data: parent = current current = current.left_child else: parent = current current = current.right_child return (parent,current) def remove(self,data): parent,node = self.get_node_with_parent(data) if (parent is None) and (node is None): return False children_count = 0 if node.left_child and node.right_child: children_count = 2 elif (node.left_child is None) and (node.right_child is None): children_count = 0 else: children_count = 1 print("no of child\t",children_count) if children_count == 0: #print("entered") if parent: if parent.left_child == node: parent.left_child = None else: parent.right_child = None else: self.root_node = None elif children_count == 1: next_node = None if node.left_child: next_node = node.left_child else: next_node = node.right_child if parent: if parent.left_child == node: parent.left_child = next_node else: parent.right_child = next_node else: self.root_node = next_node else: parent_of_leftmost_node = node leftmost_node = node.right_child while leftmost_node.left_child: parent_of_leftmost_node = leftmost_node leftmost_node = leftmost_node.left_child node.data = leftmost_node.data if parent_of_leftmost_node.left_child == leftmost_node: parent_of_leftmost_node.left_child = leftmost_node.right_child else: parent_of_leftmost_node.right_child = leftmost_node.right_child def search(self,data): current = self.root_node while current: if current is None: return False if current.data == data: return True elif data <= current.data: current = current.left_child else: current = current.right_child if __name__ == '__main__': tree = BinarySearchTree() tree.insert(5) print("root node\t",tree.root_node.data) tree.insert(3) tree.insert(9) print("max number in tree\n",tree.find_max(),'\nmin number in tree\n',tree.find_min()) tree.remove(9) print("removed 9 and we are searching for 9\t",tree.search(9)) tree.insert(9) tree.insert(12) print("inserted 12 and we are searching for 12\t",tree.search(12)) tree.remove(9) print("removed 9 and we are searching for 9\t",tree.search(9)) print("inserted 12 and we are searching for 12\t",tree.search(12)) tree.remove(12) tree.insert(9) tree.insert(7) tree.insert(13) tree.insert(12) tree.remove(9) print("removed 9 and we are searching for 9\t",tree.search(9)) print("max number in tree\n",tree.find_max(),'\nmin number in tree\n',tree.find_min())
d633210b5cf5925a42478955b173b32544c2be7e
josemorenodf/ejerciciospython
/Bucle for/BucleFor4.py
110
3.6875
4
print('Comienzo') for number in [0, 1, 2, 3]: print(f"{number} * {number} = {number ** 2}") print('Final')
91c4af4bfa8fda9b98a609d155fd0496aa44d2ea
abbytran1996/Blackout-Puzzle
/blackout.py
8,435
3.765625
4
""" Author: My Tran File name: cpmpute.py Purpose: Solve Black-out puzzle using Stack and Queue. 2 black-out squares. """ from number import * from operation import * def calculate( numStack, operStack ): """ Takes the first two numbers from the numStack and the first operation from the operStack Does the calculation. """ num1 = topNumber(numStack) numStack = popNumber( numStack ) num2 = topNumber(numStack) numStack = popNumber( numStack ) oper = topOperation( operStack ) operStack = popOperation( operStack ) if oper == '+': return num1 + num2, numStack, operStack elif oper == '-': return num2 - num1, numStack, operStack elif oper == '*': return num1 * num2, numStack, operStack elif oper == '/': #Divides by 0 if num1 == 0: return None, numStack, operStack return num2 / num1, numStack, operStack def compute( equation ): """ Takes each side of the equation, compute if it valid. :returns: the result If it's not valid, returns None. """ number = '' numStack = None operStack = None for i in equation: if i.isdigit(): #form a number of any length: number += i elif i in ['+', '-', '*', '/']: if number == '': return None numStack = pushNumber( numStack, int(number) ) number = '' #Check if the numStack is empty or not: operation = checkOperation( i ) if isEmpty( operStack ): operStack = pushOperation( operStack, operation ) else: topPre = topPrecedence( operStack ) if topPre >= operation.precedence: #Before calculating, always check the numStack again: if size(numStack) <=1: return None result, numStack, operStack = calculate( numStack, operStack ) if result == None: return None numStack = pushNumber( numStack, result ) operStack = pushOperation( operStack, operation) elif i == '(': operation = Operation( i, 0 ) operStack = pushOperation( operStack, operation) #In case 12(56+3) if number != '': return None elif i == ')': #In case: 6+5-) if number == '': return None numStack = pushNumber( numStack, int(number) ) number = '' # For example: 12) + 5 - 6 if isEmpty(operStack): return None while topPrecedence( operStack ) != 0 : if size(numStack) <=1: return None result, numStack, operStack = calculate( numStack, operStack ) if result == None: return None numStack = pushNumber( numStack, result ) #In case there is no '(': if isEmpty( operStack ): return None #Pop the '(' out of the operStack: operStack = popOperation( operStack ) #Push the last number to the numStack: if number != '': numStack = pushNumber( numStack, int(number) ) while not isEmpty(operStack) and not isEmpty(numStack): if topPrecedence(operStack) == 0: return None if size(numStack) <=1 and not isEmpty(operStack): return None result, numStack, operStack = calculate( numStack, operStack ) if result == None: return None numStack = pushNumber( numStack, result ) #The operStack is empty but there are more than one final number in the numStack: if isEmpty(operStack) and size( numStack ) != 1: return None return numStack.top.number def test( equation ): """ Tests if the equation has a valid form. If yes, computes each side and compares them. :returns: True if there is a solution Else: returns False. """ if "=" in equation: if equation.find('=') != 0 and equation.find( '=' ) != (len(equation) - 1) : expression = equation.split('=') leftResult, rightResult = compute( expression[0] ) , compute( expression[1] ) if leftResult == None or rightResult == None: return False elif leftResult == rightResult: return True else: return False else: return False else: return False def solve( equation ): """ Black out 2 squares in the equation. :returns: The correct blacked function. Or else returns None. """ for i in range( 0, len(equation) ): newEquation1 = equation[:i] + equation[i+1:] for j in range( i , len(newEquation1) ): newEquation2 = newEquation1[:j] + newEquation1[j+1:] result = test(newEquation2) if result == True: return newEquation2 return None def main(): """ Prompt users for the file name. Execute Black out functions on each line in the file. :returns: Solution if there is one, else inform that cannot find. """ inFile = input('Enter the file') for line in open(inFile): equation = line.strip() print( 'Original puzzle:', equation) solved = solve( equation ) if solved != None: print( 'Found solution:', solved) print('\n') else: print( 'Cannot find any solutions.') print('\n') ############## # TESTING ############## def compute_tests(): #Calculate operation with a higher precedence first: print( 'Compute: 2 + 3 * 6') print( 'Result is 20?', compute('2+3*6') == 20) print('\n') #Calculate in () first: print( 'Compute: 2 * (3 + 6)') print( 'Result is 18?', compute('2*(3+6)') == 18) print('\n') #Multi-digit numbers: print( 'Compute: 2 + 10 - 36') print( 'Result is -24?', compute('2+10-36') == -24) print('\n') #Equation with '(' but no ')': print( 'Compute: (12 + 3 - 6') print( 'No result?', compute('(12+3-6') == None) print('\n') #Equation with ')' but no '(': print( 'Compute: 12 + 3) - 6') print( 'No result?', compute('12+3)-6') == None) print('\n') #Equation with an operation at the beginning: print( 'Compute: + 12 - 6') print( 'No result?', compute('+12-6') == None) print('\n') #Equation with an operation at the end: print( 'Compute: 12 - 6 +') print( 'No result?', compute('12-6+') == None) print('\n') #Equation with two operations are next to each other: print( 'Compute: 12 + - 6') print( 'No result?', compute('12+-6') == None) print('\n') #No operation before '(' or after ')': print( 'Compute: 6(2 + 3) and (2 + 3)6') print( 'Both no result?', compute('6(2 + 3)') == None, compute('(2 + 3)6') == None) print('\n') def test_tests(): #Normal function: print( 'Test: 5 + 2 = 3 + 6') print( 'Valid but wrong?', test('5+2=3+6') == False) print('\n') #Normal function: print( 'Test: 5 + 4 = 3 + 6') print( 'Valid but right?', test('5+4=3+6') == True) print('\n') #Equation with '=' at the beginning: print( 'Test: = 5 + 2') print( 'Invalid?', test('=5+2') == False) print('\n') #Equation with '=' at the end: print( 'Test: 5 + 2 =') print( 'Invalid?', test('5+2=') == False) print('\n') #Equation with no '=': print( 'Test: 5 + 2 - 3') print( 'Invalid?', test('5+2-3') == False) print('\n') def solve_tests(): #Empty equation: print( 'Solve an empty equation.') print( 'Invalid?', solve('') == None) print('\n') #Equation with one or two elements: print( 'Solve: "3", "3+"') print( 'Both invalid?', solve('3') == None, solve('3+') == None ) print('\n') #Normal equation: print( 'Solve: 3+2=6') print( 'No solution?', solve('3+2=6') == None ) print('\n') #Normal equation: print( 'Solve: 3+2=3') print( 'Solution:', solve('3+2=3')) print('\n') if __name__ == "__main__": main() """ #Run testing functions compute_tests() test_tests() solve_tests() """
716f0e036e25608ab200eb72013469bd82bf023c
barneyhill/AOC19
/Day 1/main.py
481
3.828125
4
def read_input(): with open("input.txt") as f: file = f.readlines() file = [x.strip() for x in file] file = [int(x) for x in file] return file file = read_input() #part one def fuel(mass): return int(mass/3)-2 total = 0 for mass in file: total += fuel(mass) print(total) #part two total = 0 for mass in file: total -= mass while mass > 0: total += mass print(mass) mass = fuel(mass) print('\n') print(total)
2356a51fe0df76c731104a80bf310ceddfdd6469
inaram/workshops
/python2/scheduling.py
1,415
4.25
4
def sortedCalendar(myCalendar): print "Monday:", myCalendar["Monday"] print "Tuesday:", myCalendar["Tuesday"] print "Wednesday:", myCalendar["Wednesday"] print "Thursday:", myCalendar["Thursday"] print "Friday:", myCalendar["Friday"] print "Saturday:", myCalendar["Saturday"] print "Sunday:", myCalendar["Sunday"] def calendar(): myCalendar = {"Monday": "study", "Tuesday": "free", "Wednesday": "read", "Thursday": "cook", "Friday": "free", "Saturday": "party!", "Sunday": "volunteer"} print "Here is your current schedule: " sortedCalendar(myCalendar) while "free" in myCalendar.values(): print "You still have a free day" event = raw_input("What would you like to do? ") when = raw_input("When would you like to do it? ") for day in myCalendar: if day == when: if myCalendar[day] == "free": myCalendar[day] = event print "Sounds good! Now you have a new event,", event, ", scheduled on", day else: print "Sorry, you already have", myCalendar[day], "scheduled on", day else: print "Now your calendar is full. Here is what you have scheduled for next week: " print myCalendar.items() def main(): calendar() if __name__ == "__main__": main()
d6cbcc0ef65c66b676e61c5a3c17d7104a34d838
HarishKSrivsatava/DataStructureAndAlgorithms_Python
/Array/ArrayDemo.py
515
3.703125
4
from array import * myArr = array('i',[10,20,30]) for i in range(len(myArr)): print(myArr[i], end =" ") print("\n") # insertion : insert at the index myArr.insert(1,90) for i in myArr: print(i,end = " ") print("\n") # insertion : insert at the end myArr.append(100) for i in myArr: print(i, end = " ") print("\n") # deletion myArr.remove(10) print("\n") for i in myArr: print(i,end = " ") print("\n") # search print(myArr.index(100)) # Updation myArr[0] = 101 for i in myArr: print(i, end = " ")
32ad7a3f2318803af4b3d382034d3c83ccc401a2
qkrtndh/coding_test_python
/그리디,구현문제/7.py
881
3.609375
4
""" 알파벳 대문자와 숫자(0~9)로만 구성된 문자열이 입력으로 주어진다. 이때 알파벳을 오름차순으로 정렬하여 이어서 출력한 뒤에 모든 숫자를 더한 값을 이어서 출력한다.""" #아이디어 """입력된 값을 하나씩 읽어서 문자열은 따로 하나씩 list에 저장하고 숫자는 변수에 각기 더하고, list.sort후 출력하면 되지 않을까?""" """ string = input() result = 0 num=['0','1','2','3','4','5','6','7','8','9'] a = [] for i in string: if i in num: result+=int(ord(i)-ord('0')) else: a.append(i) a.sort() print(''.join(a)+str(result)) """ #개선 string = input() result = 0 a = [] #코드 간결화 for i in string: if i.isalpha(): a.append(i) else: result+=int(i) a.sort() #0처리 if(result!=0): a.append(str(result)) print(''.join(a))
51104fbc478b492d1a17b921eb366a6080e17a92
gr2y/leetcode
/solutions/binary_tree/bfs/199.py
575
3.578125
4
# https://leetcode.com/problems/binary-tree-right-side-view/ class Solution: def rightSideView(self, root: TreeNode) -> List[int]: if not root: return [] q = deque([root]) result = [] while q: n = len(q) for i in range(n): node = q.popleft() if i == n - 1: result.append(node.val) if node.left: q.append(node.left) if node.right: q.append(node.right) return result
7908314344ab87d5f95b2897288139ec37348ab7
yokomotoh/MachineLearnigExercises
/neuralNetPredictHandwrittenDigits.py
1,498
4.03125
4
from sklearn.datasets import load_digits import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.neural_network import MLPClassifier X, y = load_digits(return_X_y=True) # when only two digits, 0 and 1, n_class=2 # we will initially only be working with two digits (0 and 1), # so we use the n_class parameter to limit the number of target values to 2. print(X.shape, y.shape) # we have 300 datapoints and each datapoint has 64 features. # We have 64 features because the image is 8 x 8 pixels and we have 1 feature per pixel. # The value is on a grayscale where 0 is black and 16 is white. # print(X[0]) # print(y[0]) # print(X[0].reshape(8, 8)) #plt.matshow(X[3].reshape(8, 8), cmap=plt.cm.gray) #plt.xticks(()) # remove x tick marks #plt.yticks(()) # remove y tick marks #plt.show() X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=2) mlp = MLPClassifier(random_state=2) mlp.fit(X_train, y_train) x = X_test[10] plt.matshow(x.reshape(8, 8), cmap=plt.cm.gray) plt.show() print(mlp.predict([x])) print(mlp.score(X_test, y_test)) y_pred = mlp.predict(X_test) incorrect = X_test[y_pred != y_test] incorrect_true = y_test[y_pred != y_test] incorrect_pred = y_pred[y_pred != y_test] j = 0 plt.matshow(incorrect[j].reshape(8, 8), cmap=plt.cm.gray) plt.show() print("true value: ", incorrect_true[j]) print("predicted value: ", incorrect_pred[j]) print(incorrect.shape) print(incorrect) print(incorrect_true) print(incorrect_pred)
7e74a223c02ccef52c2ea51dd9aafd13d88dbfd1
wangqianyi2017/wqycode
/StudyPython/Python6.py
855
3.5625
4
#!/usr/bin/python # -*- coding: UTF-8 -*- # __author__ = 'wangqianyi1' def fin(n): a,b = 1,1 for i in range(n-1): a,b = b,a+b return a # 输出了第10个斐波那契数列 print fin(10) #使用递归 def fib(n): if n == 1 or n == 2: return 1 return fib(n-1)+fib(n-2) # 输出了第10个斐波那契数列 print fib(10) def fic(n): if n == 1: return [1] if n ==2: return [1,1] fics = [1,1] for i in range(2,n): fics.append(fics[-1]+fics[-2]) return fics #输出前10个斐波那契数列 print fic(10) # 输出第n个数 n = int(raw_input("第几个数: ")) # 斐波那契数列的通项公式 f =(1/(5**0.5))*(((1+(5**0.5))/2)**n - ((1-(5**0.5))/2)**n) print "第%d个数:"%n,int(f) # 输出前n个数列: l=[1] for i in range(1,n+1): f=(1/(5**0.5))*(((1+(5**0.5))/2)**i - ((1-(5**0.5))/2)**i) l.append(int(f))
2a514d99f12af58aec04b8d768ba131949358bb1
QingqinLi/hm
/old_boy/leetcode/leetcode_greedy.py
6,852
3.578125
4
# !/usr/bin/python # -*- coding: utf-8 -*- """ __author__ = 'qing.li' """ class Solution: """ Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times). Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). 跌就买涨就卖,画图简单 """ def maxProfit(self, prices) -> int: profit = 0 for i in range(len(prices)-1): if prices[i+1] - prices[i] > 0: profit += prices[i+1] - prices[i] return profit """ Given a string s and a string t, check if s is subsequence of t. You may assume that there is only lower case English letters in both s and t. t is potentially a very long (length ~= 500,000) string, and s is a short string (<=100). A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ace" is a subsequence of "abcde" while "aec" is not). 暴力求解 """ def isSubsequence(self, s: str, t: str) -> bool: begin = 0 flag = True after = t for se in s: # 关键条件 从当前找到的点的下一个点开始查找 after = after[begin:] for te in after: if se == te: begin = after.index(te) + 1 break # 任意点找不到 程序异常,退出程序 返回结果 else: flag = False break return flag """ Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child i has a greed factor gi, which is the minimum size of a cookie that the child will be content with; and each cookie j has a size sj. If sj >= gi, we can assign the cookie j to the child i, and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number. """ def findContentChildren(self, g, s) -> int: count = 0 g.sort() s.sort() for gi in g: for si in s: if si >= gi: count += 1 s.remove(si) break return count """ A robot on an infinite grid starts at point (0, 0) and faces north. The robot can receive one of three possible types of commands: -2: turn left 90 degrees -1: turn right 90 degrees 1 <= x <= 9: move forward x units Some of the grid squares are obstacles. The i-th obstacle is at grid point (obstacles[i][0], obstacles[i][1]) If the robot would try to move onto them, the robot stays on the previous grid square instead (but still continues following the rest of the route.) Return the square of the maximum Euclidean distance that the robot will be from the origin. 能到的最远距离,一步一步走,看下一步是不是障碍物 """ def robotSim(self, commands, obstacles) -> int: # list不可hash,无法set,转换成tuple obstacles = (set(map(tuple, obstacles))) start_point = [0, 0] direction = { "north": { -1: "east", -2: "west", }, "east": { -1: "south", -2: "north", }, "west": { -1: "north", -2: "south", }, "south": { -1: "west", -2: "east", } } direct = "north" result = [] for i in commands: if i == -1 or i == -2: direct = direction[direct][i] elif 1 <= i <= 9: for j in range(i): if direct == "north": start_point[1] += 1 if tuple(start_point) in obstacles: start_point[1] -= 1 break elif direct == "south": start_point[1] -= 1 if tuple(start_point) in obstacles: start_point[1] += 1 break elif direct == "east": start_point[0] += 1 if tuple(start_point) in obstacles: start_point[0] -= 1 break elif direct == "west": start_point[0] -= 1 if tuple(start_point) in obstacles: start_point[0] += 1 break result.append(pow(start_point[0], 2) + pow(start_point[1], 2)) return max(result) """ There are 2N people a company is planning to interview. The cost of flying the i-th person to city A is costs[i][0], and the cost of flying the i-th person to city B is costs[i][1]. · Return the minimum cost to fly every person to a city such that exactly N people arrive in each city. """ def twoCitySchedCost(self, costs) -> int: count_a, count_b = len(costs) // 2, len(costs) // 2 cost_value = [] costs.sort(key=lambda x: x[0]+x[1], reverse=True) cost = [] for i in costs: cost.extend(i) while cost: min_value = min(cost) min_index = cost.index(min_value) # print(min_index, min_value, cost, count_a, count_b) if count_a == 0: for m in range(len(cost)): if m % 2 == 1: cost_value.append(cost[m]) break elif count_b == 0: for m in range(len(cost)): if m % 2 == 0: cost_value.append(cost[m]) break else: if min_index % 2 == 0: count_a -= 1 cost_value.append(min_value) cost.pop(min_index) cost.pop(min_index) else: count_b -= 1 cost_value.append(min_value) cost.pop(min_index - 1) cost.pop(min_index - 1) return sum(cost_value) # print(cost, cost_value) if __name__ == "__main__": s = Solution() print(s.twoCitySchedCost([[259,770],[448,54],[926,667],[184,139],[840,118],[577,469]]))
463311559b1bea722f0485d1c9f947fb34951952
Ena-Sharma/IMDB-Top-250-Movie-Scraper
/web_scraping/IMDB_task_10.py
1,046
3.609375
4
from IMDB_task_9 import * # Task_10 #This function returns a dictionary stating numbers of movies in each language for each directors def analyse_language_and_directors(movies_list): list_of_directors={} for i in movies_list: for director in i["Director"]: list_of_directors[director]={} #Creating dictionary key for each director for i in range(len(movies_list)): #Iterating loop over all movies for director in list_of_directors: #Iterating loop over newly created dictionary if director in movies_list[i]["Director"]: for lang in movies_list[i]["Language"]: #Creating a new key of the language list_of_directors[director][lang]=0 for i in range(len(movies_list)): for director in list_of_directors: if director in movies_list[i]["Director"]: #Iterating loop over 'Directors' key of each movie for lang in movies_list[i]["Language"]: list_of_directors[director][lang]+=1 #Incrementing the value if it already exists return list_of_directors pprint(analyse_language_and_directors(movies_list))
dc8e52390d61ee847ce34c2bf33138addd3e6fbb
shunerwadel/python
/readability.py
1,035
3.875
4
# Program to determine grade level of the given text using the Coleman-Liau formula from cs50 import get_string def main(): # Ask for text text = get_string("Text: ") # Declare variables letters = 0 words = 0 sentences = 0 # Count spaces, sentence punctuation, and letters in text for char in text: if char in [' ']: words += 1 elif char in ['.', '?', '!']: sentences += 1 elif (ord(char) >= 65 and ord(char) <= 90) or (ord(char) >= 97 and ord(char) <= 122): letters += 1 # Account for last word in text words = words + 1 # Calculate ave letters per 100 words L = (letters / words) * 100 # Calculate ave senences per 100 words S = (sentences / words) * 100 # Calculate grade level index index = round(0.0588 * L - 0.296 * S - 15.8) # Print index if index < 1: print("Before Grade 1") elif index >= 16: print("Grade 16+") else: print(f"Grade {index}") main()
11e6aa51917cbd4c4155e9b6ec1a4b44f67bf8cd
CatIsCodingForU/LeetCodeProblemsRepo
/leetcode-7-easy.py
570
3.921875
4
def reverse(x): """ :type x: int :rtype: int """ if x > (2 ** 31 - 1) or x < (2 ** 31) * (-1): return 0 else: old_int_str = str(x) new_int_str = "" minus = False if old_int_str[0] == '-': minus = True old_int_str = old_int_str[1:] for i in range(len(old_int_str) - 1, -1, -1): new_int_str += old_int_str[i] new_x = int(new_int_str) if new_x >= 2 ** 31 - 1: return 0 if minus: new_x *= -1 return new_x
d085c3e6952b30c1e4e1c70c39b0cc0d12552beb
michodgs25/python-exercises
/exercises/loops-lists.py
4,116
4.84375
5
# Programs need to do repetitive things very quickly # I am going to use a for-loop to build and print various lists # The best way to store the results of a for-loop is via lists # Here is a list example: # hairs = ['brown', 'blonde', 'ginger'] # eyes = ['green', 'blue', 'brown'] # weights = [1, 2, 3, 4] # You start the list with a left square bracket, which opens the list. # Then you put each item you want in the list, separated by commas. # Close the list with a right square bracket. # Python then takes the list& all its contents and assigns it to the variable. # LIST DESCRIPTION # Lists are used to store multiple items in a single variable. # Lists are one of 4 built-in data types in Python used to store collections of data. # The other three are: # TUPLE: a collection which is ordered and unchangeable. Allows the duplicate members. # SET: is a collection, which is unordered and unindexed. No duplicate members. # DICTIONARY: a collection which is ordered and changeable. No duplicate members. # All with different quality and usage. # LIST ITEMS: are ordered, changeable, and allow duplicate values. # List items are indexed, the first item has index[0], the second item has index[1] etc. # ORDERED: This means that the items have a defined order and that order will not change. # If new items are added to the list, the new item will be placed at the end of the list. # CHANGEABLE: a list can be changed, items can be added or removed after it has been created. # DUPLICATES: lists are index, therefore lists can have items with same value. # DUPLICATE EXAMPLE: thislist = ["apple", "banana", "cherry", "apple", "cherry"] print(thislist) # LIST LENGTH: to determine how many items a list has, use the len() function # LIST LENGTH EXAMPLE: thislist = ["apple", "banana", "cherry"] print(len(thislist)) # LIST ITEMS - DATA TYPES: # List items can be of any data type # DATA TYPES EXAMPLE: list1 = ["apple", "banana", "cherry"] # STRINGS list2 = [1, 5, 7, 9, 3] # INTEGER list3 = [True, False, False] # BOOLEANS # A list with multiple different data types list1 = ["abc", 34, True, 40, "male"] # TYPE(): from Python perspective, lists are defined as objects with the data type list: # <class 'list'> # DATA TYPE EXAMPLE mylist = ["apple", "banana", "cherry"] # data type = string print(type(mylist)) # LIST() CONSTRUCTOR # You can use the list() constructor when creating a new list # LIST CONSTRUCTOR EXAMPLE: thislist = list(("apple", "banana", "cherry")) # note the double round-brackets print(thislist) # create three lists, assign each to a variable the_count = [1, 2, 3, 4, 5] fruits = ['apples', 'oranges', 'pears', 'apricots'] change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] # this kind of for-loop goes through a list for number in the_count: print(f"This is count{number}") #same as above for fruit in fruits: print(f"A fruit of type: {fruit}") # we can also go through mixed lists # notice we have to use {} since we don't know what's in it for i in change: print(f"I got{i}") # I can also build lists, first start with an empty one elements = [0, 1, 2, 3, 4, 5, 6] # then use the range function to do 0 to 5 counts # for i in range(0, 6): # print(f"Adding {i} to the list.") # append is a function that lists understand # elements.append(i) # we can print the lists also for i in elements: print(f"Element was: {i}") # RANGE FUNCTION DEFINITION AND USE # The function returns a sequence of numbers starting from 0 by default, and increments by 1 # and stops before a specified number. # SYNTAX: ######## range(start, stop, step) ################# PYTHON LIST METHODS # APPEND(): Add a single element to the end of the list # CLEAR(): Removes all items from the list # COPY(): returns a shallow copy of the list # COUNT(): returns count of the element in the list # EXTEND(): adds iterable elements to the end of the list # INDEX(): returns the index of the element in the list # INSERT(): insert an element into the list # POP(): removes item from the list # REVERSE(): reverses the list # SORT(): sorts elements of a list
a8c04cfe510487d51863894f5b14067d3bdebf29
tuannguyen0115/Python
/PythonFundamentals/CoinTosses.py
375
3.546875
4
import random head = 0 tail = 0 print "Starting the program..." for i in xrange(5001): coin = round(random.random()) if coin == 0: head+=1 else: tail+=1 print "Attempt #", i, ": Throwing a coin... It's a", "head" if coin ==0 else "tail", "! ... Got", head, "head(s) so far and", tail,"tail(s) so far" print "Ending the programe, thank you!"
24b1cd60aedcf2a2a6b532256f7cbe878783a266
saint333/python_basico_1
/list_and_tuples/10_ejercicio.py
280
4.03125
4
#Escribir un programa que almacene en una lista los siguientes precios, 50, 75, 46, 22, 80, 65, 8, y muestre por pantalla el menor y el mayor de los precios. precio=[50, 75, 46, 22, 80, 65, 8] mayor=max(precio) menor=min(precio) print(f"el mayor es {mayor} y el menor es {menor}")
9584d73c0a5aae8c44b5cd1bf2fdee03fdead1fc
subutai/appraise
/ivs/ivs.py
6,501
3.8125
4
# Simple scripts to calculate rate of return assuming dollar cost averaging # using daily closing values import sys import math import pandas import collections ###################################################################### # # Basic utility functions # The named tuples we use Closing = collections.namedtuple("Closing", "year month value timestamp") Transaction = collections.namedtuple("Transaction", "year month value timestamp shares amount") def calculateReturn(v1, v2, mths): """ Given starting dollar amount v1, ending dollar amount v2, and elapsed time in months, compute effective annual return. rate = POWER(10,(LOG10(v2)-LOG10(v1))/years) - 1.0 """ years = mths/12.0 rate = math.pow(10, (math.log10(v2) - math.log10(v1))/years) - 1.0 return rate def readFile(filename): """ Read closing values file, sort from oldest to newest, and return associated dataframe. We assume this CSV file has at least two headers: Date and Close """ print "Reading filename:",filename df = pandas.read_csv(filename, parse_dates=[0]) dfs = df.sort('Date') return dfs def monthlyClose(dfs): """ Return closing values at the start of every month. Returns a list of closing values, where each closing value is the namedtuple Closing, containing year, month, closingValue, Timestamp """ prevMonth = -1 prevYear = -1 values = [] # iterate over rows, capture closing date whenever month has passed for i,row in dfs.iterrows(): if row['Date'].month > prevMonth or row['Date'].year > prevYear: prevMonth = row['Date'].month prevYear = row['Date'].year values.append(Closing(prevYear, prevMonth, row['Close'], row['Date'])) return values def calculateReturnTransaction(transaction, closingValues): """ Given a transaction, compute it's effective annual return through the latest closing value. """ duration = closingValues[-1].timestamp - transaction.timestamp totalMonths = (duration.days/365.25)*12.0 roi = calculateReturn( transaction.amount, # Amount invested in transaction closingValues[-1].value*transaction.shares, # Value of transaction at end totalMonths # Number of elapsed months ) # print "Months=",totalMonths, # print "Return=", 100.0*roi,"% .... ", # print transaction return roi def averageReturnTransactions(transactions, closingValues): """ Compute overall effective annual rate using the set of transactions. We calculate the annual rate of return for each transaction and report the average over all transactions (except the very last one). Weighted average return weights each transaction by the number of shares purchased in each transaction and is a more accurate reflection. """ # totalShares, transactions = purchaseSharesMonthly(closingValues, x) totalR = 0.0 totalAmount = 0.0 totalShares = 0.0 weightedR = 0.0 for t in transactions[0:-1]: totalR += calculateReturnTransaction(t, closingValues) totalAmount += t.amount totalShares += t.shares weightedR += t.shares * calculateReturnTransaction(t, closingValues) print "Total amount invested:",totalAmount print "Total shares",totalShares print "Value at end:", closingValues[-1].value*totalShares # print "Total return:",(closingValues[-1][2]*totalShares)/(x*len(transactions)) print "Average annual return=",(100.0*totalR)/len(transactions),"%" print "Weighted average return=",(100.0*weightedR)/totalShares,"%" ##################################################################### # # Investing strategies def purchaseSharesMonthly(closingValues, x): """ Basic dollar cost investing: given monthly closingValues, simulate investing x dollars every month. Return a tuple containing (totalShares, list of transactions) where each transaction is: [year, month, closingValue, Timestamp, shares, x] """ totalShares = 0 transactions = [] for v in closingValues: shares = float(x) / v.value totalShares += shares transaction = Transaction(v.year,v.month,v.value,v.timestamp,shares,x) transactions.append(transaction) return totalShares,transactions def smartMonthlyPurchase(closingValues, x): """ "Smarter" dollar cost investing: every 12 months, you have to invest x*12. Month to month you can choose how much as long as you invest all x*12 every we months. Return a tuple containing (totalShares, list of transactions) where each transaction is [year, month, closingValue, Timestamp, shares, x] """ totalShares = 0 transactions = [] startYear = closingValues[0].timestamp totalInvestedThisYear = 0.0 totalRemainingThisYear = x * 12 for v in closingValues: elapsedTime = v.timestamp - startYear elapsedMonths = round(elapsedTime.days / 30.5, 0) if elapsedMonths == 12: # print v.timestamp, "Elapsed months:", elapsedMonths, "investing: ", totalRemainingThisYear shares = float(totalRemainingThisYear) / v.value totalShares += shares transaction = Transaction(v.year, v.month, v.value, v.timestamp, shares, totalRemainingThisYear) transactions.append(transaction) startYear = transaction[3] print "===>", transactions[0] return totalShares, transactions if __name__ == '__main__': # Read file and figure out monthly closing values dfs = readFile(sys.argv[1]) closingValues = monthlyClose(dfs) # Print basic statistics duration = closingValues[-1].timestamp - closingValues[0].timestamp totalYears = duration.days/365.25 totalMonths = (duration.days/365.25)*12.0 print "================= Overall Returns ========" print "Total duration=",totalYears,"years or ",totalMonths,"months" print "Annual return since beginning", print 100.0*calculateReturn(closingValues[0].value, closingValues[-1].value, totalMonths),"%" # Print return with basic monthly dollar cost averaging print "\n================= Monthly dollar cost averaging ========" totalShares, transactions1 = purchaseSharesMonthly(closingValues, 1000.0) averageReturnTransactions(transactions1, closingValues) # Print return with smarter monthly dollar cost averaging print "\n================= Smarter dollar cost averaging ========" totalShares, transactions2 = smartMonthlyPurchase(closingValues, 1000.0) averageReturnTransactions(transactions2, closingValues)
40faf0e387d414e472ace7367cb098f186bf2a85
YanZheng-16/LearningPython
/Python语言程序设计/Week1/MoneyConvert_1.py
228
3.8125
4
# 货币转换 I money = input() if money[0:3] == 'USD': RMB = eval(money[3:]) * 6.78 print("RMB{:.2f}".format(RMB)) elif money[0:3] == 'RMB': USD = eval(money[3:]) / 6.78 print("USD{:.2f}".format(USD))
cd22bd6c9ef3dd89e2236b9f33da89abb89ec38c
gabriel-valenga/CursoEmVideoPython
/ex053.py
256
4
4
numero = int(input('Digite um número:')) total = 0 for i in range(1, numero + 1): if numero % i == 0: total += 1 if total == 2: print('{} é um número primo.'.format(numero)) else: print('{} não é um número primo.'.format(numero))
800013084df9bf052a3bbdfa6702b850e1cbf4d8
Oscar-Oliveira/Python-3
/10_Exceptions/I_with.py
728
3.5625
4
""" with - with EXPR as VAR: BLOCK - call VAR.__enter__ method at the begining - call VAR.__exit__ method at the end """ import os import inspect from pathlib import Path filePath = str(Path(os.path.dirname(__file__)).parent.joinpath("_Temp", "with.txt")) # Guaranteed to close the file with open(filePath, "w") as file: file.write("Hi there!") print(dir(file)) print() a = [2, 4, 2] print(dir(a)) class temp: def __enter__(self): print("__enter__") return self def Using(self): print("Using()") def __exit__(self, exc_type, exc_val, exc_tb): print("__exit__") print() print(dir(temp)) print() with temp() as t: t.Using()
e47f9e1318020445191fb3de430eb80e3c08ae70
jesa7955/gengoshori100nokku
/0/05.py
434
3.609375
4
source = "I am an NLPer" def ngram(source, n): l = len(source) if type(source) == str: source = "$" * (n - 1) + source + "$" * (n - 1) for i in range(l + 1): print(source[i:i+n]) elif type(input) == list: source = ["$"] * (n - 1) + source + ["$"] * (n - 1) for i in range(l + i): print(source[i:i+n]) ngram(source, 2) source = source.split() ngram(source, 2)
23412a7c2698b9044c5bf0ca29634a5e1ace7998
jbrdge/ProjectEulerSolutions
/Python/problem0005.py
308
3.84375
4
#project0005 #github.com/jbrdge def smallest_multiple(number): a = list(range(2,number+1)) n = 1 for i in range(0,len(a)): for j in range(i-1,-1,-1): if(a[i]%a[j]==0): a[i]=a[i]//a[j] for i in a: n*=i return(n) print(smallest_multiple(20))
06d1292182cbcb289b2f9d35fd8149f368351b76
lwtor/python_learning
/03_demo/fact.py
440
4.09375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def fact(num): if num == 1: return 1 return fact(num - 1) * num # 使用尾递归 # 然而python并没有对尾递归做优化。。。 def fact_good(num): return fact_real(num, 1) def fact_real(num, product): if num == 1: return product return fact_real(num - 1 , num * product) num = input('input num: ') print('result: ' + str(fact_good(int(num))))
d79fb9da01de41d0c3baf2ddbd601fe21b9232d4
sabinbhattaraii/python_assignment
/Functions/q20.py
212
4.0625
4
''' Write a Python program to find intersection of two given arrays using Lambda. ''' array1 = [1,2,3,4,5,6] array2 = [4,5,6,7,8,9] intersection = list(filter(lambda x : x in array1, array2)) print(intersection)
fae03c7a8b8441149d3de60a98363084415ef50b
NairitaMitra/JISAssasins
/4th.py
439
3.984375
4
# How many number we have to sort num = int(input("How many figures : ")) storage = [] result = [] # Creating an array of users numbers for i in range(1,num+1): a = int(input("Enter value" + str(i) + " : ")) storage.append(a) # user enter # Sorting the array for m in range(len(storage)): b = min(storage) storage.remove(b) result.append(b) # user get j = ' '.join(str(i) for i in result) print(j)
0fe66fdb33a676e263a0d3a3c869a13b4d629e63
Sinjebos/EcUtbildningDevOps
/Linux and Script Languages/Python/Self Studies/FunctionsIntro/factorial_function.py
257
3.921875
4
def factorial(number: int) -> None: result = 0 for index in range(number + 1): if index == 0: result = 1 print(index, result) else: result *= index print(index, result) factorial(35)
ef477e2924536d47dc8d20b4d548c1a9aa574e3b
yichong-sabrina/learn-python
/Chap4 Functional Programming/4_1_3 Sorted.py
578
4.09375
4
num = [36, 5, -12, 9, -21] print(sorted(num)) print(sorted(num, key=abs)) print(sorted(num, key=abs, reverse=True)) s = ['bob', 'about', 'Zoo', 'Credit'] print(sorted(s)) print(sorted(s, key=str.lower)) # 用一组tuple表示学生名字和成绩, 用sorted()对其分别按名字和成绩排序 def by_name(t): return t[0] def by_grade(t): return t[1] L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)] L_1 = sorted(L, key=by_name) L_2 = sorted(L, key=by_grade, reverse=True) print('by_name:', L_1, '\nby_grade_high2low:', L_2)
65729e6e834ed23c41e4e17ccc45f37c1efbf5bf
Swastik2561/LinkedList
/linkedlist.py
453
3.96875
4
class linkedlist: def __init__(self,headvalue): self.headvalue = headvalue self.nextnode = None def printing(self): printvalue = self while printvalue is not None: print(printvalue.headvalue) printvalue = printvalue.nextnode x = linkedlist("UmarAbdullah") y = linkedlist("Amar Akbar Anthony") z= linkedlist("Abey Aur kitna chahiye") x.nextnode = y y.nextnode = z print(x.nextnode.nextnode.headvalue) x.printing()
773cbf51e889dd4bfe44a4526388c91a5e952136
weston-bailey/algorithms
/practice-problems/python/cracking_strings.py
8,285
4.25
4
''' 1.1 Is Unique: Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures? ''' test_cases_1_1 = ['abc1frgt', 'abcdefghijklmnop', 'aaaaaa', 'bcdefaaght', 'ythbuioh'] # no external datatypes def unique_chars(s: str) -> bool: for i in range(len(s)): for j in range(i + 1, len(s)): if s[i] == s[j]: return False return True # print(unique_chars(test_cases_1_1[3])) def unique_chars_hash(s: str) -> bool: table = {} for i in range(len(s)): if s[i] not in table: table[s[i]] = i else: return False return True # print(unique_chars_hash(test_cases_1_1[1])) ''' 1.2 Check Permutation: Given two strings,write a method to decide if one is a permutation of the other. ''' def check_permutation(s_1: str, s_2: str) -> bool: if len(s_1) != len(s_2): return False # turn strings into sorted arrays s_1 = list(s_1).sort() s_2 = list(s_2).sort() return True if s_1 == s_2 else False test_cases_1_2 = ['abcd', 'dcba', 'abcde', 'abch'] # print(check_permutation(test_cases_1_2[0], test_cases_1_2[3])) ''' 1.3 URLify: Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end to hold the additional characters,and that you are given the "true" length of the string. (Note: If implementing in Java,please use a character array so that you can perform this operation in place.) ''' def URLify(s: str) -> str: # s.replace(' ', '%20') for i in range(len(s)): if s[i] == ' ': s = s[:i] + '%20' + s[i +1:] return s test_cases_1_3 = ['hello world', 'goodbye cruel world'] # print(URLify(test_cases_1_3[1])) ''' find all lowercase permutations of a string ''' def list_to_string(li): stringify = '' for i in range(len(li)): stringify += li[i] return stringify def permutation_list(li: list) -> list: if len(li) == 0: return [] if len(li) == 1: return [li] return_li = [] for i in range(len(li)): current = li[i] rest = li[:i] + li[i+1:] for perm in permutation_list(rest): return_li.append([current] + perm) return return_li def string_permutation_table(s: str) -> dict: table = {} inc = 0 table[s] = inc perms = permutation_list(list(s)) for perm in perms: stringify = list_to_string(perm) if stringify not in table: table[stringify] = inc inc += 1 return table # print(string_permutation_table('Tact Coa')) ''' 1.4 Palindrome Permutation: Given a string, write a function to check if it is a permutation of a palin­drome. A palindrome is a word or phrase that is the same forwards and backwards. A permutation is a rearrangement of letters. The palindrome does not need to be limited to just dictionary words. ''' # print(permutations('Tact Coa')) def palindrome_check(s: str) -> bool: s = s.replace(' ', '') rev = s[::-1] return True if rev == s else False # print(palindrome_check('taco cat')) def palindrome_permutations(s: str) -> list: table = string_permutation_table(s) palindromes = [] for permutation in table: # print(palindrome_check(permutation)) if palindrome_check(permutation): palindromes.append(permutation) return palindromes # solves with math def pal_2(s): table = {} # count chars for i in range(len(s)): if s[i] not in table: table[s[i]] = 1 else: table[s[i]] += 1 print(table) # count the occurances of chars with an odd count odds = 0 for char in table: if table[char] % 2 != 0: odds += 1 if len(s) % 2 == 0: return True if odds == 0 else False else: return True if odds == 1 else False # my_pal = pal_2('yeet') # print(1 % 2) # print(my_pal) # li = palindrome_permutations('racecar') # print(li) ''' 1.5 One Away There are three types of edits that can be performeded on strings: insert a character, remove a character, or replace a character. Given two strings, write a function to check if they are one edit away (or zero). ''' def one_away(s_1: str, s_2: str) -> bool: # case 0 zero edits away if s_1 == s_2: print('case 0') return True # case 1 no single edit will make the strings the same if len(s_1) > len(s_2) + 1 or len(s_2) > len(s_1) + 1: print('case 1') return False # case 2 if one character needs to be replaced if len(s_1) == len(s_2): print('case 2') # loop over strings keepning track of the number of differences num_differences = 0 for i in range(len(s_1)): if s_1[i] != s_2[i]: num_differences += 1 # return true if only one difference was found return True if num_differences <= 1 else False # listify strings to make them easier to work with s_1 = list(s_1) s_2 = list(s_2) # find longer and shorter string longer_string = s_1 if len(s_1) > len(s_2) else s_2 shorter_string = s_1 if len(s_1) < len(s_2) else s_2 # case 3 if one character needs to be removed or added for i in range(len(longer_string)): # splice out the first different character and compare the strings if longer_string[i] != shorter_string[i]: # remove the offending character from the longer string splice_longer = longer_string[:i] + longer_string[i + 1:] # splice the offending character into the shorter string splice_shorter = shorter_string[:i] + [longer_string[i]] + shorter_string[i + 1:] # make comparisons among the spliced strings if splice_longer == shorter_string or splice_shorter == longer_string: print('case 3') return True else: print('case 3') return False # you shouldn't be here return 'oh no!' # test_cases_1_5 = ['pale', 'ple', 'bake'] # solution = one_away(test_cases_1_5[0], test_cases_1_5[1]) # print(solution) ''' 1.6 String Compression: Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2blc5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string. You can assume the string has only uppercase and lowercase letters (a - z). ''' def string_compression(s: str) -> str: # make hash table of character counts char_table = {} sorted_s = sorted(s) for i in range(len(sorted_s)): if sorted_s[i] not in char_table: char_table[sorted_s[i]] = 1 else: char_table[sorted_s[i]] += 1 # make compressed string from table compressed_s = '' for char in char_table: compressed_s = compressed_s + char + str(char_table[char]) return compressed_s if len(compressed_s) < len(s) else s # solution = string_compression('cbbbbbbbddddegb77777ik') # print(solution) ''' 1.7 Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place? ''' # rotates 180 degrees # def rotate_matrix(matrix: list) -> list: # # reverse each list # for i in range(len(matrix)): # matrix[i] = matrix[i][::-1] # # reverse the matirx # matrix = matrix[::-1] # return matrix # rotates 180 degrees def rotate_matrix(matrix: list) -> list: # reverse each list for i in range(len(matrix)): matrix[i] = matrix[i][::-1] # reverse the matirx matrix = matrix[::-1] return matrix matrix = [ [0, 0, 1, 1], [0, 0, 1, 1], [2, 2, 3, 3], [2, 2, 3, 3] ] for li in matrix: print(li) solution = rotate_matrix(matrix) print('solution:') for li in solution: print(li) ''' 1.9 String Rotation:Assumeyou have a method isSubstringwhich checks if one word is a substring of another. Given two strings, sl and s2, write code to check if s2 is a rotation of sl using only one call to isSubstring (e.g.,"waterbottle" is a rotation of"erbottlewat"). ''' def string_rotation(s_1: str = "waterbottle", s_2: str = "erbottlewat") -> bool: # make s_2 into array to rotate it easier string_list = list(s_2) # rotate the string list, checking each rotation against s_1 for _ in range(len(string_list)): string_list = [string_list.pop()] + string_list if ''.join(string_list) == s_1: return True return False # solution = string_rotation() # print(solution)
de3d81cba4066d43c553f6520b1034ae862d89e0
cpeixin/leetcode-bbbbrent
/geekAlgorithm010/Week08/merge_sort_1.py
993
4.03125
4
def merge(a_list, b_list): # 所要利用的额外空间 result = [] a_index, b_index = 0, 0 # index从0开始,所以 < 号 while a_index < len(a_list) and b_index < len(b_list): if a_list[a_index] < b_list[b_index]: result.append(a_list[a_index]) a_index += 1 else: result.append(b_list[b_index]) b_index += 1 if a_index == len(a_list): for i in b_list[b_index:]: result.append(i) else: for i in a_list[a_index:]: result.append(i) return result def mergeSort(total_list): # 这里即是特例判断 又是 将每次归并的拆分,拆分成包含一个元素的list if len(total_list) <= 1: return total_list mid = len(total_list) >> 1 left = mergeSort(total_list[:mid]) right = mergeSort(total_list[mid:]) return merge(left, right) if __name__ == '__main__': a = [14, 2, 34, 43, 21, 19] print(mergeSort(a))
0cd083db1a346725b1d274345692543348c29129
zileyue/python3_study
/sum1.py
488
3.859375
4
#! /usr/bin/python #coding=utf-8 print("Type integers,each follow by enter,or just enter to exit.") total = 0 count = 0 while True: line = input("Input integers: ") if line: try: number = int(line) total += number count += 1 except ValueError as err: print(err) continue else: break if count: print("count = ",count,"total = ",total,"mean = ",total/count)
3dd47a26a5ab85d875a2e5d30ef8634b72fb2642
verilyDA/DojoRepo
/DojoAssignments/Python/assignments/multiples.py
493
4.375
4
''' multiples write code that prints all numbers from 1 to 1000. use a for loop Create another program that prints all the multiples of 5 from 5 to 1,000,000. ''' ''' for count in range(1, 1000): if count % 2 == 1: print(count) for count in range(5, 1000000): if count % 5 == 0: print(count) ''' #sum lists a = [1, 2, 5, 10, 255, 3] res = 0 for count in a: res += count print(res) #average lists res = 0 for count in a: res += count res /= len(a) print(res)
f6b1b6795d8c34e92be73e61d489b9e7f2a4178f
QiWang-SJTU/AID1906
/Part1 Python base/01Python_basic/03Exercise_code/Day07/exercise06.py
342
3.875
4
# 列表解析式嵌套,全排列 list01 = ["香蕉", "苹果", "哈密瓜"] list02 = ["雪碧", "可乐", "牛奶"] list_result = [] for i in list01: for j in list02: list_result.append(i + j) print(list_result) list_result_1 = [i + j for i in list01 for j in list02] print(list_result_1)
2f98c223576a7272969a7efe38f549ebd96ad75c
FelipeDreissig/Prog-em-Py---CursoEmVideo
/Mundo 2/Ex055.py
270
3.828125
4
## maior e menor peso maior = 0 menor = 1000 for x in range(1, 7, 1): peso = int(input('Qual o seu peso?')) if peso>maior: maior = peso if peso<menor: menor = peso print('O menor peso foi de {} e o maior peso foi de {}.'.format(menor, maior))
02beeae5c74319cedbe8d5cad533357e7cd87359
Vith-MCB/Phyton---Curso-em-Video
/Cursoemvideo/Exercícios UFV/Lista 6/exer04 - N no vetor.py
157
3.578125
4
vet = [int(input()) for i in range(5)] n = int(input()) if n in vet: print(f'O numero {n} está na posição {vet.index(n)+1}') else: print('Erro!')
843b0e3acdca676aa5cb82aed08b5a12b2449d66
morrisoncd31/BeginnersScripts
/Loops.py
212
4.15625
4
upper_bound = input("Choose the range upper bound --> ") upper_bound = int(input("Choose the range upper bound --> ")) for x in range(1, upper_bound): print("The next number in line is {}".format(exit(x)))
9632933a109ff171dc261c492c53fd317e354664
junzhougriffith/test
/PyLab/W136.py
1,489
4.125
4
##////////////////////////////// PROBLEM STATEMENT ///////////////////////////// ## Write Python code that reads a boolean and an integer from the keyboard. // ## If the boolean is True and the integer is in the range 1. . 100 OR if // ## the boolean is False and the integer is not in the range 1..100 and the // ## integer is not in the range -20..-8 print True. Otherwise print False. // ## You must not use the Python if or if-else statement. // ## // ## All ranges are inclusive // ## // ## Example inputs/outputs are: // ## True 50 -> True // ## True -5 -> False // ## False 50 -> False // ## False 200 -> True // ## False -5 -> True // ##////////////////////////////////////////////////////////////////////////////// b = eval(input()) n = int(input()) #in_range1 = n >= 1 and n <= 100 in_range1 = 1 <= n <= 100 in_range2 = -20 <= n <= -8 print((b and in_range1) or (not b and not in_range1 and not in_range2))
ee3088d262f6e56e601f1906827c96928d6672e7
isaranto/CKY-algorithm
/Parser.py
1,877
3.671875
4
import re class Rule: def __init__(self, line): """ Rule is being parsed like this: eg. "S -> NP VP" will become an object Rule with non-terminal = S, first = NP and second VP :param line: :return: """ start = re.split(" -> ", line.strip('\n'))[0] end = re.split(" -> ", line.strip('\n'))[1] self.non_terminal = start if len(end.split()) == 2: self.terminal = False self.first = end.split()[0] self.second = end.split()[1] elif len(end.split()) == 1: self.terminal = True self.word = end.split()[0] def print_me(self): if self.terminal: print self.non_terminal, " -> ", self.word else: print self.non_terminal, " -> ", self.first, self.second class Grammar: def __init__(self, file): """ Rules are being parsed into a dictionary of [first, second] = non_terminal :param file: :return: """ _dict = {} vocab = {} with open(file, 'r') as fp: for line in fp: rule = Rule(line) if rule.terminal: vocab[rule.word] = rule.non_terminal else: _dict[rule.first, rule.second] = rule.non_terminal self.rules = _dict self.vocab = vocab def print_me(self): print "Grammar Rules" for key, value in self.rules.items(): tmp = Rule(str(value)+" -> "+str(key)) tmp.print_me() print "\nVocabulary :" for key, value in self.vocab.items(): print value, " -> ", key print "\n" if __name__ == '__main__': _file = 'grammar.txt' grammar = Grammar(_file) rules = grammar.rules grammar.print_me() print grammar.rules
22e044b454ac2a56bdc0db4be0199318f8da5f79
AnupamKP/py-coding
/array/add_one_num.py
550
4.125
4
''' Given a non-negative number represented as an array of digits, add 1 to the number ( increment the number represented by the digits ). The digits are stored such that the most significant digit is at the head of the list. Example: If the vector has [1, 2, 3] the returned vector should be [1, 2, 4] as 123 + 1 = 124. ''' def add_one_num(A: list) -> list: result_num = int("".join(list(map(str, A))))+1 result = [c for c in str(result_num)] return result if __name__ == "__main__": A = [1,2,3] print((add_one_num(A)))
64700219c90352da7ac9e9694225032e41be4f6e
trevorbillwaite/Week-Two-Assignment
/temp.py
798
4.375
4
__author__ = 'trevorbillwaite' # Introduction to Computer Science # temp.py # Program will compute and print a table of Celsius temperatures and the Fahrenheit equivalents every 10 degrees from 0C to 100C # Declare Magic Numbers and Constants # LOOPCOUNTER = 2 # name = "bob" # Write program code here # ask user if temperature is in Farenheit # Convert to Celsius # (F-32) * 5 / 9 = C # output answer to user # Input # First Assignment constant = 32 fraction = (9 / 5) for C in range(0,101,10): F = (C * fraction) + constant print(C,F) # Second Assignment F = eval(input("Please enter a temperature in Farenheit: ")) fraction = (5 / 9) C = (F - constant) * fraction print("The temperature " ,F, "in Farenheit is equivalent to " ,C, "in Celsius.") # Process # Output
58b781ec9727b3e44a4a58050d23b640e9c1731d
wbigal/FATEC-ALP
/lista_1/04_totais_positivos_negativos.py
418
4.125
4
#coding: utf-8 numero = -1 positivo = 0 negativo = 0 while(numero != 0): numero = int(input("Digite um número inteiro (zero para sair): ")) if (numero > 0): print("{} é positivo").format(numero) positivo += numero elif (numero < 0): print("{} é negativo").format(numero) negativo += numero print("Total dos positivos: {}").format(positivo) print("Ttoal dos negativos: {}").format(negativo)
545f6113e1771aa3e0c28e2fd068a0fb8755c1e1
francliu/mmseg
/core/quantifier.py
670
3.5625
4
import re from Dictionary import Dictionary from Dictionary.digital import is_chinese_number number_pattern = u'[0-9]+[*?]*' def combine_quantifier(words): pos = 0 words_length = len(words) result = [] while pos < words_length: word1 = words[pos] if (re.match('^%s$' % number_pattern, word1) or\ is_chinese_number(word1)) and pos < words_length -1: word2 = words[pos+1] if word2 in Dictionary.Dictionary.quantifier_words: result.append(word1+word2) pos += 2 continue result.append(word1) pos += 1 return result
03c0bae65e89fa04a3a1de8f49e07635897e56c5
JoshuaAppleby/ProjectEuler
/ProjectEuler006.py
935
3.6875
4
#Project Euler, Problem 6 #Sum square difference #The sum of the squares of the first ten natural numbers is, # 1**2 + 2**2 + ... + 10**2 = 385 #The square of the sum of the first ten natural numbers is, # (1+2+...+10)**2 = 55**2 = 3025 #Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025-385=2640. #Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. import time def sumdif(N): """This function will return the difference between the sum of the squares and the square of the sum""" sumofsquares, sumnat = 0, 0 for i in range(1,N+1): sumofsquares += i**2 for i in range(1,N+1): sumnat += i sumsquare = sumnat**2 return sumsquare - sumofsquares start = time.time() print(sumdif(100)) print(time.time() - start) #25164150 in 0.0 secs
33b2297c72b078002963aeaf258b90a7a907b442
Esala-Senarathna/Python-Ex
/DSA Labs/Lab 7/Question 1.py
270
3.984375
4
def bubbleSort(arr): n = len(arr) for i in range(n - 1): for j in range(0, n - i - 1): if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] l =[] for i in range(8): l.append(int(input())) bubbleSort(l) print(l)
6f72e573ebabc68a71625596ae8c91c7aac77506
majaharkot/gitrepo
/python/tabliczka_mnozenia.py
528
3.859375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # # tabliczka_mnozenia.py # def tabliczka(a, b): for kolumna in range(1, a + 1): #pętla zewnętrzna for wiersz in range(1, b + 1): #pętla wewnętrzna print("{:>3} ".format(wiersz*kolumna), end='') print() def main(args): a = int(input("Podaj zakres liczb w kolumnie: ")) b = int(input("Podaj zakres liczb w wierszu: ")) tabliczka(a, b) return 0 if __name__ == '__main__': import sys sys.exit(main(sys.argv))
76f1d0362e949a052594b36944c3133eddb809ce
blukke/Python
/Funcoes/Exercicios/Coiso 4.py
266
3.78125
4
# Turma B # Exercício número 4 por Juan Lucas Melo de Borba def area(w, h): area = w * h # w= largura e h= altura t = area / 2 print('Area de {} '.format(t)) w = int(input('digite a largura do negocio: ')) h = int(input('Digite a altura do negocio: ')) area(w, h)
66f7428753e059054aad34e979a01814f17555a3
NARESHSWAMI199/python
/python/dictnary/more.py
605
4.3125
4
# access the value form a dict names = { 'presion1' : {'name' : 'naresh','age' :24}, 'presion2' : {'name' : 'nsh','age' :14}, } # you can't store a list or tuple or dict in a dict whitout his key print ([names[name]['name'] for name in names]) # find the max score using max() function students = { 'naresh ' : {'score' : 45 ,'age':20 }, 'manish ' : {'score' : 65 ,'age':23 }, 'chanda ' : {'score' : 85 ,'age':20 }, } # you can access the value like this print([students[items]['age'] for items in students]) print(max(students , key= lambda items: students[items]["score"]))
9c000e40e2a43eadc5465c47d4dfbe9fef8feac7
Rajatkhatri7/Project-Milap
/DataStructure and algorithms/LinkedList/reverseLL.py
1,837
4.25
4
#!/usr/bin/env python3 class Node: def __init__(self,data): self.data = data self.next = next class LinkedList: def __init__(self): self.head = None def appending(self,data): if self.head is None: new_node = Node(data) self.head = new_node new_node.next = None return else: new_node = Node(data) last_node = self.head while last_node.next: last_node = last_node.next last_node.next = new_node new_node.next = None def print_list(self): ptr = self.head while ptr: print(ptr.data) ptr = ptr.next def reverse_iteratiion(self): #swapping via iteration prev = None current = self.head while current !=None: nxt = current.next current.next = prev prev = current current = nxt self.head = prev def recursive_reverse(self): def _reverse_reverse(current,prev): if not current: #base case when current reach the end of linked list ,current is None return prev nxt = current.next current.next = prev prev = current current = nxt return _reverse_reverse(current,prev) self.head = _reverse_reverse(current = self.head,prev = None) llist = LinkedList() llist.appending("A") llist.appending("B") llist.appending("C") llist.appending("D") print("Original List") llist.print_list() print("reversing by recursion: ") llist.recursive_reverse() llist.print_list() print("reverse the list via iteration: ") llist.reverse_iteratiion() #see in the results swapping happens llist.print_list()
f8bfb8e771eda351736c7d85fda378fe279bff96
himabinduU/Python
/bank_account.py
2,736
4.03125
4
# Title : Bank_account for multiple users. import math list = [] #Bank_account fields dict = {'name':'none', 'balance':0, 'account_no': 0} g = 0 #Creating an account def make_account(name, account): seq = ('name', 'balance', 'account_no') list.append(dict.fromkeys(seq)) global g list[g]['account_no'] = account list[g]['name'] = name list[g]['balance'] = 0 g = g + 1 #If the account number exist than entered money will get deposit, otherwise asks to enter the valid account number. def deposit(account, amount) : i = 0 while (i < len(list)) : if list[i]['account_no'] == account : list[i]['balance'] += amount print "balance: ",list[i]['balance'] return i = i + 1 print "enter the valid account number orelse create an account" #If the account number exist than entered money will get withdrawn, otherwise asks to enter the valid account number. def withdraw(account, amount) : i = 0 while (i < len(list)) : if list[i]['account_no'] == account : list[i]['balance'] -= amount print list[i] return i = i + 1 print "enter the valid account number orelse create an account" #If the account number exist than it will show the account details along with balance, otherwise asks to enter the valid account number. def balance_enquiry(account) : i = 0 while (i < len(list)) : if list[i]['account_no'] == account : print list[i] return i = i + 1 print "enter the valid account number orelse create an account" #User Interface program def user_interface(): print ("---------------User Interface---------------") print ("| 1. creating an new account |") print ("| 2. depositing the amount |") print ("| 3. withdrawing the amount |") print ("| 4. balance enquiry |") print ("| 5. exit |") print ("--------------------------------------------") return int(input()) key = user_interface() #This loop runs until user selects exit option. while (1) : if (key == 1): print "enter the name" name = raw_input() print "enter the account number" account = int(raw_input()) make_account(name, account) elif (key == 2) : print "enter the account number" account = int(raw_input()) print "enter the amount to be deposited" amount = int(raw_input()) print deposit(account, amount) elif (key == 3) : print "enter the account number" account = int(raw_input()) print "enter the amount to be withdrawn" amount = int(raw_input()) print withdraw(account, amount) elif (key == 4) : print "enter the account number" account = int(raw_input()) balance_enquiry(account) elif (key == 5) : exit(0) else : print "Please enter the valid choice" key = user_interface()
ae7745125e3efb617e6050b3e9b799b0873c6c03
xioner/TileTraveller
/tiletraveller.py
3,859
4.125
4
# Player starts at pos 1,1 # Depending on position, the player can either move north, south, west or east. # Ask for direction, convert to lowercase. # If invalid direction is entered error handle + give user a chance to redeem themselves # east and west are on x axis # south and north are on y axis # If valid direction is entered by user # calculate new coordinates, and move on to next coordinates # https://github.com/xioner/TileTraveller N = '(N)orth' S = '(S)outh' E = '(E)ast' W = '(W)est' x_pos, y_pos = 1,1 player_start = x_pos, y_pos while True: if (x_pos == 1) and (y_pos == 1) or ((x_pos == 2) and (y_pos == 1)): print(f"You can travel: {N}.") direction = str(input("Direction: ")) while True: if direction.lower() == 'n': y_pos += 1 break else: print ("Not a valid direction!") direction = str(input("Direction: ")) if (x_pos == 1) and (y_pos == 2): print(f"You can travel: {N} or {E} or {S}.") direction = str(input("Direction: ")) while True: if direction.lower() in ('n', 's', 'e'): if direction.lower() == 'n': y_pos += 1 break elif direction.lower() == 's': y_pos -= 1 break elif direction.lower() == 'e': x_pos += 1 break else: print("Not a valid direction!") direction = str(input("Direction: ")) if (x_pos == 1) and (y_pos == 3): print(f"You can travel: {E} or {S}.") direction = str(input("Direction: ")) while True: if direction.lower() in ('s', 'e'): if direction.lower() == 's': y_pos -= 1 break elif direction.lower() == 'e': x_pos += 1 break else: print("Not a valid direction!") direction = str(input("Direction: ")) if ((x_pos == 2) and (y_pos == 2)) or ((x_pos == 3) and (y_pos == 3)): print(f"You can travel: {S} or {W}.") direction = str(input("Direction: ")) while True: if direction.lower() in ('w', 's'): if direction.lower() == 'w': x_pos -= 1 break elif direction.lower() == 's': y_pos -= 1 break else: print("Not a valid direction!") direction = str(input("Direction: ")) if (x_pos == 2) and (y_pos == 3): print(f"You can travel: {E} or {W}.") direction = str(input("Direction: ")) while True: if direction.lower() in ('e', 'w'): if direction.lower() == 'e': x_pos += 1 break elif direction.lower() == 'w': x_pos -= 1 break else: print("Not a valid direction!") direction = str(input("Direction: ")) if (x_pos == 3) and (y_pos == 2): print(f"You can travel: {N} or {S}.") direction = str(input("Direction: ")) while True: if direction.lower() in ('n','s'): if direction.lower() == 'n': y_pos += 1 break elif direction.lower() == 's': y_pos -= 1 break else: print("Not a valid direction!") direction = str(input("Direction: ")) if x_pos == 3 and y_pos == 1: print ('Victory!') exit()
86311e1988b63d841c5f3a3264c9d68657ecc567
jordangerdin/Capstone-Lab-7
/coinprice.py
1,041
3.765625
4
import requests import pprint def main(): dollars = get_bitcoin_ammount() converted = convert_bitcoin_to_dollars(dollars) display_result(dollars, converted) def get_bitcoin_ammount(): while True: try: return float(input(f'Enter bitcoin to convert: ')) except: print('Enter a number') def get_exchange_rate(): # Get exchange rate from bitcoin to USD response = request_rates() rate = extract_rate(response) return rate def convert_bitcoin_to_dollars(bitcoin): exchange_rate = get_exchange_rate() return convert(bitcoin, exchange_rate) def request_rates(): url = 'https://api.coindesk.com/v1/bpi/currentprice.json' return requests.get(url).json() def extract_rate(rates): return rates['bpi']['USD']['rate_float'] def convert(amount, exchange_rate): return amount * exchange_rate def display_result(bitcoin, converted): print(f'{bitcoin:.2f} bitcoin is equivalent to ${converted:.2f} dollars') if __name__ == '__main__': main()
79fe64cb4e46bf28500de4061f8d62e46911ed6d
beajmnz/IEDSbootcamp
/theory/02a-Data Types and Variables/DTV4.py
205
4.15625
4
#! /usr/bin/python3 # -*- coding: utf-8 -*- """ Created on Tue May 4 17:05:42 2021 @author: Bea Jimenez <bea.jimenez@alumni.ie.edu> """ text = input("please write some text: ") print("\nthe length of the text is:",len(text))
d026ba76da4eb16e843971a63503136b42972dae
heitorchang/learn-code
/checkio/home/pawn_brotherhood.py
1,220
3.609375
4
def coordToGrid(coord): col = ord(coord[0]) - ord('a') row = int(coord[1]) - 1 return (col, row) def inBounds(coord): return 0 <= coord[0] <= 7 and 0 <= coord[1] <= 7 def safe_pawns(pawns): board = [[0 for _ in range(8)] for _ in range(8)] # place pawns for pawn in pawns: gridCoord = coordToGrid(pawn) board[gridCoord[0]][gridCoord[1]] = 1 totalSafe = 0 # check each pawn and guard for pawn in pawns: gridCoord = coordToGrid(pawn) # if in first row, it is unsafe if gridCoord[1] > 0: bottomLeft = (gridCoord[0] - 1, gridCoord[1] - 1) bottomRight = (gridCoord[0] + 1, gridCoord[1] - 1) protectedByLeft = inBounds(bottomLeft) and board[bottomLeft[0]][bottomLeft[1]] == 1 protectedByRight = inBounds(bottomRight) and board[bottomRight[0]][bottomRight[1]] == 1 if protectedByLeft or protectedByRight: totalSafe += 1 return totalSafe def test(): assert safe_pawns({"b4", "d4", "f4", "c3", "e3", "g5", "d2"}) == 6 assert safe_pawns({"b4", "c4", "d4", "e4", "f4", "g4", "e5"}) == 1 testeql(safe_pawns(["a1","b2","c3","d4","e5","f6","g7","h8"]), 7)
41b27cf462d4797fd99b187e13ad2b383c87090d
ixaxaar/seq2seq-dnc
/src/scripts/index_corpus.py
855
3.703125
4
#!/usr/bin/env python3 import argparse from util import * def index_corpus(name, corpus): '''Index a corpus to form a dictionary Arguments: name {string} -- Name of this language / corpus corpus {string} -- Path to the text corpus to index ''' l = Lang(name) with open(corpus) as i: for line in i: l.index(normalize(line)) l.save(name + '.lang') if __name__ == '__main__': parser = argparse.ArgumentParser(description=''' Language distionary creator Creates a frequency-counted dictionary from a corpus ''') parser.add_argument('-corpus', required=True, help='Path to the text corpus to index') parser.add_argument('-name', required=True, help='Name of this lang') opts = parser.parse_args() index_corpus(opts.name, opts.corpus)
4e7896157f721045c361812f1f9bbb78e5960321
matheusmpereira/tecnicas-de-programacao
/atividade.n1.py
1,697
3.765625
4
from random import randint movimentos= 0 casa = 1 venceu = 0 jogada= 0 while venceu == 0: if movimentos >= 6: print("Você atingiu o limite de movimentos!") break; else: while casa == 1 and movimentos <7: print("Você esta na casa: ",casa) print("Você ainda tem", 7-movimentos,"movimentos") print("Escolha seu caminho:") print("[1]- Caminho vermelho") print("[2]- Caminho preto") jogada = int(input("")) print("") if jogada == 1: casa = 2 movimentos = movimentos+1 break; elif jogada == 2: casa = 4 movimentos = movimentos+1 break; else: print("Opção inválida!") print("") break; while casa == 3 and movimentos <7: print("Você esta na casa: ",casa) print("Você ainda tem", 7-movimentos,"movimentos") print("Escolha seu caminho:") print("[1]- Caminho vermelho") print("[2]- Caminho preto") jogada = int(input("")) print("") if jogada == 1: casa = 4 movimentos = movimentos+1 break; elif jogada == 2: casa = 5 movimentos = movimentos+1 break; else: print("Opção inválida!") print("") break; while casa == 4 and movimentos <7: print("Você esta na casa: ",casa) print("Você ainda tem", 7-movimentos,"movimentos") print("Escolha seu caminho:") print("[1]- Caminho vermelho") print("[2]- Caminho preto") jogada = int(input("")) print("") if jogada == 1: casa = 5 movimentos = movimentos+1 break; elif jogada == 2: casa = 6 movimentos = movimentos+1 break; else: print("Opção inválida!") print("") break;
e749dab1950110418c36005e5907388f7026eb4a
aloha45/python_control_lab
/fruits.py
365
4.0625
4
prices = { 'banana': 4, 'apple': 2, 'orange': 1.5, 'pear': 3 } stock = { 'banana': 4, 'apple': 5, 'orange': 6, 'pear': 7 } for price in prices: print(f'{price}') print(f'Price: {prices[price]}') print(f'Stock: {stock}') total = 0 for price in prices: inventory = prices[price] * stock[price] total += inventory print(f'Total: {total}')
ebcb30f8a743ecb48b0f5a6bb8eb097a39631b19
freitasSystemOutPrint/Python3
/pythonteste - aulas/aula08a.py
351
4.21875
4
import math num = int(input('Digite um número: ')) raiz = math.sqrt(num) print('A raiz de {} é igual a {:.2f}'.format(num, raiz)) ''' Para arredondar para cima use o ceil e para baixo florr e para casas decimais dentro dos '{}' use ':' dois pontos {:.2f} em vez de '%' print('A raiz de {} é igual a {}'.format(num, math.ceil(raiz))) '''
5b748cdacdcfd35ec0a04e32d19a1c232a7d6965
thaisNY/GuanabaraPy
/30.py
123
4.03125
4
num = int(input('Digite um número')) if num % 2 == 0 : print('O numero é par') else : print('O némero é impar')
4b9307392c50072fd4b11de15f4595919d0334ce
theChad/ThinkPython
/chap12/reducible.py
3,351
4.0625
4
# Exercise 12.4 # complecting <-- largest reducible word in words.txt # Using the hints.. # 12.4.4 # A bit backwards, but doing this first so we have the memo variable as global known = dict() # 12.4.1 def find_children(words, word): """Find all children of a word, i.e. words that are revealed by dropping a single letter. words: dictionary of words word: string """ children = [] for i in range(len(word)): possible_child = word[:i] + word[i+1:] if possible_child in words: children.append(possible_child) return children # 12.4.2 def is_reducible(words, word, verbose=False): """True if a word is reducible, given a dictionary of words. words: dictionary word: string verbose: flag for printing out path of a single reducible word """ # Base case. Empty string is reducible. if word=='': return True # Check memos if word in known: return known[word] # Cycle through children. If any is reducible, return True. for child in find_children(words, word): if is_reducible(words, child, verbose): known[word] = True # Set memo # This is just to print out all the words word reduces # down through. if verbose: print(word) return True # No reducible children. Word isn't reducible. known[word] = False # Set memo return False # 12.4.3 def add_single_letter_words(words): """Add single letter words to the dictionary. """ words['']=None words['i']=None words['a']=None return words # Get dictionary of words from file def get_words(filename="../chap9/words.txt"): fin = open(filename) words = dict() for line in fin: word = line.strip() words[word]=None return add_single_letter_words(words) # Find all reducible words in dictionary def find_reducible(words): """Find all reducible words in words. Return a new dictionary. words: dictionary """ reducible=dict() for word in words: if is_reducible(words, word): reducible[word]=None return reducible # Create new dictionary by length of keys of the old one # to find the longest reducible words def key_lengths(words): """Return a dictionary whose keys are numbers indicating word length. Their values will be a list of all words whose length is equal to that key. words: dictionary of words """ word_length = dict() # For each word, add it to the appropriate entry (its length) # in word_length. for word in words: word_length.setdefault(len(word),[]).append(word) return word_length # Find the maximum entry in a dictionary def max_key(words): """Return the item with the maximum key in words. words: dictionary """ return words[max(words.keys())] # Find the biggest reducible word from words.txt def find_reducible_from_file(filename="../chap9/words.txt"): words = get_words(filename) # Read in words (plus single letter words) reducible = find_reducible(words) # Dictionary of reducible # Find all reducible words with the longest length biggest_reducibles = max_key(key_lengths(reducible)) print(biggest_reducibles) if __name__=='__main__': find_reducible_from_file()
59fc62450c7d1a60ebdd369ec22c02233038f7cb
Aquariuscsx/python
/homework/day18/duojiceng.py
1,975
3.9375
4
# # class A: # # pass # # # # class B(A): # # pass # # # # class C: # # pass # # # # class D(C): # # pass # # # # class E( B, D): # # pass # class Person(object): # def __init__(self, name, age, height): # self.name = name # self.age = age # self._height = height # # # class Father(Person): # def __init__(self,name, age, height, money): # super().__init__(name, age, height) # self.money = money # # def work(self): # print('你老爸在拼命工作供你上学') # # class Mother(Person): # def __init__(self,money, name, age, height ): # super().__init__(name, age, height) # # self.name = name # # self.age = age # # self._height = height # self.money = money # # def work(self): # print('你老妈在拼命工作供你上学') # # def boy(self): # print('生育') # # super 在继承中,重写了父类方法时,调用父类时用 # #super().父类方法(参数...) # class Chind(Father, Mother): # def __init__(self,money, name= None, age = 1, height = 175): # super().__init__(money) # # def show(self): # print('我是') # # if __name__== '__main__': # chind = Chind(1000) # chind.show() ''' 1.重写 __new__() 2.创建一个私有的静态变量 __instance = None 3.判断(类变量)静态变量是否为None 如果为None 表示第一次执行该对象NEW方法 4.new 底层创建新的对象 ''' class Play(object): __instance = None def __new__(cls, *args, **kwargs): if cls.__instance is None: cls.__instance = super().__new__(cls) return cls.__instance def __init__(self, source): self.source = source def play(self): print(self.source) if __name__ == '__main__': mp1 = Play('凉凉') mp1.play() print(id(mp1)) mp2 = Play('远走高飞') mp2.play() print(id(mp2)) # print(mp1 is mp2)
9c63d6032f0cc504bc40c668e715d0aa7ec2204d
mjh-sakh/python-project-lvl1
/brain_games/games/gcd.py
821
3.84375
4
# noqa: D100 import random RULE = 'Find the greatest common divisor of given numbers.' def find_gcd(number1: int, number2: int) -> int: """ Find GCD for two numbers. Args: number1: int number2: int Returns: gcd: """ if number2 > number1: return find_gcd(number2, number1) if number2 == 0: return number1 return find_gcd(number2, number1 % number2) def generate_task_answer(): """ Generate task and answer for gcd game. Returns: task: two numbers, str. answer: str """ initial_gcd = random.randint(2, 9) number1 = random.randint(2, 5) * initial_gcd number2 = random.randint(4, 9) * initial_gcd task = f'{number1} {number2}' answer = str(find_gcd(number1, number2)) return task, answer
ae5403397b4d71d9650467d874aed9c4c44b00c7
itay-feldman/a3c-continuous-action-space
/bullet_minitaur/lib/experience.py
6,459
3.59375
4
import numpy as np import random from collections import namedtuple import gym from collections import deque # Simple named tuple that stores Experience Experience = namedtuple('Experience', ['state', 'action', 'reward', 'done']) class ExperienceSource: """ Class that creates an iterable experience source, returns an Experience object tuple each iteration """ def __init__(self, envs, agent, steps_count=1): """ Create simple experience source :param env: environment or list of environments to be used :param agent: callable to convert batch of states into actions to take :param steps_count: count of steps to track for every experience chain """ super().__init__() assert isinstance(steps_count, int) assert steps_count >= 1 if isinstance(envs, (list, tuple)): self.envs = envs else: self.envs = [envs] self.agent = agent self.steps_count = steps_count self.total_rewards = [] self.total_steps = [] def __iter__(self): """ This function is called each time the object is iterated over, it uses the agent and the environment to generate Experience """ # Setup states, batches, current_rewards, current_steps, env_lengths = [], [], [], [], [] total_steps = [0] * len(self.envs) for env in self.envs: env_lengths.append(1) states.append(env.reset()) current_rewards.append(0.0) current_steps.append(0) batches.append(deque(maxlen=self.steps_count)) while True: # main loop actions = [None] * len(states) states_in, states_idx = [], [] # get all states that will be passed to the agent (and their indices): for idx, state in enumerate(states): if state is None: # if environment's firs observation is None, sample a random action actions[idx] = self.envs[0].action_space.sample() else: states_in.append(state) states_idx.append(idx) if states_in: out_actions = self.agent(states_in) for idx, action in enumerate(out_actions): global_idx = states_idx[idx] actions[global_idx] = action grouped_actions = _group_list(actions, env_lengths) global_offset = 0 for env_idx, (env, action_v) in enumerate(zip(self.envs, grouped_actions)): next_state, r, done, _ = env.step(action_v[0]) next_state_v, r_v, done_v = [next_state], [r], [done] for offset, (action, next_state, r, done) in enumerate(zip(action_v, next_state_v, r_v, done_v)): idx = global_offset + offset state = states[idx] batch = batches[idx] current_rewards[idx] += r current_steps[idx] += 1 if state is not None: batch.append(Experience(state=state, action=action, reward=r, done=done)) if len(batch) == self.steps_count: yield tuple(batch) states[idx] = next_state if done: if 0 < len(batch) < self.steps_count: yield tuple(batch) while len(batch) > 1: batch.popleft() yield tuple(batch) self.total_rewards.append(current_rewards[idx]) self.total_steps.append(current_steps[idx]) current_rewards[idx] = 0.0 current_steps[idx] = 0 states[idx] = env.reset() batch.clear() global_offset += len(action_v) def pop_total_rewards(self): """ Return all the rewards accumulated so far """ r = list(self.total_rewards) # python passes a refernce of a list, so we need to explicitly create a new one if r: self.total_rewards = [] return r def pop_rewards_steps(self): """ Return all the rewards accumulated so far paired with the number of steps that episode was """ res = list(zip(self.total_rewards, self.total_steps)) if res: self.total_rewards, self.total_steps = [], [] return res def _group_list(items, lens): """ Unflat the list of items by lens :param items: list of items :param lens: list of integers :return: list of list of items grouped by lengths """ res = [] cur_ofs = 0 for g_len in lens: res.append(items[cur_ofs:cur_ofs+g_len]) cur_ofs += g_len return res ExperienceFirstLast = namedtuple('ExperienceFirstLast', ['state', 'action', 'reward', 'last_state']) class ExperienceSourceFirstLast(ExperienceSource): """ This is a wrapper around ExperienceSource to prevent storing full trajectory in replay buffer when we need only first and last states. For every trajectory piece it calculates discounted reward and emits only first and last states and action taken in the first state. If we have partial trajectory at the end of episode, last_state will be None """ def __init__(self, env, agent, gamma, steps_count=4): assert isinstance(gamma, float) super(ExperienceSourceFirstLast, self).__init__(env, agent, steps_count=steps_count+1) self.gamma = gamma self.steps = steps_count def __iter__(self): for exp in super(ExperienceSourceFirstLast, self).__iter__(): if exp[-1].done and len(exp) <= self.steps: last_state = None elems = exp else: last_state = exp[-1].state elems = exp[:-1] total_reward = 0.0 for e in reversed(elems): total_reward *= self.gamma total_reward += e.reward yield ExperienceFirstLast(state=exp[0].state, action=exp[0].action, reward=total_reward, last_state=last_state)
b9568096be39dd3ec10d0e600945f5d9721dec64
BillionsRichard/pycharmWorkspace
/leetcode/easy/find_learned_words_len/srcs/a.py
861
3.75
4
# encoding: utf-8 """ @version: v1.0 @author: Richard @license: Apache Licence @contact: billions.richard@qq.com @site: @software: PyCharm @time: 2019/9/13 22:43 """ from pprint import pprint as pp class Solution: def countCharacters(self, words, chars): word_cnt = len(words) word_cab_list = list(chars) word_tot_len = 0 for i in range(word_cnt): word = words[i] for word_chr in word: if list(word).count(word_chr) > word_cab_list.count(word_chr): break else: word_tot_len += len(word) return word_tot_len if __name__ == '__main__': s = Solution() words = ["cat", "bt", "hat", "tree"] chars = "atach" words = ["hello", "world", "leetcode"] chars = "welldonehoneyr" print(s.countCharacters(words, chars))