blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
9e7183bcf3d1673a836edc624d881c538a113201
mattblk/Study
/Python/level1/level1_문자열내마음대로정렬하기.py
182
3.671875
4
strings=["abce", "abcd", "cdx"] n=2 def solution(strings, n): strings.sort() answer = sorted(strings, key=lambda k :k[n]) return answer print(solution(strings,n)) #8점
ccb988ec5cc4a16821c8d6a8c3b11cac393a9ed3
antiface/pybot
/cnjokes.py
527
3.5
4
import urllib2 import re import json """ Return the website json response for Chuck Norris jokes """ def getJsonForJokes(): apiCall = urllib2.urlopen('http://api.icndb.com/jokes/random/') return json.loads(apiCall.read()) """ Returns the joke as a string without the parentheses """ def getJoke(response): return response["value"]['joke'] """ Returns the joke as a string without the parentheses """ def handleMessage(text): if re.findall('chuck norris', text, re.I): return getJoke(getJsonForJokes())
629c12d7ef38a57f3453ef78090988f418b2475a
JLowe-N/Algorithms
/AlgoExpert/checkbstequality.py
2,846
3.921875
4
''' Given 2 arrays that represent BSTs and the order in which elements are inserted into each BST, check and return a boolean if the 2 arrays produce equivalent BSTs. Do not construct a BST to implement this algorithm. ''' # Solution 1 - Recursive Approach with Pointers # Complexity - O(N^2) Time | O(d) Space # Where N is the number of elements in the array # Where d is the depth of the deepest branch of the array due to recursion calls # on the call stack def checkBstEquality(arrayOne, arrayTwo): return bstEqualityHelper(arrayOne, arrayTwo, 0, 0, float("-inf"), float("inf")) def bstEqualityHelper(arrayOne, arrayTwo, rootIdxOne, rootIdxTwo, minVal, maxVal): if rootIdxOne == -1 or rootIdxTwo == -1: return rootIdxOne == rootIdxTwo if arrayOne[rootIdxOne] != arrayTwo[rootIdxTwo]: return False leftRootIdxOne = getIdxOfFirstSmaller(arrayOne, rootIdxOne, minVal) leftRootIdxTwo = getIdxOfFirstSmaller(arrayTwo, rootIdxTwo, minVal) rightRootIdxOne = getIdxOfFirstBiggerOrEqual(arrayOne, rootIdxOne, maxVal) rightRootIdxTwo = getIdxOfFirstBiggerOrEqual(arrayTwo, rootIdxTwo, maxVal) parentNodeValue = arrayOne[rootIdxOne] leftAreSame = bstEqualityHelper(arrayOne, arrayTwo, leftRootIdxOne, leftRootIdxTwo, minVal, parentNodeValue) rightAreSame = bstEqualityHelper(arrayOne, arrayTwo, rightRootIdxOne, rightRootIdxTwo, parentNodeValue, maxVal) return leftAreSame and rightAreSame def getIdxOfFirstSmaller(array, startingIdx, minVal): for i in range(startingIdx + 1, len(array)): if array[i] < array[startingIdx] and array[i] >= minVal: return i return -1 def getIdxOfFirstBiggerOrEqual(array, startingIdx, maxVal): for i in range(startingIdx + 1, len(array)): if array[i] >= array[startingIdx] and array[i] <= maxVal: return i return -1 # Solution 2 - Recursive Approach with Array Copies # Complexity - O(N^2) Time | O(N^2) Space # def checkBstEquality(arrayOne, arrayTwo): # if len(arrayOne) != len(arrayTwo): # return False # if len(arrayOne) == 0 or len(arrayTwo) == 0: # return True # if arrayOne[0] != arrayTwo[0]: # return False # leftOne = getSmaller(arrayOne) # leftTwo = getSmaller(arrayTwo) # rightOne = getBiggerOrEqual(arrayOne) # rightTwo = getBiggerOrEqual(arrayTwo) # return checkBstEquality(leftOne, leftTwo) and checkBstEquality(rightOne, rightTwo) # def getSmaller(array): # smaller = [] # for i in range(1, len(array)): # if array[i] < array[0]: # smaller.append(array[i]) # return smaller # def getBiggerOrEqual(array): # biggerOrEqual = [] # for i in range(1, len(array)): # if array[i] >= array[0]: # biggerOrEqual.append(array[i]) # return biggerOrEqual
ff21fb3637537b9d00186742381a4b388ac89e47
jkbockstael/leetcode
/2020-07-month-long-challenge/day07.py
1,527
3.96875
4
#!/usr/bin/env python3 # Day 7: Island Perimeter # # You are given a map in form of a two-dimensional integer grid where 1 # represents land and 0 represents water. # Grid cells are connected horizontally/vertically (not diagonally). The grid # is completely surrounded by water, and there is exactly one island (i.e., one # or more connected land cells). # The island doesn't have "lakes" (water inside that isn't connected to the # water around the island). One cell is a square with side length 1. The grid # is rectangular, width and height don't exceed 100. Determine the perimeter of # the island. class Solution: def islandPerimeter(self, grid: [[int]]) -> int: # This is not the most subtle approach, but it gets the job done fast # enough and without extra memory def neighbors(row, col): count = 0 if row > 0: count += grid[row - 1][col] if row < len(grid) - 1: count += grid[row + 1][col] if col > 0: count += grid[row][col - 1] if col < len(grid[0]) - 1: count += grid[row][col + 1] return count perimeter = 0 for row in range(len(grid)): for col in range(len(grid[0])): if grid[row][col] == 1: perimeter += 4 - neighbors(row, col) return perimeter # Test test_grid = [[0,1,0,0], [1,1,1,0], [0,1,0,0], [1,1,0,0]] assert Solution().islandPerimeter(test_grid) == 16
7396f18aea8cd11de075e5998081a7191fb8a36e
nkowdley/AutoInterview
/Rank.py
3,153
3.671875
4
import sys import StringIO class Rank: skills = [] gpa = 0.0 graduation = 'Undergrad' #topTierCompanies = [] def __init__(self, arrayOfStrings): self.arrayOfStrings = arrayOfStrings def enterDiscrimination(self): listOfSkills = raw_input('Enter the skills your require: ') global skills skills = listOfSkills.split(' ') for word in skills: print word print "---------------------------------------------------------------------" gpa = input('Enter the min GPA ') #graudation = input('Enter the gradation year your looking for ') #graduation = graduation - datetime.now().year def rankThePerson(self, arrayOfStrings): #self.rankGPA(arrayOfStrings) self.rankSkills(arrayOfStrings) def rankSkills(self, arrayOfStrings): global skills for word in skills: num =len(arrayOfStrings) - 1 index = 0 #print word #print "---------------------------------------------------------------------" while True: #if arrayOfStrings[index] in word: #print words + ' ' + word #print "---------------------------------------------------------------------" #if arrayOfStrings[index].find(word, len(arrayOfStrings[index])) == True: # array = arrayOfStrings[index + 1].split('\n') # if float(array[0]) <= 4.00: # print(array[0]) # print(arrayOfStrings[index]) if index == num: #print('elif') break else: array = arrayOfStrings[index ].split('\n') i = 0 bool = True while(bool == True): if i == len(array): bool = False elif(word in array[i]): #print(array[i]) #print(index) #print "---------------------------------------------------------------------" bool = False else: i+=1 index = index + 1 '''for words in array: if word in words: #print('Break') print(words) print(index) print "---------------------------------------------------------------------" break index = index + 1''' def rankGPA(self, arrayOfStrings): index = 0 while True: if arrayOfStrings[index] == "GPA:": array = arrayOfStrings[index + 1].split('\n') if float(array[0]) <= 4.00: print(array[0]) print('Break') break index = index + 1
9427fcd08cff9abfe8aa8fd74a71bd5c0c092359
sinha414tanya/tsinha
/armstrong.py
414
3.625
4
num1=int(input()) def check_armstrong(num1): if num1<=100000: num = num1 st=str(num1) l=len(st) sum=0 while(num>0): c=num%10 sum=sum+(c**l) num=num//10 if int(num1)==sum: return True else: return False if check_armstrong(num1)==True: print("yes") else: print("no")
f44bbaafaed7dd847dc4cecb6c23929d33aea33f
omerfarballi/Python-Dersleri
/04.variables.py
844
4.03125
4
klavye = 50 gozluk = 300 kdv_oranı= 0.18 kdvli_klavye = klavye+(klavye*kdv_oranı) kdvli_gozluk = gozluk+(gozluk*kdv_oranı) print("kdvli gözlük : ",kdvli_gozluk,"kdvli klavye: ",kdvli_klavye) # değişken isimi verirken dikkat etmemmiz gereken durumlar: # sayı ile başlayamaz number1 = 99 print(number1) number1 = 999 print(number1) number1 += 1 number1 -= 1 number1 /= 9 number1 *= 9 print(number1) # age AGE age = 18 AGE = 81 Age =55 print(age,AGE,Age) #Türkçe karakter kullnamayalım age = 18 #int money = 85.5 #float name = "Ömer" #str(string) isStudent = True #Bool age , money , name , isStudent = (18,85.6,'Ömer Faruk ',True ) number1 = '25' number2 = '52' print(number1+number2) # 77 => 2552 # Boşluk koyamayız #ogrenci mi (Böyle bir değişken atayamayız)
731dd5ebf7927e965ff639430e59f952f3845d98
mckilem/python1_hw
/lesson1/hard.py
680
4.5
4
# Задание-1: # Ваня набрал несколько операций в интерпретаторе и получал результаты: # Код: a == a**2 # Результат: True # Код: a == a*2 # Результат: True # Код: a > 999999 # Результат: True # Вопрос: Чему была равна переменная a, если точно известно что её значение не изменялось? # Пришлось поискать есть ли бесконечность в переменных питона :) a = float('inf') print(a == (a ** 2)) # True print(a == (a * 2)) # True print(a > 999999) # True
28086150814e85d850cb2d1ff157dc879e5e3e36
Zoe8888/error-handling
/window.py
1,314
4.03125
4
from tkinter import * from tkinter import messagebox # Initializing the window root = Tk() # Creating a title root.title('Exception handling') # Setting the window size root.geometry('300x200') # Ensuring the window size cannot be adjusted root.resizable('False', 'False') # Setting a background color root.config(bg='#d177f7') # Creating & positioning the label with a background color label = Label(root, text='Please enter amount in your account', bg='#bc5cd6') label.place(relx=0.1, rely=0.2) # Creating & positioning the entry point with a background color entry = Entry(root, bg='#d0cbd1') entry.place(relx=0.22, rely=0.4) # Making the check button functional def check(): try: amount = int(entry.get()) if amount == '': messagebox.showerror(message='Enter an amount') if amount >= 3000: messagebox.showinfo(message='Congratulations! You qualify to go to Malaysia') else: messagebox.showerror(message='You do not qualify to go to Malaysia') except ValueError: messagebox.showerror(message='Enter a valid amount') # Creating & positioning the check button with a background color checkButton = Button(root, text='Check qualification', bg='#bc5cd6', command=check) checkButton.place(relx=0.15, rely=0.5) root.mainloop()
b9ec028ff6eda91cc29e75e1b96256d0ad7c2179
ShaunaVayne/python_version01
/com/wk/DbDemo/test.py
716
3.734375
4
# 连接mysql import mysql.connector connect = mysql.connector.connect(user='root', password='root123', database='wangkun') # cursor = connect.cursor() # # 创建user表 # cursor.execute('create table user (id VARCHAR(10) PRIMARY KEY , NAME VARCHAR(20))') # # 插入一行数据 # # 注意, 在python中mysql的占位符是%s, java中是? # cursor.execute('insert into user(id, name) VALUES (%s , %s)',['1','WangKun']) # # 操作影响的行数 # i = cursor.rowcount # print(i) # # 提交事物 # connect.commit() # connect.close() # 查询 connect_cursor = connect.cursor() connect_cursor.execute('select * from user where id = %s',('1',)) fetchall = connect_cursor.fetchall() print(fetchall) connect.close()
8525f2d4ea50e2809449332c57a6e0447aa5fb7a
Velu2498/codekata-array-python
/150.py
410
3.828125
4
""" Given a number N, print all the prime factors once in ascending order. Input Size : N <= 100000 Sample Testcase : INPUT 100 OUTPUT 2 5 """ n=int(input()) ans=[] i=1 while(i<=n): k=0 if(n%i==0): j=1 while(j<=i): if(i%j==0): k=k+1 j=j+1 if(k==2): # print(i) ans.append(i) i=i+1 print(" ".join(map(str,ans)))
443d623364fde55c25c7c510e3f4699836275de1
saparia-data/data_structure
/geeksforgeeks/dynamic_programming/12_0_1_knapsack_problem.py
1,371
3.96875
4
''' You are given weights and values of N items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. Note that we have only one quantity of each item. In other words, given two integer arrays val[0..N-1] and wt[0..N-1] which represent values and weights associated with N items respectively. Also given an integer W which represents knapsack capacity, find out the maximum value subset of val[] such that sum of the weights of this subset is smaller than or equal to W. You cannot break an item, either pick the complete item, or don't pick it (0-1 property). Example 1: Input: N = 3 W = 4 values[] = {1,2,3} weight[] = {4,5,1} Output: 3 Example 2: Input: N = 3 W = 3 values[] = {1,2,3} weight[] = {4,5,6} Output: 0 ''' def knapSack(W, wt, val, n): dp = [[0 for x in range(W + 1)] for x in range(n + 1)] for i in range(W+1): dp[0][i] = 0 for i in range(n+1): dp[i][0] = 0 # Build table K[][] in bottom up manner for i in range(1, n + 1): for w in range(1, W + 1): if(wt[i - 1] > w): dp[i][w] = dp[i - 1][w] else: dp[i][w] = max(val[i - 1] + dp[i - 1][w - wt[i - 1]], dp[i - 1][w]) return dp[n][W] values = [1,2,3] weight = [4,5,1] n = len(values) print(knapSack(4, weight, values, n))
4911fa14f055ca3f6dfdc66284dfb2f18b73297d
italoohugo/Python
/Geometria/C.py
247
4
4
print('Programa Calculo da area de um Trapezio') Base = float(input('Digite a base Maior: ')) base = float(input('Digite a base Menor: ')) h = float(input('Qual a autura: ')) area = (Base + base) * h / 2 print('A area de um Trapezio é:',area)
93abbc4b3978bcaa2eef75f402288645a5a31509
tdworowy/PythonPlayground
/Playground/dice_game/dice_game.py
2,781
3.671875
4
import itertools from typing import Union def count_wins(dice1: list, dice2: list) -> tuple: assert len(dice1) == 6 and len(dice2) == 6 dice1_wins, dice2_wins = 0, 0 for res in itertools.product(dice1, dice2): if res[0] > res[1]: dice1_wins += 1 if res[1] > res[0]: dice2_wins += 1 return dice1_wins, dice2_wins def find_the_best_dice(dices: list) -> Union[int, list]: assert all(len(dice) == 6 for dice in dices) dices = {i: dice for i, dice in enumerate(dices)} wins_dices = {i: 0 for i, dice in enumerate(dices)} for c in itertools.combinations(dices.keys(), 2): wins = count_wins(dices[c[0]], dices[c[1]]) if wins[0] > wins[1]: wins_dices[c[0]] += 1 if wins[1] > wins[0]: wins_dices[c[1]] += 1 max_value = max(list(wins_dices.values())) if max_value < len(dices) - 1: return -1 else: return list(wins_dices.keys())[list(wins_dices.values()).index(max_value)] def compute_strategy(dices: list) -> dict: assert all(len(dice) == 6 for dice in dices) strategy = dict() strategy["choose_first"] = True strategy["first_dice"] = 0 optimal_dice = find_the_best_dice(dices) if optimal_dice != -1: strategy["first_dice"] = optimal_dice else: strategy["choose_first"] = False strategy.pop("first_dice", None) for i in range(len(dices)): for j in range(i + 1, len(dices)): wins = count_wins(dices[i], dices[j]) if wins[0] < wins[1]: strategy[i] = j elif wins[0] > wins[1]: strategy[j] = i return strategy if __name__ == "__main__": dice1 = [1, 2, 3, 4, 5, 6] dice2 = [1, 2, 3, 4, 5, 6] wins = count_wins(dice1, dice2) assert wins == (15, 15) dice1 = [1, 1, 6, 6, 8, 8] dice2 = [2, 2, 4, 4, 9, 9] assert count_wins(dice1, dice2) == (16, 20) dices1 = [[1, 1, 6, 6, 8, 8], [2, 2, 4, 4, 9, 9], [3, 3, 5, 5, 7, 7]] best_dice = find_the_best_dice(dices1) assert best_dice == -1 dices2 = [[1, 1, 2, 4, 5, 7], [1, 2, 2, 3, 4, 7], [1, 2, 3, 4, 5, 6]] best_dice = find_the_best_dice(dices2) assert best_dice == 2 dices3 = [[3, 3, 3, 3, 3, 3], [6, 6, 2, 2, 2, 2], [4, 4, 4, 4, 0, 0], [5, 5, 5, 1, 1, 1]] best_dice = find_the_best_dice(dices3) assert best_dice == -1 dices4 = [[1, 2, 3, 4, 5, 6], [1, 1, 2, 4, 5, 7], [1, 2, 2, 3, 4, 7]] best_dice = find_the_best_dice(dices4) assert best_dice == 0 input = [[1, 1, 4, 6, 7, 8], [2, 2, 2, 6, 7, 7], [3, 3, 3, 5, 5, 8]] excepted = {'choose_first': False, 0: 1, 2: 0, 1: 2} output = compute_strategy(input) assert output == excepted
c13c703d11980c4313fe826b112934adc0808ec3
fbidu/Etudes
/Python/exceptions/chaining.py
539
3.625
4
# Exception masking a = {"key": "value!!"} try: unvalid = a["heey"] except KeyError as ke: raise Exception("I'll mask the key error!") from ke # Python 3.7 Output """ Traceback (most recent call last): File "chaining.py", line 6, in <module> unvalid = a["heey"] KeyError: 'heey' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "chaining.py", line 8, in <module> raise Exception("I'll mask the key error!") from ke Exception: I'll mask the key error! """
085bf90e0c8ebe9b2ff1836f12a74932008d84d9
JaisonVB/INTRODUCAOPYTHON
/aula1/exercicio5.py
431
3.921875
4
# Elaborar um programa que efetue a leitura de três valores inteiros (variáveis A, B, C) # e apresente como resultado final o valor do quadrado da soma var_A = int(input('Digite o primeiro valor ')) var_B = int(input('Digite o primeiro valor ')) var_C = int(input('Digite o primeiro valor ')) soma = var_A + var_B + var_C soma_quadrado = soma * soma print('O quadrado da soma dos valores digitados he ' + str(soma_quadrado))
01b72080419d548f8f1646dec0a22c552e36c7dd
bbb1991/devlabs-python
/week2/examples/example18.py
278
3.8125
4
# coding=utf-8 # Разное # Укороченная запись if else def my_abs(x): return x if x >= 0 else x * -1 print(my_abs(-5)) # Печать подключенных модулей print(dir(__builtins__)) # аналог type() print(isinstance(1, int))
58ab5f53b6f3192e7477ee823a606f6d66116b36
ssiddam0/Python
/Lab4/lab4-16_Sowjanya.py
1,183
4.40625
4
# program - lab4-16_sowjanya1.py 12 April 2019 ''' This program will perform the following actions: 1. ask for the input of number of squares to draw 2. Based on the input, draws a design using repaeated squares. ''' # ==============================import the turtle graphics system import turtle # =========== Named constants STARTING_LENGTH = 10 OFFSET = 5 # ========== Variable declarations. num_squraes = 0 length = STARTING_LENGTH # length of first square # ============ask the user for input num_squares = int(input('How many squares? ')) # =============Make sure it is not less than or equal to zero. while num_squares <= 0: print('ERROR: Please enter a value greater than 0') num_squares = int(input('How many squares? ')) # =======Draw the squares for count in range(num_squares): # =============hide the turtle turtle.hideturtle() # Draw the square for x in range(4): turtle.forward(length) turtle.left(90) length = length + OFFSET # increase the length of next square # ============Keep the window open. turtle.done()
1326ba7d5aaf18d8375fbdae7a98abe0aa05e5dc
cutoutsy/leetcode
/medium/problem24/Solution.py
780
3.75
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def swapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ if head is None or head.next is None: return head pre = head cur = head.next ans = cur tail = ListNode(0) while pre and cur: next = cur.next cur.next = pre pre.next = next tail.next = cur tail = tail.next.next pre = next if pre: cur = pre.next if pre: tail.next = pre tail = tail.next tail.next = None return ans
87402b2ab768de560be94667f2dbf033bcd63a4f
Kaushik8511/Competitive-Programming
/Mathematics/isPrime(O(sqrt(N)).py
280
4.1875
4
num = int(input("enter a number")) def isPrime(n): if n==0 or n==1: return False i=2 while(i*i<=n): if n%i==0: return False i+=1 return True print(isPrime(num))
6b820f76f2c1c1dfbe59e5b9792288746808bf54
natanno4/home_assistant
/db/db_handler.py
2,263
3.734375
4
import sqlite3 class DbHandler: def __init__(self, db_path): """ constructor :param db_path: db file path to connect to. :type db_path: str """ self.__path=db_path self.__conn = None self.__cursor = None def get_path(self): """ returns the data base connection path. """ return self.__path def connect(self): """ connect to the data base path. and create cursor.returns True if ok, else False. """ try: self.__conn = sqlite3.connect(self.__path) self.__cursor = self.__conn.cursor() print("connected to database") return True except: print('connection error') return False def disconnect(self): """ disconnect from the data base. """ if self.__conn: self.__conn.close() print("disconnected from database") def select(self, query, params): """ runs an select query with the given query and params. returns the result or None if Failed. disconnects from the connection after query. :param query: select query. :type query: str :param query: select query. :type query: str """ try: if params: self.__cursor.execute(query, params) else: self.__cursor.execute(query) rs = self.__cursor.fetchall() self.disconnect() return rs except: print('select failed') return None def insert(self, query, params): """ runs an insert query that can handle multiple values with the given query and params. returns the True or False if Failed. disconnects from the connection after query. :param query: insert query. :type query: str :param query: select query. :type query: str """ try: self.__cursor.executemany(query, params) self.__conn.commit() self.disconnect() return True except: print('insertion failed') return False
c16f182399168fca334dbf809031d8404a5a1404
tbhall/Ciphers
/rsa_cipher.py
4,080
3.96875
4
#!/bin/python # -*- coding: utf-8 -*- ###################################################################### ### ### ### Description: Uses the RSA encryption method to encrypt ### ### and decrypt data. ### ### ### ###################################################################### __author__ = "Tyler Hall" __copyright__ = "Copyright 2017" ################### # IMPORTS # ################### import random import rabinMiller ################### # GLOBAL # ################### ################### # FUNCTIONS # ################### # Desc : Greatest Common Denominator # Param : a : number # b : number #Returns : Greatest Common Denominator def gcd(a,b): while b != 0: a, b = b, a % b return a # Desc : Finds and returns two 2048 bit prime numbers # Param : NONE #Returns : p , q (Two prime 2048 bit numbers) def twoPrimes(): p = rabinMiller.generateLargePrime() q = rabinMiller.generateLargePrime() return p, q # Desc : Finds the value for d that fits in the equation e*d = 1 mod phi # Param : e : e value # phi : phi value #Returns : the d value def inverse(e,phi): d = 0 x1 = 0 x2 = 1 y1 = 1 temp_phi = phi while e > 0: temp1 = temp_phi/e temp2 = temp_phi - temp1 * e temp_phi = e e = temp2 x = x2- temp1* x1 y = d - temp1 * y1 x2 = x1 x1 = x d = y1 y1 = y if temp_phi == 1: return d + phi # Desc : produces the Public and Private key pairs # Param : p : 2048 bit prime number # q : 2048 bit prime number #Returns : (e,n),(d,n) returns the Public Key and the Private Key (e,n),(d,n) def keyPair(p,q): # Variables e,phi,d = 0, 0, 0 #n n = p * q #phi phi = (p-1)*(q-1) #e e = random.randint(1, phi) g = gcd(e, phi) while g != 1: e = random.randint(1, phi) g = gcd(e, phi) #d d = inverse(e, phi) return ((e,n), (d,n)) # Desc : Encrypts the plain Text with the public key # Param : plainText : Message you would like to encrypt # pubKey : Public Key #Returns : the Cipher Text def encrypt(plainText, pubKey): # Variables position = len(plainText) - 1 cipherText = 0 e, n = pubKey for i in range(len(plainText)): asciiChar = ord(plainText[i]) asciiChar = asciiChar * pow(256, position) position -= 1 cipherText += asciiChar cipherText = pow(cipherText, e, n) return cipherText # Desc : Takes the cipher Text and decrypts using the Private Key # Param : cipher: Encrypted message # privKey: Private Key #Returns : returns the plain text message def decrypt(cipher, privKey): #Variables charList = {} position = 0 loop = 0 plainText,decrypted = '', '' d, n = privKey cipherText= pow(cipher,d,n) decrypted = int(cipherText) while decrypted > 0: asciiChar = decrypted % 256 if asciiChar == 0: asciiChar = decrypted while asciiChar > 256: asciiChar = asciiChar / 256 loop += 1 charList[loop] = chr(asciiChar) decrypted -= asciiChar * pow(256, loop) loop = 0 else: charList[position] = chr(asciiChar) decrypted -= asciiChar * pow(256, position) position += 1 for index, value in sorted(charList.items(), reverse=True): plainText += charList[index] return plainText ################### # EX MAIN # ################### #Uncomment to see the example of code use """ #produce two primes p, q = twoPrimes() #get the keys pubKey, privKey = keyPair(p,q) #encrypt the plaintext encrypted = encrypt('TEST message FOR testing PURPOSES', pubKey) print encrypted #decrypt the cipher text decrypted = decrypt(encrypted, privKey) print decrypted """
b532e610f45e7aa88c5eee2c3c78132988a2cf97
Hongtao-Lin/Leetcode
/Python/109. Convert Sorted List to Binary Search Tree.py
1,006
3.953125
4
""" Idea Consider a one-pass O(n) time and O(1) space solution Using the in-order framework, we can move the linked list forward and only consider the current node assignment """ class Solution(object): def sortedListToBST(self, head): """ :type head: ListNode :rtype: TreeNode """ self.head = head if not head: return None def count(head): p = head cnt = 0 while p: cnt += 1 p = p.next return cnt # wrap the construction into range (i, j) def inorder(i, j): if i > j: return None mid = (j + i) / 2 left = inorder(i, mid - 1) node = TreeNode(self.head.val) # move linked list forward self.head = self.head.next node.left, node.right = left, inorder(mid + 1, j) return node return inorder(0, count(head) - 1)
f555b1d903d9646e4fdbcafaa300a424d5239efe
liuyanhui/leetcode-py
/leetcode/implement-strstr/implement-strstr.py
3,365
3.984375
4
""" https://leetcode.com/problems/implement-strstr/ 28. Implement strStr() Easy ----------------------------------- Implement strStr(). Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. Example 1: Input: haystack = "hello", needle = "ll" Output: 2 Example 2: Input: haystack = "aaaaa", needle = "bba" Output: -1 Clarification: What should we return when needle is an empty string? This is a great question to ask during an interview. For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf(). """ class Solution: def strStr(self, haystack, needle): return self.strStr_3(haystack, needle) def strStr_1(self, haystack, needle): """ 常规方法 :param haystack: :param needle: :return: """ if haystack is None: return -1 if needle is None or len(needle.strip()) == 0: return 0 for i in range(len(haystack)): if haystack[i] == needle[0] and haystack[i:i + len(needle)] == needle: return i return -1 def strStr_2(self, haystack, needle): """ 另一种实现方法 :param haystack: :param needle: :return: """ if haystack is None: return -1 if needle is None or len(needle.strip()) == 0: return 0 for i in range(len(haystack) - len(needle) + 1): count = 0 for j in range(len(needle)): if haystack[i + j] == needle[j]: count += 1 else: count = 0 break if count == len(needle): return i return -1 def strStr_3(self, haystack, needle): """ 另一种实现方法 :param haystack: :param needle: :return: """ if haystack is None: return -1 if needle is None or len(needle.strip()) == 0: return 0 for i in range(len(haystack) - len(needle) + 1): for j in range(len(needle)): if haystack[i + j] == needle[j]: if j == len(needle) - 1: return i else: break return -1 def main(): haystack = "hello" needle = "ll" ret = Solution().strStr(haystack, needle) print(ret) print("------------") haystack = "aaaaa" needle = "bba" ret = Solution().strStr(haystack, needle) print(ret) print("------------") haystack = "sdsd" needle = "" ret = Solution().strStr(haystack, needle) print(ret) print("------------") haystack = "" needle = "" ret = Solution().strStr(haystack, needle) print(ret) print("------------") haystack = "aaa" needle = "aaaa" ret = Solution().strStr(haystack, needle) print(ret) print("------------") haystack = "mississippi" needle = "sipp" ret = Solution().strStr(haystack, needle) print(ret) print("------------") haystack = "a" needle = "a" ret = Solution().strStr(haystack, needle) print(ret) print("------------") if __name__ == '__main__': main()
1207d889d8e4e5d304270e91b6cbb8ff50c3720a
DmitryVlaznev/leetcode
/35-search-insert-position.py
1,102
4.0625
4
# 35. Search Insert Position # Given a sorted array and a target value, return the index if the # target is found. If not, return the index where it would be if it were # inserted in order. # You may assume no duplicates in the array. # Example 1: # Input: [1,3,5,6], 5 # Output: 2 # Example 2: # Input: [1,3,5,6], 2 # Output: 1 # Example 3: # Input: [1,3,5,6], 7 # Output: 4 # Example 4: # Input: [1,3,5,6], 0 # Output: 0 from typing import List class Solution: def searchInsert(self, nums: List[int], target: int) -> int: l = -1 r = len(nums) while r - l > 1: mid = l + (r - l) // 2 if nums[mid] < target: l = mid else: r = mid return r def log(correct, res): if correct == res: print("[v]", res) else: print(">>> INCORRECT >>>", correct, " | ", res) t = Solution() log(2, t.searchInsert([1, 3, 5, 6], 5)) log(1, t.searchInsert([1, 3, 5, 6], 2)) log(4, t.searchInsert([1, 3, 5, 6], 7)) log(0, t.searchInsert([1, 3, 5, 6], 0)) log(0, t.searchInsert([], 42))
f35290dbd65ecf08f11d1a780f24d275a58b57d8
evilgod/Leetcode
/ReverseInteger/reverseInt.py
443
3.625
4
class Solution: # @return an integer def reverse(self, x): result = "" if x == 0: return 0 if x < 0: result = "-" x = abs(x) while x > 0: p = x%10 q = x/10 result = result + str(p) x=q r = int(result) return r #return result /return a string if need 021 instead of 21
2206893a32ea57675028d45cc09868ea100f6985
nigel2912/guess_number
/guess_number.py
2,176
4.46875
4
# implement a guessing game # where the computer has a secret no. which we have to guess # having the computer gen a secret no import random # random.randint(a,b) returns a no 'n' in range (a,b) such that a<n<b # computer generates the random number and user guesses it def guess(x): random_number = random.randint(1, x) # returns a random number guess = 0 while guess != random_number: guess = int(input(f'Guess a number between 1 and {x}: ')) if guess < random_number: print('Sorry,too low.Guess again') if guess > random_number: print('Sorry,too high.Guess again') print(f'Yay! Congrats.You have guessed the number {random_number} correctly') def computer_guess(x): low = 1 high = x feedback = '' while feedback != 'c': if low != high: # we can't have this condition in the while loop # because the whole point of the function is that we want the user to say # whether the number is correct(c) or not # so if we put the low!=high condition in the while condition # and for eg low == high in a case then the while loop will # break without executing the rest of the function # and therefore the statement 'Yay!...' will be printed directly, # but we don't want that directly, we want the user to enter 'c' guess = random.randint(low, high) else: guess = low # or high, doesn't matter as low = high # Note: random.randint will throw an error if low and high are the same value # because if low and high are equal then basically the computer has # narrowed it down to your number feedback = input(f'Is {guess} too High(H), too Low(L), or Correct(C)').lower() if feedback == 'h': high = guess-1 elif feedback == 'l': low = guess+1 print(f'Yay! the computer guessed your number, {guess},correctly') # guess(10) #for the user to guess a certain number computer_guess(1000) # for the computer to guess a certain number
aea204e593f7caba9431f82bd78e64b6bd1744f8
DBeardionaire/learning-python
/thehardway/test.py
1,288
3.984375
4
lloyd = { "name": "Lloyd", "homework": [90.0, 97.0, 75.0, 92.0], "quizzes": [88.0, 40.0, 94.0], "tests": [75.0, 90.0] } alice = { "name": "Alice", "homework": [100.0, 92.0, 98.0, 100.0], "quizzes": [82.0, 83.0, 91.0], "tests": [89.0, 97.0] } tyler = { "name": "Tyler", "homework": [0.0, 87.0, 75.0, 22.0], "quizzes": [0.0, 75.0, 78.0], "tests": [100.0, 100.0] } class_list = [lloyd, alice, tyler] # Add your function below! def average(lst): return float(sum(lst)) / len(lst) def get_average(student_dict): return average(student_dict["homework"]) * 0.1 + average(student_dict["quizzes"]) * 0.3 + average(student_dict["tests"]) * 0.6 def get_letter_grade(score): if score >= 90: return "A" elif score >= 80: return "B" elif score >= 70: return "C" elif score >= 60: return "D" else: return "F" def get_class_average(a_class_list): class_total = 0 for each_student in a_class_list: class_total += get_average(each_student) class_average = float(class_total) / len(a_class_list) return class_average print "The class average is %f" % get_class_average(class_list) print "That is a(n) %s!" % get_letter_grade(get_class_average(class_list))
4bdd28d1987d8dbfec3e34f2740951e8593dcc20
QiongWangUSCEE/EE511-Simulation-Methods-for-Stochastic-Systems
/project2/Q3(ab).py
535
3.640625
4
import random import matplotlib.pyplot as plt for times in range(20): X2 = 0 num = 1000 degree = 9 sample = [] for i in range(num): sample.extend(random.sample(range(10), 1)) for i in range(degree + 1): X2 += ((sample.count(i) - num / (degree + 1)) ** 2) / (num / (degree + 1)) print('In the ' + str(times) + ' times calculation, chi-Square =', X2) plt.figure() plt.hist(sample, bins=range(11), edgecolor='black', ) plt.xlabel('value of samples') plt.ylabel('number of sample') plt.show()
4151807b069f082f6b8426e033b7caf997507d7d
jennyChing/onlineJudge
/350.py
1,378
3.96875
4
''' functions - 350 - Pseudo-Random Numbers A common pseudo-random number generation technique is called the linear congruential method. If the last pseudo-random number generated was L, then the next number is generated by evaluating ( tex2html_wrap_inline32 , where Z is a constant multiplier, I is a constant increment, and M is a constant modulus. For example, suppose Z is 7, I is 5, and M is 12. In this problem you will be given sets of values for Z, I, M, and the seed, L. Each of these will have no more than four digits. For each such set of values you are to determine the length of the cycle of pseudo-random numbers that will be generated. But be careful: the cycle might not begin with the seed! ''' def mod(Z, I, M, L): cnt = 0 while True: remain = (Z * L + I) % M L = remain if remain in seen: return len(seen) seen.add(remain) case = 0 if __name__ == '__main__': while True: try: Z, I, M, L = list(map(int, input().split())) if Z == 0 and I == 0 and M == 0 and L == 0: break elif M == 0: continue while L > M: L = L % M case += 1 seen = set() mod(Z, I, M, L) print("Case ", case, ": ", len(seen), sep="") except(EOFError): break
0041608cafd2a0c1ca58b94404f8d430d3596415
aninda052/Computative_Programming-
/LeetCode/9/9-Palindrome_Number.py
369
3.53125
4
class Solution(object): def isPalindrome(self, x): """ :type x: int :rtype: bool """ if x < 0: return False reverse_x = 0 tmp_x = x while tmp_x: remainder = tmp_x % 10 tmp_x /= 10 reverse_x = (reverse_x * 10) + remainder return x == reverse_x
7293396f1e7b631b089af28dfe6f9c98ed0cfcb6
Ghostfyx/machine_learning_algorithms
/linerRegression/computeCostMult.py
607
3.796875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/12/15 18:07 # @Author : fanyuexiang # @Site : 求解多特征数据集损失函数 # @File : computeCostMult.py # @Software: PyCharm import numpy as np def computeCostMult(X, y, theta): """ Compute cost for linear regression with multiple variables J = computeCost(X, y, theta) computes the cost of using theta as the parameter for linear regression to fit the data points in X and y """ m = y.size J = 0 h_theta = np.dot(X, theta) J = (h_theta - y).dot(h_theta-y) /(2*m) return J
cd9dd2ba8e0959bd0a93e193914b5aea89dcab0b
azuretime/Digital-World
/W5/extract_value calc_ratios.py
501
4.15625
4
def extract_values(values): values=values.strip().split() return (int(values[0]),int(values[1])) '''strip() returns a copy of the string in which all chars have been stripped from the beginning and the end of the string (default whitespace characters). str = "0000000this is string example....wow!!!0000000"; print str.strip( '0' ) this is string example....wow!!!''' def calc_ratios(values): if values[1]==0: return None return float(values[0])/values[1]
83d9662eb0e9a60f15cbfd66bf46b12713620813
jkusita/Automate-Ideas-for-Similar-Programs-1
/tempCodeRunnerFile.py
224
3.5625
4
# Enter seconds here # # 1800 seconds = 30 minutes, 120 seconds = 2 minutes # time_limit = 10 # while time_limit != 0: # print(time_limit) # So that you can see the time left # time_limit -= 1 # time.sleep(1)
c36b7fcd888b222dad589e37e971f1c637f915c3
banditypte/leet-code
/longest_common_prefix.py
841
3.734375
4
class Solution: def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if len(strs) == 0: return '' prefix = strs[0] for string in strs[1:]: cur_prefix = '' for i_char, char in enumerate(prefix): if i_char > len(string) - 1: break if char is not string[i_char]: break cur_prefix += char prefix = cur_prefix if len(prefix) == 0: break return prefix if __name__ == '__main__': assert Solution().longestCommonPrefix(['flower', 'flow', 'flight']) == 'fl' assert Solution().longestCommonPrefix(['dog', 'racecar', 'car']) == '' assert Solution().longestCommonPrefix([]) == ''
2bab7c39d62579f60dae4c6f75d60a90f4658465
thaysom22/dsa-problems
/fibonacci.py
789
3.609375
4
# import random def calc_fib(n): if n < 2: return n fib_vals = [0]*(n+1) fib_vals[1] = 1 for i in range(2, n+1): fib_vals[i] = fib_vals[i-1] + fib_vals[i-2] return fib_vals[n] # def calc_fib_naive(n): # if n < 2: # return n # return calc_fib_naive(n-1) + calc_fib_naive(n-2) # def generate_input(): # return random.randint(0, 30) # if __name__ == '__main__': # # stress test # while True: # n = generate_input() # print(n) # result1 = calc_fib_efficient(n) # result2 = calc_fib_naive(n) # if result1 == result2: # print("OK") # else: # print(result1, result2) # break # manual input n = int(input()) print(calc_fib(n))
5689cc2e627b3547810153939e1375c189604c37
pu-bioinformatics/python-exercises-Fnyasimi
/Scripts/exercise05_bank.py
1,895
3.828125
4
#! /home/user/anaconda2/envs/bioinf/bin/python #This script was made in Python 3.7.2 acountbal = 50000 print('%s' % "Welcome to Festus Enterpise Bank".center(60)) print('%s' %"We are commited to serve you".center(60)) choice = input("Please enter 'b' to check balance, 'w' to withdraw, or 'd' to deposit: ") while choice != 'q': if choice.lower() in ('w','b','d'): if choice.lower() == 'd': print("How much do you want to deposit?") deposit = float(input("Enter amount to deposit: ")) print ("You have deposited %d into your account." %deposit) acountbal= acountbal + deposit print("Your new account balance is: %d." %acountbal) choice = input("Enter b for balance, w to withdraw, d for deposit or q to quit: ") print(choice.lower()) if choice.lower() == 'b': print("Your balance is: %d" % acountbal) print("Do you want to do another transaction?") choice = input("Enter b for balance, w to withdraw, d to deposit or q to quit: ") print(choice.lower()) else: withdraw = float(input("Enter amount to withdraw: ")) if withdraw <= acountbal: print("Here is your: %.2f" % withdraw) acountbal = acountbal - withdraw print("Your new account balance is: %d." %acountbal) print("Do you want to do another transaction?") choice = input("Enter b for balance, w to withdraw, d for deposit or q to quit: ") #choice = 'q' else: print("You have insufficient funds, your account balance is: %.2f" % acountbal) else: print("Wrong choice!") choice = input("Please enter 'b' to check balance 'w' to withdraw or 'd' to deposit: ") #CK: Good
2f1db5676446327f2787d8d1c61c941472a3fa91
shady1924/chap1
/Assisgments/ch7_10_main.py
491
3.890625
4
from Assisgments.ch7_10 import Time def main(): # create object for current time t1 = Time() print('Current time is {0}:{1}:{2}'.format(t1.getHour(),t1.getMinute(),t1.getSecond()) ) # get input from the user setseconds=eval(input("Enter the elapsed time:")) ## 55550505 # set the new time for the object t1.setTime(setseconds) print('The hour:minute:second for the elapsed time is {0}:{1}:{2}'.format(t1.getHour(),t1.getMinute(),t1.getSecond()) ) main()
4f94380c66e2d2248431f0893d22ffbbb69e5c99
JianHangChen/LeetCode
/Lint14. First Position of Target.py
545
3.859375
4
class Solution: """ @param nums: The integer array. @param target: Target to find. @return: The first position of target. Position starts from 0. """ def binarySearch(self, nums, target): low = 0 high = len(nums) - 1 while low < high: mid = low + (high - low) // 2 if nums[mid] >= target: high = mid else: low = mid + 1 if nums and nums[low] == target: return low else: return -1
cef70e7eb527c89e7b29a493de495f01f5ca1cc6
nkukarl/leetcode
/remove_nth_node_from_end_of_list_test.py
832
3.515625
4
from unittest import TestCase from remove_nth_node_from_end_of_list import Solution from utils_linked_list import compare_linked_lists, get_head_linked_list class TestRemoveNthNodeFromEndOfList(TestCase): def test_remove_nth_from_end(self): # Setup sol = Solution() N = 5 linked_list_raw = [n for n in range(1, N + 1)] # Exercise and Verify for n in range(1, N + 1): head = get_head_linked_list(linked_list_raw) head = sol.remove_nth_from_end(head, n) expected_linked_list_raw = linked_list_raw[:-n] if n != 1: expected_linked_list_raw += linked_list_raw[-(n - 1):] expected_head = get_head_linked_list(expected_linked_list_raw) self.assertTrue(compare_linked_lists(head, expected_head))
e16960d3759677e4f7f13b30728b07d321c94af5
Hugocorreaa/Python
/Curso em Vídeo/Desafios/Mundo 2/ex044 - Gerenciador de Pagamentos.py
1,409
4.0625
4
""" Elabore um programa que calcule o valor a ser pago por um produto, considerando o seu preço normal e condição de pagamento: -Á vista dinheiro/cheque: 10% de desconto -À vista no cartão: 5% de desconto -Em até 2x no cartão: Preço Normal -3x ou mais no cartão: 20% de Juros """ valor = float(input("Digite o valor do produto: R$")) print("""Qual a forma de pagamento? [1] Dinheiro ou Cheque. [2] Á vista no cartão. [3] Em até 2x no cartão. [4] 3x ou mais no cartão.""") pag = int(input("Sua opção: ")) if pag == 1: descont = valor - (valor * 10 // 100) print("""Com pagamento em dinheiro ou cheque você tem 10% de desconto. Valor com desconto: R${:.2f} reais""".format(descont)) elif pag == 2: descont = valor - (valor * 5 // 100) print("""Com pagamento à vista no cartão você tem 5% de desconto. Valor com desconto: R${:.2f} reais""".format(descont)) elif pag == 3: par = valor / 2 print("Sua compra será parcelada em 2x de R${:.2f} SEM JUROS.".format(par)) print("Valor final: R${:.2f} reais".format(valor)) elif pag == 4: parcelas = int(input("Quantas parcelas? ")) par = valor / parcelas print("Sua compra será parcelada em {}x de R${:.2f} COM 20% DE JUROS.".format(parcelas, par)) juros = (valor * 20 / 100) + valor print("Valor com juros: R${:.2f} reais".format(juros)) else: print("\033[1;31mOperação Inválida!\033[m")
a9a5df8868059c15d4dfdc949291b2670f545198
Mugeri/Bootcamp-7
/andelabs/reverse_string.py
137
4
4
def reverse_string(string): if string == '': return None string1 = string[::-1] if string1 == string: return True return string1
c699c7428a17620bbf365ab7f919b1d167f3b884
calonso/IEAlgorithmsDataStructures
/bubble_sort.py
225
4.0625
4
def bubble_sort(data): for i in range(len(data)): for j in range(len(data)-i-1): if data[j] > data[j+1]: temp = data[j] data[j] = data[j+1] data[j+1] = temp return data print(bubble_sort([3, 6, 2, 1]))
dc481c354f1afe3d93e1db3f17c1b7d033b98bb2
burglim/practiceprojects
/notebooks/games/blackjack/blackjack.py
4,713
3.765625
4
from random import shuffle from IPython.display import clear_output nums = ['Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace'] suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades'] values = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, 'Nine':9, 'Ten':10, 'Jack':10, 'Queen':10, 'King':10, 'Ace':11} class Card: def __init__(self,num,suit): self.num = num self.suit = suit self.value = values[num] def __str__(self): return f'{self.num} of {self.suit}' class Deck: def __init__(self): self.whole_deck = [] for suit in suits: for num in nums: created_card = Card(num, suit) self.whole_deck.append(created_card) def __str__(self): return f'{len(self.whole_deck)} cards' def shuffle(self): return shuffle(self.whole_deck) def deal_one(self): return self.whole_deck.pop() class Chips: def __init__(self, balance=100): self.balance = balance def __str__(self): return f'Account balance: {self.balance} chips' def deposit(self, deposit): self.balance += deposit print(f'New balance: {self.balance} chips') def withdraw(self, withdraw): if withdraw>self.balance: print('Chips Unavailable!') else: self.balance -= withdraw print(f'Accepted\nNew balance: {self.balance} chips') class Hand: def __init__(self): self.cards_in_hand = [] self.hand_value = 0 def __str__(self): return f'Number of cards played: {len(self.cards_in_hand)}\nValue of hand: {self.hand_value}' def play_one(self, new_card): self.cards_in_hand.append(new_card) if new_card.num == 'Ace': if self.hand_value <= 10: new_card.value = 11 else: new_card.value = 1 self.hand_value += new_card.value print(new_card) def play_one_hidden(self, new_card): self.cards_in_hand.append(new_card) self.hand_value += new_card.value def bet(chips): player_bet = True while player_bet: try: bet_amount = int(input('How much would you like to bet? Please enter a whole number: ')) if bet_amount > chips.balance: print('Chips Unavailable!') continue player_bet = False break except ValueError: print('Please enter an integer') continue if bet_amount == 0: print('Game Ended') return bet_amount else: chips.withdraw(bet_amount) return bet_amount def player_choice(): valid = False while valid == False: choice = input('Would you like to hit or stay? ').lower() if choice[0] == 'h' or choice[0] == 's': valid = True else: print('Please enter either hit or stay') continue if choice[0] == 'h': return 'hit' else: return 'stay' def win_check(marker, person, comp, chips, bet_amount): #print(person.hand_value) if person.hand_value > 21: print('You lose!') marker = False return marker elif person.hand_value == 21: print('You win: you receive double your bet!') chips.deposit(bet_amount*2) marker = False return marker else: pass def comp_win_check(marker, person, comp, chips, bet_amount): if comp.hand_value > 21: print('You win: you receive double your bet!') chips.deposit(bet_amount*2) marker = False return marker elif comp.hand_value == 21: print('You lose!') marker = False return marker elif comp.hand_value > person.hand_value: print('Bust: you lose!') marker = False return marker elif comp.hand_value < person.hand_value: print('You win: you receive double your bet!') chips.deposit(bet_amount*2) marker = False return marker elif comp.hand_value == person.hand_value: print('Draw: you get your chips back') chips.deposit(bet_amount) marker = False return marker else: print('Error') def play_again(): answer = input('Would you like to play again? Please type y or n: ').lower() if answer == 'y': clear_output(wait=True) return True else: return False
c5789c34bddd97d0ddb811a068c393fd530b4ec5
yeshaj/CS261
/assignment3/max_stack_sll.py
2,369
3.75
4
# Yesha Jhala # CS 261 # Assignment 3 Part 3 # Description: Implementation of a stack built off of a singly linked list structure, and keep track of max value of stack for O(1) getter method. from sll import * class StackException(Exception): """ Custom exception to be used by MaxStack Class DO NOT CHANGE THIS CLASS IN ANY WAY """ pass class MaxStack: def __init__(self): """ Init new MaxStack based on Singly Linked Lists DO NOT CHANGE THIS METHOD IN ANY WAY """ self.sll_val = LinkedList() self.sll_max = LinkedList() def __str__(self) -> str: """ Return content of stack in human-readable form DO NOT CHANGE THIS METHOD IN ANY WAY """ out = "MAX STACK: " + str(self.sll_val.length()) + " elements. " out += str(self.sll_val) return out def push(self, value: object) -> None: """ Adds node containing value to top of the stack """ self.sll_val.add_front(value) if self.sll_max.is_empty(): self.sll_max.add_front(value) current_max = self.sll_max.get_front() if value > current_max: self.sll_max.add_front(value) else: self.sll_max.add_front(current_max) def pop(self) -> object: """ Removes top element from stack and returns its value """ if self.sll_val.is_empty(): raise StackException self.sll_max.remove_front() top_value = self.sll_val.get_front() self.sll_val.remove_front() return top_value def top(self) -> object: """ Returns value of the top of the stack in a non-destructive manner """ if self.sll_val.is_empty(): raise StackException return self.sll_val.get_front() def is_empty(self) -> bool: """ Indicates whether MaxStack is empty """ return self.sll_val.is_empty() def size(self) -> int: """ Returns the number of elements in the MaxStack """ return self.sll_val.length() def get_max(self) -> object: """ Returns maximum value currently stored in MaxStack """ if self.is_empty(): raise StackException return self.sll_max.get_front()
403424c6ac3cb4acb1c9ce2a3d6e5402c1875bce
GuoQin8284/PythonCode
/学院管理系统/student.py
447
3.578125
4
class Student(): def __init__(self, name, age): self.name = name self.age = age self.stu_data = self.load_student_info("./stu_data.txt") def __str__(self): data = f'{self.name}, {self.age}' print(type(data)) return data def load_student_info(self,file_path): stu_file = open(f"{file_path}","w+",encoding="utf-8") stu_data = stu_file.readlines() return stu_data
91f1e4782ea97fad00f6c77a791dea06359658a2
Zebfred/ENIT_reference
/Mobile_Laptop/Additional_Resources/code_signal/CodeSignal-WorkingSolutions/Codesignal Arcade - Intro/44 - findEmailDomain.py
201
3.671875
4
def findEmailDomain(address): address_spl = address.split("@") c = [ i for i in address_spl ] if len(address_spl) == 2: return c[1] if len(address_spl) == 3: return c[2]
ea806becec12909e6cd578908b9bbf80e379a7a1
InfoTech-Academy/Python_Week3
/3.week-homework-7.py
110
3.765625
4
def word_upper(): x= input("please enter word or sentence : ") return print(x.title()) word_upper()
6012b80dd8bb2a00df247b7af87dc0c11e7d6b3d
kdandiwala/Calculator
/project.py
2,871
4.0625
4
from tkinter import * root = Tk() root.title("Calculator") root.configure(background='white') root.resizable(False, False) console = StringVar() console.set('') window = Entry(root, textvariable = console) text = str(window) window.grid(row = 0, columnspan = 4, ipady=7) def button_press(num): global text text = text + str(num) console.set(text) def clear_press(): global text text = "" console.set("") def equal_press(): try: global text answer = str(eval(text)) console.set(answer) except: console.set("Error") text = "" #number button gui one = Button(root, text = "1", fg = "black", bg = 'red', height=5, width=8, command=lambda: button_press(1)) two = Button(root, text = "2", fg = "black", height=5, width=8, command=lambda: button_press(2)) three = Button(root, text = "3", fg = "black", height=5, width=8, command=lambda: button_press(3)) four = Button(root, text = "4", fg = "black", height=5, width=8, command=lambda: button_press(4)) five = Button(root, text = "5", fg = "black", height=5, width=8, command=lambda: button_press(5)) six = Button(root, text = "6", fg = "black", height=5, width=8, command=lambda: button_press(6)) seven = Button(root, text = "7", fg = "black", height=5, width=8, command=lambda: button_press(7)) eight = Button(root, text = "8", fg = "black", height=5, width=8, command=lambda: button_press(8)) nine = Button(root, text = "9", fg = "black", height=5, width=8, command=lambda: button_press(9)) zero = Button(root, text = "0", fg = "black", height=5, width=16, command=lambda: button_press(0)) seven.grid(row=2, column=0) eight.grid(row=2, column=1) nine.grid(row=2, column=2) four.grid(row=3, column=0) five.grid(row=3, column=1) six.grid(row=3, column=2) one.grid(row=4, column=0) two.grid(row=4, column=1) three.grid(row=4, column=2) zero.grid(columnspan=2, row=5, sticky = E) #action button gui decimal = Button(root, text = ".", fg = "black", height=5, width=8, command=lambda: button_press(".")) equal = Button(root, text = "=", fg = "black", height=5, width=8, command = equal_press) clear = Button(root, text = "Clear", fg = "black", height=5, width=25, command = clear_press) add = Button(root, text = "+", fg = "black", height=5, width=8, command=lambda: button_press("+")) subtract = Button(root, text = "-", fg = "black", height=5, width=8, command=lambda: button_press("-")) divide = Button(root, text = "/", fg = "black", height=5, width=8, command=lambda: button_press("/")) multiply = Button(root, text = "x", fg = "black", height=5, width=8, command=lambda: button_press("*")) decimal.grid(column = 2, row = 5) equal.grid(column = 3, row = 5) clear.grid(columnspan=3, row=1) add.grid(row=1, column=3) subtract.grid(row=2, column=3) multiply.grid(row=3, column=3) divide.grid(row=4, column=3) root.mainloop()
be157fb4c4a78da4069c0840f525345ac37211e2
daviswu/selfteaching-python-camp
/exercises/1901100294/1001S02E05_string.py
1,844
3.734375
4
text = ''' The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambxiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! ''' print('这是第1个小要求,把better换成worse\n') text_replace = text.replace('better','worse') print(text_replace) text_new = text_replace.split(' ') #把字符串分割成列表 '''import re 正则表达式方法 把单词为单位分隔开 text_string = re.findall(r"\w+",text_replace) print(text_string)''' list_text = [] for strea in text_new: if 'ea' in strea: strea = strea.replace(strea,'') else: pass list_text.append(strea) #删掉列表中包含ea的值 print(list_text) print('这是第2个小要求,删除掉包含ea的字符\n') string_text = " ".join(list_text) #再把列表转成字符串 print(string_text) print('这是第3个小要求,转换大小写\n') text_trans = string_text.swapcase()#这是大小写转换 print(text_trans) print('这是第4个小要求,将所有单词按照a...z的升序排列\n') list_new = text_trans.split(' ') list_new.sort() list_sorted = "".join(list_new) print(list_sorted)
bcce1ed1bb63873e81ab2b6ba87602a7ef569d67
kdaivam/leetcode
/DI String match.py
420
3.515625
4
class Solution: def diStringMatch(self, a: str) -> List[int]: low = 0 high = len(a) res = [] for i in a: if i == 'I': res.append(low) low += 1 else: res.append(high) high -= 1 res += [high] #add left out element to the result return res
b4365951efb1e6b398afd76c9404e9fa85d654ac
rhitayu2/solar-cell-maintenance
/solar_cell.py
1,093
3.515625
4
import RPi.GPIO as GPIO import time filename = "/home/pi/solar_cell_reading" #Setting the configuration as board instead of BCM GPIO.setmode(GPIO.BOARD) #Setting the pins in which the 8 bit output will come GPIO.setup(3, GPIO.IN) GPIO.setup(5, GPIO.IN) GPIO.setup(8, GPIO.IN) GPIO.setup(10, GPIO.IN) GPIO.setup(11, GPIO.IN) GPIO.setup(12, GPIO.IN) GPIO.setup(13, GPIO.IN) GPIO.setup(15, GPIO.IN) #Setting the pin in which the ALE(Address Latch Enable would be set) GPIO.setup(38, GPIO.OUT) #Setting the Address Latch to IN0 according to the clock cycle GPIO.output(38, GPIO.HIGH) time.sleep(0.5) GPIO.output(38, GPIO.LOW) while True: #Opening the file in which the readings of the solar cell need to be stored f = open(filename, "w") i = GPIO.input(3)*128 + GPIO.input(5)*64 + GPIO.input(8)*32+GPIO.input(10)*16+GPIO.input(11)*8+GPIO.input(12)*4+GPIO.input(13)*2+GPIO.input(15)*1 #Digital output, needs to be converted to output voltage #i = i* 5/256 #To get the current reading, we need to use the formula V=IR print(i) f.write(str(i)) time.sleep(2)
f5eb203c7d67edf5c3b9a753782ed84f14ed7c92
ankita30/Exam-Statistics
/Exam_statistics.py
705
3.9375
4
grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5] def print_grades(grades): for grade in grades: print grade def grades_sum(grades): return sum(grades) def grades_average(grades): return grades_sum(grades)/ float(len(grades)) def grades_variance(grades): average = grades_average(grades) variance = 0 for score in grades: variance += (average - score)**2 return variance/len(grades) def grades_std_deviation(variance): return variance**0.5 variance = grades_variance(grades) print print_grades(grades) print grades_sum(grades) print grades_average(grades) print grades_variance(grades) print grades_std_deviation(variance)
ecb38516d5992fcc4cb0824ac99a955b78f8aa6c
Travmatth/LeetCode
/Medium/jump_game.py
1,393
3.90625
4
""" Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Determine if you are able to reach the last index. """ class Solution(object): def canJump(self, nums): """ :type nums: List[int] :rtype: bool """ n = len(nums) if n <= 1: return True last = n - 1 for i in reversed(range(n)): if i + nums[i] >= last: last = i return last == 0 if __name__ == "__main__": s = Solution() ex_0 = s.canJump([2, 3, 1, 1, 4]) if ex_0 != True: print("Error") # Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index. ex_1 = s.canJump([3, 2, 1, 0, 4]) if ex_1 != False: print("Error") # Explanation: You will always arrive at index 3 no matter what. Its maximum # jump length is 0, which makes it impossible to reach the last index. ex_2 = s.canJump([2, 5, 0, 0]) if ex_2 != True: print("Error") ex_3 = s.canJump([2,0,6,9,8,4,5,0,8,9,1,2,9,6,8,8,0,6,3,1,2,2,1,2,6,5,3,1,2,2,6,4,2,4,3,0,0,0,3,8,2,4,0,1,2,0,1,4,6,5,8,0,7,9,3,4,6,6,5,8,9,3,4,3,7,0,4,9,0,9,8,4,3,0,7,7,1,9,1,9,4,9,0,1,9,5,7,7,1,5,8,2,8,2,6,8,2,2,7,5,1,7,9,6]) if ex_3 != True: print("Error") pass
86f33d38a055d94ed4a119e3d94031817ec11c17
darkbodhi/Some-python-homeworks
/pyramid2.py
324
3.703125
4
total = int(input("Please, insert the number of rows: ")) y = int(1) counter = int(0) my_list = [] my_list.append(y) for counter, i in enumerate(range(0, total)): for j in range(1): print(*my_list, end=" ") my_list.clear() for w in range(counter): y += 1 my_list.append(y)
293538e544b8e97db6f02e8e78c41d86dedada3e
saigowtham96/testing-repository
/cspp1-practice/m6/p3/digit_product.py
296
3.859375
4
''' Given a number int_input, find the product of all the digits ''' NUM = int(input()) # NUM = -12345 temp = NUM I = 1 if NUM < 0: NUM = NUM * -1 while NUM >= 1: A = NUM%10 I = A*I NUM = NUM//10 if temp < 0: I = I * -1 if temp == 0: print(temp) else: print(I)
611d73ab4d1797da6db8354ada4c6a69d1f2c4d1
matiyashu/pythonProjectCodeCademy
/Strings_medical-Insurance.py
2,579
3.96875
4
medical_data = \ """Marina Allison ,27 , 31.1 , #7010.0 ;Markus Valdez , 30, 22.4, #4050.0 ;Connie Ballard ,43 , 25.3 , #12060.0 ;Darnell Weber , 35 , 20.6 , #7500.0; Sylvie Charles ,22, 22.1 ,#3022.0 ; Vinay Padilla,24, 26.9 ,#4620.0 ;Meredith Santiago, 51 , 29.3 ,#16330.0; Andre Mccarty, 19,22.7 , #2900.0 ; Lorena Hodson ,65, 33.1 , #19370.0; Isaac Vu ,34, 24.8, #7045.0""" #code: print(medical_data) updated_medical_data = medical_data.replace("#", "$") print(updated_medical_data) num_records = 0 for character in updated_medical_data: if character == "$": num_records += 1 print(f"\nThere are " + str(num_records) + " medical records in the data.") # split(";") will create a separate item in the list each time ";" occurs in the string medical_data_split = updated_medical_data.split(";") print(f"\n{medical_data_split}") medical_records = [] for record in medical_data_split: medical_records.append(record.split(',')) print(f"\n{medical_records}") medical_records_clean = [] # outside loop that goes through each record in medical_records for record in medical_records: # empty list that will store each cleaned record record_clean = [] # nested loop to go through each item in each medical record for item in record: # cleaning the whitespace for each record using item.strip() record_clean.append(item.strip()) # add the cleaned medical record to the medical_records_clean list medical_records_clean.append(record_clean) print(f"\n{medical_records_clean}") for record in medical_records_clean: print(f"\n{record[0]}") for record in medical_records_clean: record[0] = record[0].upper() print(record[0]) names = [] ages = [] bmis = [] insurance_costs = [] """ Next, iterate through medical_records_clean and for each record: Append the name to names. Append the age to ages. Append the BMI to bmis. Append the insurance cost to insurance_costs. """ for records in medical_records_clean: names.append(records[0]) ages.append(records[1]) bmis.append(records[2]) insurance_costs.append(record[3]) print("Names: " + str(names)) print("Ages: " + str(ages)) print("BMI: " + str(bmis)) print("Insurance Costs: " + str(insurance_costs)) # calculate the average BMI in our dataset. total_bmi = 0 for bmi in bmis: total_bmi += float(bmi) # calculate average BMI average_bmi = total_bmi/len(bmis) print("Average BMI: " + str(average_bmi)) #Extra insurace_costs = 0 for i in range(len(names)): print(f"\n{names[i] + ' is ' + ages[i] + ' years old with a BMI of ' + bmis[i] + ' and an insurance cost of ' + insurance_costs[i] + '.'}")
25ac9f4e9558c2044c1d5aad20f3c602204a43e6
decimozack/coding_practices
/leetcode/python/longest_palindromic_substr.py
2,105
3.59375
4
#!/usr/bin/python3 # https://leetcode.com/problems/longest-palindromic-substring/ class Solution: def longestPalindrome(self, s: str) -> str: lg_str = '' lg_count = 0 str_len = len(s) for idx, char in enumerate(s): # check for odd palindrome curr_str = self.odd_palindrome(s, idx, str_len) if len(curr_str) > lg_count: lg_str = curr_str lg_count = len(curr_str) # check of even palindrome curr_str = self.even_palindrome(s, idx, str_len) if len(curr_str) > lg_count: lg_str = curr_str lg_count = len(curr_str) return lg_str def odd_palindrome(self, s: str, idx: int, str_len: int) -> str: is_palin = True start = end = idx count = 1 while is_palin: if idx - count >= 0 and idx + count < str_len: if s[idx - count] == s[idx + count]: start = idx - count end = idx + count count = count + 1 else: is_palin = False else: is_palin = False return s[start:end + 1] def even_palindrome(self, s: str, idx: int, str_len: int) -> str: is_palin = True start = end = idx count = 1 if idx - 1 >= 0 and s[idx - 1] != s[idx]: return '' else: start = idx - 1 end = idx while is_palin: if idx - count - 1 >= 0 and idx + count < str_len: if s[idx - count - 1] == s[idx + count]: start = idx - count - 1 end = idx + count count = count + 1 else: is_palin = False else: is_palin = False return s[start:end + 1]
359b62716f35e25db41cafbb4132e92b5bb2c8e0
qmshan/DataEngineering_Challenge
/src/process_log.py
12,599
3.65625
4
from sys import argv import heapq import time import datetime from collections import deque from sets import Set import sys """ log class is used to store log information after string parsing """ class log(object): def __init__(self, IP, time, stamp, resource, status, size, line): self.IP = IP self.time = time self.stamp = stamp self.resource = resource self.status = status self.size = size self.line = line #For debug print out only def print_out(self): print "------------------------NEW LINE------------------------------------" print self.IP print self.time print self.stamp print self.resource print self.status print self.size print self.line return """ The function to transform time string into actual seconds """ def timeTrans(t): monthMap = {"Jan":"01", "Feb": "02", "Mar": "03", "Apr":"04", "May":"05", "Jun":"06", "Jul":"07", "Aug":"08", "Sep":"09", "Oct":"10", "Nov": "11", "Dec": "12"} t = t[:3] + monthMap[t[3:6]] + t[6:20] return int(time.mktime(time.strptime(t, '%d/%m/%Y:%H:%M:%S'))) """ The function to transform actual seconds into time string """ def timeReverse(stamp): monthReverse = {"01":"Jan", "02":"Feb", "03":"Mar", "04":"Apr", "05":"May", "06":"Jun", "07":"Jul", "08":"Aug", "09":"Seq", "10":"Oct", "11":"Nov", "12":"Dec"} time_str = datetime.datetime.fromtimestamp(stamp).strftime('%d/%m/%Y:%H:%M:%S') return time_str[:3] + monthReverse[time_str[3:5]] + time_str[5:19] + " -0400" """ The function to parse a single line log into program specified structure Many corner cases included, as parsing failure may occur if a log line is not irregular . """ def parse(line): if not checkValid(line): return None visit = line.split(" - - ") if len(visit) < 2: return None IP = visit[0] info = visit[1].split("\"") if len(info) < 3: return None tmp = info[0].strip() if (not len(tmp)): return None time = tmp.strip('[]') stamp =timeTrans(time) tmp = info[1].split(" ") if len(tmp) < 2: return None resource = tmp[1] tmp = info[2].strip() if (not len(tmp)): return None ss= tmp.split(" ") if len(ss) < 2: return None if not len(ss[0]) or not len(ss[1]): return None s, size= ss[0].strip(),ss[1].strip() if (size == "-"): size = 0 else: size = int(size) if s == "401": status = False else: status = True item = log(IP, time, stamp, resource, status, size, line) return item """ The function to check if the current input log line is valid """ def checkValid(line): ndash = line.count(" - - ") nlb = line.count('[') nrb = line.count(']') nq = line.count('\"') return ndash == 1 and nlb == 1 and nrb == 1 and nq == 2 """ Feature 1: List in descending order the top 10 most active hosts/IP addresses that have accessed the site. """ class TopIP(object): def __init__(self, fname): self.fname = fname self.dict = {} # hash is used to store the visit time of each ip return def getItem(self, item): ip = item.IP; if ip in self.dict: self.dict[ip] += 1 else: self.dict[ip] = 1 return def output(self): heap = [] heapq.heapify(heap) #priority Q is used to store in the ip with the most visit time. topIpList = [] for ip, count in self.dict.items(): if len(heap) < 10: heapq.heappush(heap, (count, ip)) else: if count >= heap[0][0]: #if visit time the ip >= the smallest of the current top 10 ip heapq.heappop(heap) heapq.heappush(heap, (count, ip)) #replace the smallest with the current ip while heap: # write current heap result into an array in ascending order count, ip = heapq.heappop(heap) topIpList.append(ip + "," + str(count)) f = open(self.fname, 'w') while topIpList: #write to file in descending order currline = topIpList.pop() f.write(currline + "\n") f.close() return """ Feature 2: Identify the top 10 resources on the site that consume the most bandwidth. The feature works in a very similar way with the the first feature. """ class TopResource(object): def __init__(self, fname): self.fname = fname self.dict = {} return def getItem(self, item): res = item.resource; nbytes = item.size if res in self.dict: self.dict[res] += nbytes else: self.dict[res] = nbytes return def output(self): heap = [] heapq.heapify(heap) topList = [] for res, count in self.dict.items(): if len(heap) < 10: heapq.heappush(heap, (count, res)) else: if count >= heap[0][0]: heapq.heappop(heap) heapq.heappush(heap, (count, res)) while heap: count, res = heapq.heappop(heap) topList.append(res) f = open(self.fname, 'w') while topList: currline = topList.pop() f.write(currline + "\n") f.close() return """ Feature 3: Get top 10 busiest 60 min time window """ class BusyTime(object): def __init__(self, fname): self.fname = fname self.dq = deque([]) #deque to save {time, count, timstamp} for at most an hour self.heap = [] #heap for top 10 as {count, -tm_sec, timestamp} self.total = 0 # visits within each 60 min window, heapq.heapify(self.heap) def getItem(self, item): tm_str = item.time tm_sec = item.stamp #remove item outside of 3600 sec time window while self.dq and (tm_sec - self.dq[0][0]) >= 3600: if len(self.heap) < 10: heapq.heappush(self.heap, (self.total, -self.dq[0][0], self.dq[0][2])) #negative value to ensure when different window has the same visits time, we can list the time in ascending order else: if self.total > self.heap[0][0]: heapq.heappop(self.heap) heapq.heappush(self.heap, (self.total, -self.dq[0][0], self.dq[0][2])) self.total -= self.dq[0][1] self.dq.popleft() if self.dq and self.dq[-1][0] == tm_sec: t, c, s = self.dq.pop() self.dq.append((t, c + 1, s)) else: while self.dq and self.dq[-1][0]!= tm_sec -1: new_tm = self.dq[-1][0] + 1 new_tm_str = timeReverse(new_tm) self.dq.append((new_tm, 0, new_tm_str)) new_tm, new_tm_str = tm_sec, timeReverse(tm_sec) self.dq.append((new_tm, 1, new_tm_str)) self.total += 1 return def output(self): while self.dq: if len(self.heap) < 10: heapq.heappush(self.heap, (self.total, -self.dq[0][0], self.dq[0][2])) else: if self.total > self.heap[0][0]: heapq.heappop(self.heap) heapq.heappush(self.heap, (self.total, -self.dq[0][0], self.dq[0][2])) self.total -= self.dq[0][1] self.dq.popleft() f = open(self.fname, 'w') topList = [] while self.heap: count, sec, time = heapq.heappop(self.heap) topList.append(time + "," + str(count)) while topList: currline = topList.pop() f.write(currline + "\n") f.close() return """ Feature 4: Detect patterns of three consecutive faileid login attempts over 20 seconds and block all further attempts to reach the site from the same IP address for the next 5 minutes. """ class BlockList(object): def __init__(self, fname): self.f = open(fname, 'w') self.dqBlock = deque([]) self.blockList = {} self.dqFail = deque([]) #<time, hash<ip, cnt_in_this_second> > self.failCounter = {} def getAndOutput(self, item): ip = item.IP line = item.line time = item.stamp sta = item.status if self.checkBlock(ip, time): self.f.write(line) else: if sta: self.FailReset(ip) else: self.UpdateFail(ip, time) return """ 1) Update dqBlock and blocklist by removing items older than 300 secs 2) Check if new ip stays in blocklist """ def checkBlock(self, ip, time): #update current block list and check if ip is in the list while self.dqBlock and time - self.dqBlock[0][0] >= 300: del self.blockList[self.dqBlock[0][1]] self.dqBlock.popleft() return ip in self.blockList """ Update dqFail and failCounter when the coming login is success """ def FailReset(self, ip): #reset the 20s fail count after a successful login if ip not in self.failCounter: return else: del self.failCounter[ip] for i in range(len(self.dqFail)): if ip in self.dqFail[i][1]: del self.dqFail[i][1][ip] return """ Called only when the coming login fails. 1) Update dqFail and failCounter by removing record older than 20 secs 2) Put the coming login into failCounter and dqFail 3) Check if the coming IP has failed 3 times """ def UpdateFail(self, ip, time): #Update dqFail and failCounter by removing items older than 20 sec while self.dqFail and time - self.dqFail[0][0] >= 20: dict = self.dqFail[0][1] for i, c in dict.items(): self.failCounter[i] -= c if self.failCounter[i] == 0: del self.failCounter[i] self.dqFail.popleft() #Set new ip into dqFail and failCounter if self.dqFail and time == self.dqFail[-1][0]: dict = self.dqFail[-1][1] if (ip not in dict): dict[ip] = 1 else: dict[ip] += 1 else: self.dqFail.append((time, {ip : 1})) if (ip not in self.failCounter): self.failCounter[ip] = 1 else: self.failCounter[ip] += 1 #Update blocklist and dqBlock if necessary if 3 == self.failCounter[ip]: self.dqBlock.append((time, ip)) self.blockList[ip] = 1 return def finalize(self): f.close() return """ main program """ input_list = str(sys.argv) print 'argument list', input_list logfile = sys.argv[1]; hostfile = sys.argv[2] resfile = sys.argv[3] hourfile = sys.argv[4] blockfile = sys.argv[5] print 'input file is: ', logfile print 'host file is: ', hostfile print 'resource file is: ', resfile print 'hour file is: ', hourfile print 'block file is: ', blockfile f = open(logfile) #Initialize all features print 'Initial all features...' ti = TopIP(hostfile) tr = TopResource(resfile) bt = BusyTime(hourfile) bl = BlockList(blockfile) print 'Start to process all given logs... ' cnt = 0 for line in f: item = parse(line) if not item: print 'Warning: Invalid log line encountered on line #:', line continue #item.print_out() #For debug printout ti.getItem(item) tr.getItem(item) bt.getItem(item) bl.getAndOutput(item) cnt += 1 if not cnt % 100: print cnt, 'logs has been processed.' print 'Start to output all results... ' ti.output() tr.output() bt.output() bl.finalize() f.close() print 'Program finishes succesfully!'
8d68b252611c68b2ff236d3ebd4ad817ddbf13b5
lujun9972/word_grouping.py
/word_grouping.py
1,190
3.53125
4
import sys from edit_distance import edit_distance def distance(group, s): 'Calulate the average distance between seq S and seqs in GROUP' if not group: return 0 distances = list(edit_distance(s, seq)[0] if seq[0:2] == s[0:2] else 9999 for seq in group) # 前两个字母不同的单词不在一起 return sum(distances) / len(distances) def grouping(groups, s, accuracy=2): 'grouping seq S into one of group in GROUPS' if not groups: groups.append([]) distances = list(distance(group, s) for group in groups) min_distance = min(distances) min_pos = distances.index(min_distance) # print('min_distance=', min_distance, "min_pos=", min_pos) if min_distance <= accuracy: groups[min_pos].append(s) else: groups.append([s]) return groups if __name__ == '__main__': # 1,2个字母组成的单词就不要参活了.... words = (word.strip() for word in sys.stdin if len(word) > 2) words = sorted(words) groups = list() for word in words: grouping(groups, word) groups = sorted(groups, key=len) for group in groups: print(group, end='\n\n')
5dfc0ffe1f36566d3d72c062aeefd5c8dfa49287
saltmania/web-caesar
/helpers.py
939
3.96875
4
def alphabet_position(someChar): alphabet = 'abcdefghijklmnopqrstuvwxyz' position=0 newChar=someChar.lower() position=alphabet.find(newChar) return(position) def giveNewChar(someChar, x): #The only real purpose of this function is to maintain Uppers vs. Lowers. alphabetLOWER = 'abcdefghijklmnopqrstuvwxyz' alphabetUPPER = alphabetLOWER.upper() if (alphabetLOWER.find(someChar)!=-1): newChar=alphabetLOWER[x] else: if (alphabetUPPER.find(someChar)!=-1): newChar=alphabetUPPER[x] else: newChar=someChar return(newChar) def rotate_character(rotChar, x): rotatedChar = '' charAlphaIndex = alphabet_position(rotChar) if (charAlphaIndex<0): rotatedChar= rotChar else: charAlphaIndex = charAlphaIndex + x rotatedChar = giveNewChar(rotChar,charAlphaIndex % 26) return rotatedChar
862d6475a0c66bbcc9e99628162ef58ca7c90cc8
gambxxxx/scripts
/practice-stuff/error_exc.py
298
3.75
4
def exception_handling(): try: for i in ['a','b','c']: print (i**2) print('code weas executed correctly') except: print('Nuh Uh!') finally: print("c'monbruh!") def main(): exception_handling() if __name__ == "__main__": main()
0b3f7be835d17ab358760961d8749b11a903f07a
ranji2612/Algorithms
/sorts/selectionSort.py
243
3.53125
4
def selectionSort(A, printStep = False): l = len(A) for i in range(l-1): k = i for j in range(i+1,l): if A[j] < A[k]: k = j #Swap the min t = A[k] A[k] = A[i] A[i] =t if printStep: print 'Iter '+str(i+1),A return A
4a48b9e2d888dc74eca3482c18dfb503f899a83e
ddavid/supervisely
/plugins/import/watermark-images/supervisely_lib/imaging/color.py
3,421
3.65625
4
# coding: utf-8 import random import colorsys def _validate_color(color): if not isinstance(color, (list, tuple)): raise ValueError('Color has to be list, or tuple') if len(color) != 3: raise ValueError('Color have to contain exactly 3 values: [R, G, B]') for channel in color: if 0 <= channel <= 255: pass else: raise ValueError('Color channel have to be in range [0; 255]') def random_rgb() -> list: """ Generate RGB color with fixed saturation and lightness :return: RGB integer values. """ hsl_color = (random.random(), 0.3, 0.8) rgb_color = colorsys.hls_to_rgb(*hsl_color) return [round(c * 255) for c in rgb_color] def _normalize_color(color): """ Divide all RGB values by 255. :param color: color (RGB tuple of integers) """ return [c / 255. for c in color] def _color_distance(first_color: list, second_color: list) -> float: """ Calculate distance in HLS color space between Hue components of 2 colors :param first_color: first color (RGB tuple of integers) :param second_color: second color (RGB tuple of integers) :return: Euclidean distance between 'first_color' and 'second_color' """ first_color_hls = colorsys.rgb_to_hls(*_normalize_color(first_color)) second_color_hls = colorsys.rgb_to_hls(*_normalize_color(second_color)) hue_distance = min(abs(first_color_hls[0] - second_color_hls[0]), 1 - abs(first_color_hls[0] - second_color_hls[0])) return hue_distance def generate_rgb(exist_colors: list) -> list: """ Generate new color which oppositely by exist colors :param exist_colors: list of existing colors in RGB format. :return: RGB integer values. Example: [80, 255, 0] """ largest_min_distance = 0 best_color = random_rgb() if len(exist_colors) > 0: for _ in range(100): color = random_rgb() current_min_distance = min(_color_distance(color, c) for c in exist_colors) if current_min_distance > largest_min_distance: largest_min_distance = current_min_distance best_color = color _validate_color(best_color) return best_color def rgb2hex(color: list) -> str: """ Convert integer color format to HEX string :param color: RGB integer values. Example: [80, 255, 0] :return: HEX RGB string. Example: "#FF42А4 """ _validate_color(color) return '#' + ''.join('{:02X}'.format(component) for component in color) def _hex2color(hex_value: str) -> list: assert hex_value.startswith('#') return [int(hex_value[i:(i + 2)], 16) for i in range(1, len(hex_value), 2)] def hex2rgb(hex_value: str) -> list: """ Convert HEX RGB string to integer RGB format :param hex_value: HEX RGBA string. Example: "#FF02А4 :return: RGB integer values. Example: [80, 255, 0] """ assert len(hex_value) == 7, "Supported only HEX RGB string format!" color = _hex2color(hex_value) _validate_color(color) return color def _hex2rgba(hex_value: str) -> list: """ Convert HEX RGBA string to integer RGBA format :param hex_value: HEX RGBA string. Example: "#FF02А4CC :return: RGBA integer values. Example: [80, 255, 0, 128] """ assert len(hex_value) == 9, "Supported only HEX RGBA string format!" return _hex2color(hex_value)
7121dd7448252c5bda04f388eef62bb27dfc351f
ganpatparmar/python_practice
/ex10.py
437
3.8125
4
print("i am 6'2\" tall") print('i am 6\'2" tall') tabby_cat = "\ti'am tabbed in" persian_cat = "\tI'm split\n \t on a line:" backlash_cat = "\tI'm \\a\\car" fat_cat = ''' let me make a list: \ooo* Cat Food \t* Fishes \t* Cat tip\n\t* Grass """ ''' print(tabby_cat) print(persian_cat) print(backlash_cat) print(fat_cat) #while True: # for i in ["/","_","|","\\","|",">"]: # print("%s\v"%i)
28000eb1b3ed46449256fb844db76e8e77d03cc7
challeger/leetCode
/初级算法/leetCode_45_有效的括号.py
1,292
3.953125
4
""" day: 2020-08-15 url: https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xnbcaj/ 题目名: 有效的括号 题目描述: 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。 有效字符串需满足: 左括号必须用相同类型的右括号闭合。 左括号必须以正确的顺序闭合。 注意空字符串可被认为是有效字符串。 示例: 输入: '()' 输出: ture 输入: '([)]' 输出: false 输入: '({})' 输出: true 思路: 利用哈希映射,以及辅助栈,每次遍历,若是左边括号,则将对应的右边括号添加到栈中 若是右边括号,则进行pop操作,判断pop出来的括号是否等于当前括号,是则继续,否则返回false """ class Solution: def isValid(self, s: str) -> bool: if len(s) % 2 == 1: return False hashmap = { '(': ')', '[': ']', '{': '}', } result = ['?'] for c in s: if c in hashmap: result.append(hashmap[c]) elif result.pop() != c: return False return len(result) == 1 if __name__ == "__main__": test = '' s = Solution() print(s.isValid(test))
6414adde77a522780a3ccef062feaa6f6fa87cff
forbearing/mypython
/Process/1.2_multiprocessing.py
4,308
3.765625
4
https://blog.csdn.net/brucewong0516/article/details/85776194 1:概述 1:multiprocessing类似于threading模块支持生成进程的包,是Python的标准模块,它既可以 用来编写多进程,也可以用来编写多线程。如果是多线程的话,用 multiprocessing.dummy 即可,用法与 multiprocessing 基本相同 2:由于python使用全局解释器锁(GIL),他会将进程中的线程序列化,也就是多核cpu实际上并 不能达到并行提高速度的目的,而使用多进程则是不受限的,所以实际应用中都是推荐多进程的 3:如果每个子进程执行需要消耗的时间非常短(执行+1操作等),这不必使用多进程, 因为进程的启动关闭也会耗费资源 4:当然使用多进程往往是用来处理CPU密集型(科学计算)的需求,如果是IO密集型 (文件读取,爬虫等)则可以使用多线程去处理。 5:在UNIX平台上,当某个进程终结之后,该进程需要被其父进程调用wait,否则进程成为僵尸 进程(Zombie)。所以,有必要对每个Process对象调用join()方法 (实际上等同于wait)。 对于多线程来说,由于只有一个进程,所以不存在此必要性 6:multiprocessing提供了threading包中没有的IPC(比如Pipe和Queue),效率上更高。应优先 考虑Pipe和Queue,避免使用Lock/Event/Semaphore/Condition等同步方式 (因为它们占据的 不是用户进程的资源) 7:多进程应该避免共享资源。在多线程中,我们可以比较容易地共享资源,比如使用全局变量 或者传递参数。在多进程情况下,由于每个进程有自己独立的内存空间,以上方法并不合适。 此时我们可以通过共享内存和Manager的方法来共享资源。但这样做提高了程序的复杂度, 并因为同步的需要而降低了程序的效率。 2:multiprocessing 常用组建及功能 1:管理进程模块 Process 用于创建进程模块 Pool 用于创建管理进程池 Queue 用于进程通信,资源共享 Value,Array 用于进程通信,资源共享 Pipe 用于管道通信 Manager 用于资源共享 2:同步子进程模块 Condition Event Lock RLock Semaphore === Process 类 class multiprocessing.Process(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None) run() 表示进程运行的方法。可以在子类中重写此方法。标准run() 方法调用传递给对象构造函数 的可调用对象作为目标参数(如果有),分别使用args和kwargs参数中的顺序和关键字参数 start() 进程准备就绪,等待CPU调度 join(timeout) 如果可选参数timeout是None,则该方法将阻塞,直到join()调用其方法的进程终止. 如果timeout是一个正数,它最多会阻塞超时秒 name 进程的名称。该名称是一个字符串,仅用于识别目的 is_active() 返回进程是否存活。从start() 方法返回到子进程终止的那一刻,进程对象仍处于活动状态。 daemon 进程的守护进程标志,一个布尔值。必须在start()调用之前设置,当进程退出时,它会 尝试终止其所有守护进程子进程 pid 返回进程ID。在产生该过程之前,这将是 None。 exitcode 子进程的退出代码。None如果流程尚未终止,这将是。负值-N表示孩子被信号N终止。 from multiprocessing import Process import time import os def info(): print('module name:', __name__) print("parent proccess:", os.getppid()) print('process id:', os.getpid()) def f(name): info() time.sleep(3) print("hello", name) if __name__ == "__main__": p = Process(target=f, args=('hybfkuf',)) # p.daemon = False p.daemon = True print(p.daemon) p.start() p.join() print('name:', p.name) print("is_active:", p.is_alive()) print("exitcode:", p.exitcode)
e03cfa63c699a133d9dff021cbc9e1040973df23
crystalattice/Python_MicroDegree
/function_decorator.py
730
4.375
4
from math import pi def arg_checker(input_func): def wrapper(num): if type(num) != float: raise TypeError("Argument is not a float") elif num <= 0: raise ValueError("Argument is not positive") else: return input_func(num) return wrapper @arg_checker def circle_measures(radius): circumference = 2 * pi * radius area = pi * radius * radius diameter = 2 * radius return diameter, circumference, area if __name__ == "__main__": diameter, circumference, area = circle_measures(6.0) print("The diameter is {diam}. \nThe circumference is {circum}. \nThe area is {area}".format( diam=diameter, circum = circumference, area=area))
da0f3749566f4ecf4a8d3cd6b7d1580e3b92b155
kzl5010/HackerRank-Python
/InsertionSort.py
371
3.828125
4
def insertionSort(ar): key = 0 i = 0 for j in range(1, len(ar)): for i in range(j): if ar[j] < ar[i]: key = ar[j] ar[j] = ar[i] ar[i] = key for x in ar: print (x, end = ' ') print() m = input() ar = [int(i) for i in input().strip().split()] insertionSort(ar)
9f67d565658f49607f2dce62d54d1e6efd102971
Italo-Neves/Python
/Paradigmas_Program/aula01.py
3,679
4.40625
4
""" CEUB - Ciência da Computação - Prof. Barbosa Atalho de teclado: ctlr <d>, duplica linha. ctrl <y>, apaga linha. ctrl </>, comenta linha - Valor default Quando declaramos as variáveis na classe Conta, aprendemos que podemos atribuir um valor padrão para cada uma delas. Então, atribuo um valor padrão ao limite, por exemplo, 1000.0 reais. Implemente: 1- Crie a classe Conta com os atributos numero, nome_cliente, saldo, limite. - Crie os métodos gets e sets. - Crie um objeto da classe Conta passando os dados - Mostre o endereço do objeto conta criado 5- Consulte e mostre os dados da conta 6- Altere o nome do cliente do objeto Conta, teste. - Faça um depósito, teste. 8- Faça um saque, teste. - Faça uma transferência, teste. 10- Consulte um extrato com os dados: nome, número e saldo da conta - Use o método __class__ no objeto cliente - Use o método __class__.__name__ no objeto cliente - Mostre os atributos do objeto cliente com o método __dict__ 14- Mostre os atributos do objeto cliente com o método vars """ class Conta: def __init__(self, numero, nome_cliente, saldo, limite=1000.0): self.numero = numero self.titular = nome_cliente self.saldo = saldo self.limite = limite def get_titular(self): return self.titular def set_titular(self, nome): self.titular = nome def get_saldo(self): return self.saldo def get_numero(self): return self.numero def deposito(self, valor): self.saldo += valor # self.saldo = self.saldo + valor def saque(self, valor): if self.saldo + self.limite < valor: print('Saldo insuficiente.') return False else: self.saldo -= valor print('Saque realizado.') return True def transfere_para(self, destino, valor): retirou = self.saque(valor) if not retirou: # if retirou == False: print('Transferência não realizada') return False else: destino.deposito(valor) print('Transferência realizada com sucesso') return True def extrato(self): # print("Extrato:\nNome: {}, Número: {}, Saldo: {}".format(self.titular, self.numero, self.saldo)) print(f"Extrato:\nNome: {self.titular}, Número: {self.numero}, Saldo: {self.saldo}") if __name__ == '__main__': # mai <tab> conta1 = Conta('123-4', 'João', 1200.0, 1000.0) # Chama o contrutor (__init__) print(conta1) # <conta_agregacao.Conta object at 0x000002B9DBA4AF70> print('Nome:', conta1.get_titular()) # Consulta nome_objeto.nome_metodo() print('Número:', conta1.get_numero()) conta1.set_titular('Ana') # Altera o nome do cliente print('Nome:', conta1.get_titular()) conta1.deposito(200) print('Saldo:', conta1.get_saldo()) conta1.saque(100) print('Saldo:', conta1.get_saldo()) conta2 = Conta('923-4', 'Ailton', 2000.0, 1000.0) # Chama o contrutor (__init__) print(conta1) conta1.transfere_para(conta2, 200) # Transferência da conta1 para a conta2 conta1.transfere_para(conta2, 4000) # Transferência da conta1 para a conta2 conta1.extrato() conta2.extrato() print('Método especiais:') print(conta1.__class__) # <class '__nain__.Conta'> print(conta1.__class__.__name__) # Conta print(conta1.__dict__) # {'numero': '123-4', 'titular': 'Ana', 'saldo': 1100.0, 'limite': 1000.0} print(vars(conta1)) # {'numero': '123-4', 'titular': 'Ana', 'saldo': 1100.0, 'limite': 1000.0}
3553661a4854d98fba76f9caa19025d2e373806d
bhirbec/interview-preparation
/CTCI/2.2.py
1,011
3.78125
4
class Node(): def __init__(self, value, next_node=None): self.value = value self.next_node = next_node def main(): head = Node(12, Node(10, Node(3, Node(1, Node(156, Node(43)))))) print find_kth_from_tail(head, 2) print find_kth_from_tail_runner(head, 2) print find_kth_from_tail(None, 2) print find_kth_from_tail_runner(None, 2) def find_kth_from_tail_runner(n, k): runner = n for _ in xrange(k): if runner is None: return None runner = runner.next_node while runner.next_node: n = n.next_node runner = runner.next_node return n.value def find_kth_from_tail(n, k): def _f(n, k): if n is None: return None, -1 k_node, l = _f(n.next_node, k) if k_node is not None: return k_node, l l += 1 if l == k: return n, l return None, l n, l = _f(n, k) if n is None: return None return n.value main()
9d0a614fb0935e2e5ec4d62fbccafa54c12ecb16
KaylaZhou/PythonStudy
/PPy/海归图库的用法.py
1,985
4
4
#!/usr/bin/python3 import turtle turtle.screensize(400, 400, '#a9758b') # 设置画布宽和高的大小,颜色 turtle.setup(400, 400, 0, 0) # 设置画布窗口宽和高,以及坐标x,y的距离(距屏幕左上角的距离). turtle.speed(1) # 设置画笔移动的速度,(1-10)数字越大,速度越快. turtle.pencolor('#ffaf50') # 设置画笔的颜色 # 画笔运动命令: turtle.pensize(10) # 设置画笔的宽度 turtle.forward(100) # 向当前画笔方向移动distance像素长 turtle.backward(50) # 向当前画笔相反方向移动distance像素长 turtle.right(100) # 顺时针移动 ° turtle.left(150) # 逆时针移动 ° turtle.pendown() # 移动时绘制图形,缺省时也为绘制 turtle.goto(10, 20) # 将画笔移动到坐标为x,y的位置 turtle.penup() # 移动时不绘制图形,提起笔,用于另起一个地方绘制时用 turtle.circle(50) # 画圆,半径为正(负),表示圆心在画笔的左边(右边)画圆 # 画笔控制命令: turtle.fillcolor('red') # 绘制图形的填充颜色(箭头内部颜色) turtle.color('red', '#72538e') # 同时设置箭头颜色pencolor=color1, fillcolor=color2 turtle.filling() # 返回当前是否在填充状态(无参数) turtle.begin_fill() # 准备开始填充图形(无参数) turtle.end_fill() # 填充完成 turtle.showturtle() # *与hideturtle()函数对应* turtle.hideturtle() # 隐藏箭头显示 # 全局控制命令 turtle.clear() # 清空turtle窗口,但是turtle的位置和状态不会改变 turtle.reset() # 清空窗口,重置turtle状态为起始状态 turtle.undo() # 撤销上一个turtle动作(注:无法撤销reset,clear) turtle.isvisible() # 返回当前turtle是否可见 # turtle.stamp() # 复制当前图 # 三角形 (steps (optional) (做半径为radius的圆的内切正多边形,多边形边数为steps)) turtle.circle(80, steps=30) turtle.circle(20, 80) # 半圆 turtle.done() # python -m pip install --upgrade pip'pip升级命令'
0e2d658ab423943a077af23369eb8d007e91dfb8
judacribz/python_repo
/csci_3070u/ass/A2/part2.py
2,707
3.6875
4
from util import * # ============================================================================= # Constants # ============================================================================= RAND_MAX = 1000000 NUM_VALUES = 10 # ============================================================================= # Radix Sort Functions # ============================================================================= # Gets an array of single digits at the digit index of each number in the # provided array def get_digit_arr(arr, digit_index): digitArray = [] for num in arr: digitArray.append((num//10**(digit_index-1))%10) return digitArray # Gets a random array of n numbers between 0(inclusive) and rand_max(exclusive) def get_rand_arr(n, rand_max): randArray = np.random.randint(0, rand_max, n) return randArray # Performs counting sort on the array by using its provided single digit array def count_sort(digitArray, arr): digitList = list(digitArray) uniqueList = list(set(digitArray)) # creates an list of occurrences of each number in digitArray c0 = [] for num in uniqueList: c0.append(digitList.count(num)) # creates a list of cumulative occurences based on c0 c1 = [i for i in np.cumsum(c0)] # Inserts arr values based on c1 values used as its indexes # Next, decrements c1 at that index to place repeated values in the index # before b = np.zeros(len(arr), int) for i in range(len(digitArray)-1, -1, -1): ind = uniqueList.index(digitArray[i]) b[c1[ind]-1] = arr[i] c1[ind] -= 1 return b[:] def radix_sort(arr): digitArrayMax = -1 i = 1 # get array of digits at index i digitArray = get_digit_arr(arr, i) while digitArrayMax != 0: arr = count_sort(digitArray, arr[:]) i += 1 digitArray = get_digit_arr(arr, i) digitArrayMax = np.amax(digitArray) return arr # ============================================================================= # Main # ============================================================================= if __name__ == "__main__": print_title("Radix Sort") num_values = NUM_VALUES usage = "Usage: python part2.py <num_values>(optional)" num_args, error = check_args(1, usage) if num_args == 1: num_values = int(sys.argv[1]) if num_values < 1: print "Error: Number of values must be > 0" error = True if error: sys.exit(0) arr = get_rand_arr(num_values, RAND_MAX) print "Array before radix_sort:" print arr arr = radix_sort(arr) print "\nArray after radix_sort:" print arr print ""
784773db84f4abcd40217530d82f4e5fb2b40b34
daniel-reich/turbo-robot
/jWHkKc2pYmgobRL8R_14.py
816
4.21875
4
""" Write a function that takes in a string and for each character, returns the distance to the nearest vowel in the string. If the character is a vowel itself, return `0`. ### Examples distance_to_nearest_vowel("aaaaa") ➞ [0, 0, 0, 0, 0] distance_to_nearest_vowel("babbb") ➞ [1, 0, 1, 2, 3] distance_to_nearest_vowel("abcdabcd") ➞ [0, 1, 2, 1, 0, 1, 2, 3] distance_to_nearest_vowel("shopper") ➞ [2, 1, 0, 1, 1, 0, 1] ### Notes * All input strings will contain **at least one vowel**. * Strings will be lowercased. * Vowels are: `a, e, i, o, u`. """ def distance_to_nearest_vowel(txt): out, lst =[],[i for i in range(len(txt)) if txt[i].lower() in ['a','e','i','o','u']] for i in range (len(txt)): out.append(min([abs(i-j) for j in lst])) return out
c6c115f2e6a2c1123d0372dd111c6d5cc86e2476
peteryanggy/python
/VariableType.py
2,714
3.546875
4
# -*- coding: UTF-8 -*- ''' 数据类型转换 ''' #数据类型转换 print('int') print(int('64', 16)) print(int('64', 10)) print(int('64', 8)) print('\nlong') print(long('64', 16)) print(long('64', 10)) print(long('64', 8)) print('\nfloat') print(float('64.5997')) print('\ncomplex') print(complex(1, 56.597)) listvar = [1, 2, 3, 4, 5] dictvar = {'one': 1, 'two': 2, 'three': 3} print('\nstr') #将对象 x 转换为字符串 print(str(64.2365)) print(str(listvar)) #相当于toString print('\nrepr') #将对象 x 转换为表达式字符串 print(repr(listvar)) print(repr(dictvar)) print('\nset 函数创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等。') sx = set('runoob') sy = set('google') print(sx) print(sy) print('交集'), print(sx & sy) print('并集'), print(sx | sy) print('差集'), print(sx - sy) print(sy - sx) print('\ndict') print(dict()) #创建空字典 print(dict(a='a', b='b', t='t')) #传入关键字 print(dict(zip(['one', 'two', 'three'], [1, 2, 3]))) #映射函数方法来构造字典 print(dict([('one', 1), ('two', 2), ('three', 3)])) #可迭代对象方法来构造字典 print('\ntuple') print(tuple([1, 2, 3, 4])) print(tuple({1:2, 3: 4})) #针对字典 会返回字典的key组成的tuple print((1, 2, 3, 4)) #元组会返回元组自身 print(tuple([123, 'xyz', 'tuple', 3.14])) print('\nlist') print(list((123, 'xyz', 'hello', 32))) print(list({'one': 1, 'two': 2})) #针对字典 会返回字典的key组成的list print('\neval') ex = 10 print(eval('3 * ex')) print(eval('pow(2, 3)')) print(eval('2 + 2')) print('\nfrozenset') a = frozenset(range(10)) print(a) b = frozenset('runoob') print(b) c = [123, 'xyz', 32] print(frozenset(c)) print('\nchr 用一个范围在 range(256)内的(就是0~255)整数作参数,返回一个对应的字符。') print(chr(0x30)), print(chr(0x31)), print(chr(0x61)) print(chr(48)), print(chr(49)), print(chr(97)) print('\nunichr') print(unichr(0x31)) print(unichr(97)) print('\nord 函数是 chr() 函数(对于8位的ASCII字符串)或 unichr() 函数(对于Unicode对象)的配对函数,' '它以一个字符(长度为1的字符串)作为参数,返回对应的 ASCII 数值,或者 Unicode 数值,如果所给的 Unicode ' '字符超出了你的 Python 定义范围,则会引发一个 TypeError 的异常。') print(ord('1')) print(ord('a')) print('\nhex 将一个整数转换为一个十六进制字符串') print(hex(255)) print(hex(0x12)) print(type(hex(100))) print('\noct 将一个整数转换成8进制字符串') print(oct(255)) print(oct(0x12)) print(oct(12))
b3b02871392b88dc429f4eae7750de3d00a34577
edbeeching/ProjectEuler
/Problem_023.py
1,997
3.890625
4
# -*- coding: utf-8 -*- """ Created on Sat Oct 28 17:13:56 2017 @author: Edward A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number. A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n. As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit. Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers. """ import math def get_divisors(num): divs = set() for i in range(1,int(math.sqrt(num))+1): if num % i == 0: divs.add(i) divs.add(num//i) return sorted(list(divs)) abundant_nums = set() for n in range(2, 28124): divs = get_divisors(n)[:-1] if sum(divs) > n: abundant_nums.add(n) abundant_nums_list = list(abundant_nums) total = 0 for n in range(1,28124): not_abundant = True for num in abundant_nums_list: if n - num in abundant_nums: not_abundant = False continue if not_abundant: total += n print(total)
d48524b4056e1263df3698a979ef064742cf8262
BronzeCrab/remont_task
/remont_task.py
1,402
3.65625
4
import requests as rq import json from math import sin, cos, sqrt, atan2, radians PARIS_LONG = 2.350987 PARIS_LAT = 48.856667 DISTANCE_FROM_PARIS_KM = 450 API_URL = "https://opensky-network.org/api/states/all" def calc_distance(lat1, lon1, lat2, lon2): """ https://stackoverflow.com/questions/19412462/getting-distance-between-two-points-based-on-latitude-longitude#answer-19412565 """ # approximate radius of earth in km R = 6371.0 lat1 = radians(lat1) lon1 = radians(lon1) lat2 = radians(lat2) lon2 = radians(lon2) dlon = lon2 - lon1 dlat = lat2 - lat1 a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2 c = 2 * atan2(sqrt(a), sqrt(1 - a)) return R * c def get_all_planes(): resp = rq.get(API_URL) if resp.status_code == 200: try: resp = json.loads(resp.text) return resp['states'] except Exception as e: return 'Error: {0}'.format(e) else: return 'Error with api' def main(): planes = get_all_planes() if type(planes) is list: return [plane for plane in planes if len(plane) >= 7 and type(plane[6]) is float and type(plane[5]) if float and calc_distance(PARIS_LAT, PARIS_LONG, plane[6], plane[5]) <= DISTANCE_FROM_PARIS_KM] return planes if __name__ == '__main__': main()
973b01333d9fb23e51d7385523e2b444e475a483
SJMagaziner/5-Card_Poker_Hand_Simulator_and_Visualizer
/Program_components/Main_program.py
2,664
3.890625
4
#%% MAIN PROGRAM: Auto hand-drawer, visualizer, and data compiler. # Enter the number of hands you desire to generate how_many_hands = 5 # Do you want images to appear for each hand (if yes, input 1, if false input 0? #### TOO MANY HAND IMAGES BEING GENERATED WILL SLOW DOWN YOUR COMPUTER GREATLY make_images_appear = True # Generates empty pandas dataframe onto which we will append info from each hand poker_hands_df = pd.DataFrame() # Hand counter hand_counter = 0 # Current time: StartTime = datetime.datetime.now() for i in range(how_many_hands): # Notifies which hand the player is currently on hand_counter = hand_counter + 1 print('This is hand #' + str(hand_counter)) # This draws one's unique 5-card hand and sorts it, grouping like cards random_hand = draw_a_hand() sorted_hand = sorted(random_hand) print(sorted_hand) # Pulls hand values and suits for use in rank checking, see function documentation for detailed explanation hs = check_hand_values_and_suits()[0] hv = check_hand_values_and_suits()[1] # Defines hand ranks; see function documentation for detailed explanation hand_rank = what_is_the_hand_rank() print(hand_rank) # Creates a time stamp for each hand iteration current_time = datetime.datetime.now() time_diff = current_time - StartTime print(time_diff) # This generates a pandas dataframe for the most recent hand drawn add_hand = pd.DataFrame({'Hand Rank': hand_rank, 'Card 1': sorted_hand[0], 'Card 2': sorted_hand[1], 'Card 3': sorted_hand[2], 'Card 4': sorted_hand[3], 'Card 5': sorted_hand[4], 'Time to completion': str(time_diff)}) # This will append the most recently drawn hand to the empty/existing pandas dataframe poker_hands_df = poker_hands_df.append(add_hand) # This argument will return an image for each hand drawn (if noted by player) # It can be used to stitch any images together, just change pathways and names of the function # See function documentation for more information if make_images_appear == 1: make_poker_hand_images() # Lastly, this will store the dataframe as an excel sheet entitled 'Poker Statistics' # While the variable poker_hands_df will be the appropriate, complete dataframe, this ensures the data is saved if how_many_hands == hand_counter: with pd.ExcelWriter('Data/Poker Hand Statistics.xlsx') as writer: poker_hands_df.to_excel(writer, sheet_name='Sheet1') print(poker_hands_df)
3396ff3192f3a30a0e7d7e0218a5abda2e7bb375
Aaron44201/Selection
/Task 4 class excersises.py
314
3.9375
4
#Aaron Bentley #30/09/2014 #dev ex 4 grade = int(input("Test score out of 100: ")) if grade >= 81: print("Grade A") elif grade >= 71: print("Grade B") elif grade >= 61: print("Grade C") elif grade >= 51: print("Grade D") elif grade >= 41: print("Grade E") else: print("Grade U")
5c07eeb88e213c6712e7fdc6b42853ab45527290
minwoo2305/minwoo_Git
/Weight_optimize_using_genetic_algorithm/Genetic_Algorithm.py
3,615
3.640625
4
import numpy as np import random class genetic_algorithm(): def __init__(self, init_chromosome_list, num_of_population=10, extend_range=0.01): self.chromosomes = init_chromosome_list self.number_of_population = num_of_population self.extend_range = extend_range self.population_list = [] def make_population(self): for i in range(self.number_of_population): temp = [] for chromosome in self.chromosomes: shape_of_chromosome = np.shape(chromosome) population = np.random.uniform(low=-0.01, high=0.01, size=len(np.reshape(chromosome, (-1)))) population = np.reshape(population, (shape_of_chromosome[0], shape_of_chromosome[1])) temp.append(population) temp.append([0]) self.population_list.append(temp) return self.population_list def set_fitness(self, index, fitness): self.population_list[index][-1] = fitness def extend_line_crossover(self, x, y): if x <= y: return random.uniform(x-self.extend_range, y+self.extend_range) else: return random.uniform(y-self.extend_range, x+self.extend_range) def generation(self, num_of_replacement): self.population_list = sorted(self.population_list, key=lambda x: x[-1], reverse=True) print("Best Accuracy : " + str(self.population_list[0][-1])) best_population = self.population_list[0] offspring_set = [] for num in range(num_of_replacement): selected_population = self.selection() offspring = self.crossover(selected_population) offspring_set.append(offspring) self.replacement(offspring_set) return self.population_list, best_population def crossover(self, selected_list): offspring_list = [] for i in range(len(selected_list[0]) - 1): list_shape = np.shape(selected_list[0][i]) parent1 = np.reshape(selected_list[0][i], (-1)) parent2 = np.reshape(selected_list[1][i], (-1)) offspring = [] for ele_index in range(len(parent1)): offspring_element = self.extend_line_crossover(parent1[ele_index], parent2[ele_index]) offspring.append(offspring_element) offspring = np.reshape(offspring, (list_shape[0], list_shape[1])) offspring_list.append(offspring) offspring_list.append([0]) return offspring_list def mutation(self, offspring=[]): random_element = random.choice(offspring[:-1]) offspring[offspring.index(random_element)] = random_element + np.random.normal() return offspring def selection(self): sum_of_fitness = 0 for fitness in self.population_list: sum_of_fitness += fitness[-1] selection_list = [] for count in range(2): sum = 0 point = np.random.uniform(0, sum_of_fitness) for choice in enumerate(self.population_list): sum += choice[1][-1] if point < sum: selection_list.append(self.population_list[choice[0]]) break return selection_list def replacement(self, selection_list): for i in range(len(selection_list)): self.population_list[-(i+1)] = selection_list[-(i+1)] def test_print(self): for i in self.population_list: print(i[-1])
d222c22c204fb728b8c3afdf909e11cb055f9ce8
rebahozkoc/To_learn2
/quiz5-2.py
390
3.625
4
import sys def diamond_comprehension(x): for i in range(1, x+1): temp_list = [" " for m in range(x-i)] + ["*" for n in range(2*i-1)] print(temp_list) print("".join(temp_list)) for k in range(x-1, 0, -1): temp_list = [" " for p in range(x-k)] + ["*" for o in range(2*k-1)] print("".join(temp_list)) diamond_comprehension(int(sys.argv[1]))
e27199d30e9ddb40e2fd7534df36bf98fa7a1a14
Lubright/training-python
/Function/ex3_star_function_kwargs.py
673
3.796875
4
# 使用 ** 建立可變參數函式 def formMolecules(**kwargs): if len(kwargs) == 2 and kwargs["hydrogen"] == 2 and kwargs["oxygen"] == 1: return "water" elif len(kwargs) == 1 and kwargs["unobtanium"] == 12: return "aether" print(formMolecules(hydrogen=2, oxygen=1)) print(formMolecules(unobtanium=12)) print(formMolecules(**{ "hydrogen": 2, "oxygen": 1 })) # 使用 * 和 ** 建立包裝函式 def printLower(*args, **kwargs): args = list(args) # 讓他為list for i, s in enumerate(args): args[i] = str(s).lower() print(*args, **kwargs) name = "Amy" printLower("Hello,", name) printLower(*list("ABC"), sep=", ")
1053521ce30551b0831ecf3548242ad18a689f9e
brewersey/dsp
/python/q8_parsing.py
881
4.09375
4
# The football.csv file contains the results from the English Premier League. # The columns labeled ‘Goals’ and ‘Goals Allowed’ contain the total number of # goals scored for and against each team in that season (so Arsenal scored 79 goals # against opponents, and had 36 goals scored against them). Write a program to read the file, # then print the name of the team with the smallest difference in ‘for’ and ‘against’ goals. player = [100000,1] winner = 'Quakes' with open('football.csv', 'r') as f: header = f.readline() header = header.split(',') print(header) for line in f: line = line.split(',') a = int(line[6]) b = int(line[7]) print(line) if abs(a - b) < abs(player[0] - player[1]): winner = line[0] player[0] = a player[1] = b print(winner)
a6fa7da843440683cbc34f8c97aa7834e8566c85
rajgopav/Algorithms
/DynamicProgramming/Equal.py
2,090
3.546875
4
# Importing standard libraries import sys # Parsing functions def parseInt(stream): return int(stream.readline().rstrip()) def parseIntArr(stream): return [int(x) for x in stream.readline().rstrip().split()] ''' Function that returns the total number of minimum operations required. This has three conceptual aspects. 1. Adding choclates to everyone else except one by a number N is equal to subtracting choclates from that one person by N. This is because we only are concerned with OPERATIONS for equalizing number of choclates of everybody. 2. There is an optimum minimum level.(minimum number of chochlates). This can be either the min of the entire numbers of choclates with peo -ple initially, or anything in range [fMin, fMin - 5]. It can't go bey -onod that because it will always require an extra operation since the max greedy reaching way(subtraction amount of choclates) is 5. 3. for any level between fMin to fMin - 5, we make each person reach there by subtracting choclates in a greedy way. Say if the chocs ini -tially are k, we reach by k/5 + (k%5)/2 + (k%5)%2 . We compute such steps for all people are compute total number of operations in this way. FINALLY, we do this for the range fMin to fMin - 5 and compute the min of this and return this as the answer. ''' def getMinOper(NArr): NArr.sort() minVal = NArr[0] results = [] for val in range(minVal - 5, minVal + 1): results.append(getMin(NArr,val)) return min(results) def getMin(A,minVal): count = 0 for k in A: count += getOperGreedy(k,minVal) return count def getOperGreedy(k,minVal): k = k - minVal opers = 0 opers += k/5 opers += (k%5)/2 opers += (k%5)%2 return opers # Main function for the program if __name__ == "__main__": stream = sys.stdin T = parseInt(stream) for i in range(T): N = parseInt(stream) NArr = parseIntArr(stream) NMinOper = getMinOper(NArr) result = NMinOper print result
d7642ac4fb38d4f31e37fb8fcfd1334f2d995266
christian-miljkovic/interview
/Leetcode/Algorithms/Medium/Arrays/MinimumDominoRotations.py
1,963
4.46875
4
""" In a row of dominoes, A[i] and B[i] represent the top and bottom halves of the i-th domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.) We may rotate the i-th domino, so that A[i] and B[i] swap values. Return the minimum number of rotations so that all the values in A are the same, or all the values in B are the same. If it cannot be done, return -1. Example 1: Input: A = [2,1,2,4,2,2], B = [5,2,6,2,3,2] Output: 2 Explanation: The first figure represents the dominoes as given by A and B: before we do any rotations. If we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure. Example 2: Input: A = [3,5,1,2,3], B = [3,6,3,3,4] Output: -1 Explanation: In this case, it is not possible to rotate the dominoes to make one row of values equal. Note: 1 <= A[i], B[i] <= 6 2 <= A.length == B.length <= 20000 """ # Time Complexity: O(n) where n is the length of the lists # Space Complexity: O(1) class Solution: def minDominoRotations(self, A: List[int], B: List[int]) -> int: swap_a = check_one_row(A,B) swap_b = check_one_row(B,A) if swap_a == swap_b and swap_a == -1: return -1 elif swap_a == -1: return swap_b elif swap_b == -1: return swap_a else: return min(swap_a, swap_b) def check_one_row(A,B): min_swaps = float('inf') is_filled = False for num in range(1,7): curr_swaps = 0 correct_nums = 0 for i in range(len(A)): if A[i] != num and B[i] == num: curr_swaps += 1 correct_nums += 1 elif A[i] == num: correct_nums += 1 if correct_nums == len(A): min_swaps = min(min_swaps, curr_swaps) is_filled = True if is_filled: return min_swaps return -1
d704ac06646836bafa4203d67f3522e3f4748eb4
riderswhocode/streamlit_opencv
/main.py
1,808
3.625
4
import cv2 import numpy as np import streamlit as st st.title('OpenCV Thresholding') st.write(""" Adding threshold to images to further simplify visual data analysis. """) st.sidebar.header('User Input Features') uploaded_img = st.sidebar.file_uploader("Upload your image", type=["png","jpg","jpeg"]) #file_name = cv2.imread(st.sidebar.text_input("Copy the uploaded filename and location")) isGray = st.sidebar.checkbox('Convert to Grayscale') if uploaded_img is not None: file_bytes = np.asarray(bytearray(uploaded_img.read()), dtype=np.uint8) opencv_img = cv2.imdecode(file_bytes,1) #cv2.imwrite('input.jpg', cv2.resize(uploaded_img, (50,50), interpolation=cv2.INTER_LINEAR)) #test_img = cv2.imread('input.jpg') if isGray: new_img = cv2.cvtColor(opencv_img, cv2.COLOR_BGR2GRAY) thresh_type = st.sidebar.selectbox('Threshold Type',('Ordinary','Adaptive Threshold')) if thresh_type == 'Ordinary': thresh_value = st.sidebar.slider('Threshold Value', 1, 255, 12) retval, data = cv2.threshold(new_img, thresh_value, 255, cv2.THRESH_BINARY) else: block_size = st.sidebar.slider('Block Size', 3, 255, 115, 2) data = cv2.adaptiveThreshold(new_img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, block_size, 1) else: new_img = opencv_img thresh_value = st.sidebar.slider('Threshold Value', 1, 255, 12) retval, data = cv2.threshold(new_img, thresh_value, 255, cv2.THRESH_BINARY) st.subheader('Original Image') st.image(new_img, caption='Input Image', use_column_width=True) cv2.imwrite('output.jpg',data) st.subheader('Output Image') st.image('output.jpg', caption='Ouput Image', use_column_width=True)
29fd25304e8cd43d16019a837d8512fb61bdf3f6
shivam-agarwal-17/Udacity-Nanodegree-Data-Structures-and-Algorithms
/Projects/P1/problem_3_HuffmanCoding.py
4,864
3.6875
4
import sys from heapq import heappush, heappop class Node: def __init__(self, freq=0, letter=None): self.freq = freq self.letter = letter self.left = None self.right = None self.parent = None def increment_freq(self): self.freq += 1 def is_leaf(self): return self.left is None and self.right is None def __repr__(self): return f"Node({self.freq}, {self.letter})" def __gt__(self, node): return self.freq > node.freq @classmethod def merge(cls, node_1, node_2): parent_node = cls(freq = (node_1.freq + node_2.freq)) parent_node.left = node_1 parent_node.right = node_2 node_1.parent = parent_node node_2.parent = parent_node return parent_node class HuffmanTree: def __init__(self): self.root = None self.char_to_node = dict() def _compute_char_freq(self, data): """ compute frequencies of characters found in the data """ for char in data: if char not in self.char_to_node: self.char_to_node[char] = Node(freq = 1, letter = char) else: self.char_to_node[char].increment_freq() def _build_tree(self): """ build the Huffman tree """ # add nodes to min-heap h = [] for _, node in self.char_to_node.items(): heappush(h, node) # build huffman tree while len(h) > 1: node_1 = heappop(h) node_2 = heappop(h) new_node = Node.merge(node_1, node_2) heappush(h, new_node) # get root of Huffman Tree self.root = heappop(h) def encode(self, data): """ Perform Huffman encoding on data Args: data(str): data to be Huffman encoded Returns: String of 0s and 1s denoting Huffman encoding of data """ # compute character frequencies and initialize nodes of the tree self._compute_char_freq(data) # building the huffman tree self._build_tree() # encode data encoded_data = "" if self.root.is_leaf(): # edge case: if root is also the character node, that is, only one node present in huffman tree for char in data: encoded_data += "0" return encoded_data for char in data: current_node = self.char_to_node[char] code = "" while current_node.parent is not None: if current_node == current_node.parent.left: code += "0" else: code += "1" current_node = current_node.parent encoded_data += code[::-1] return encoded_data def decode(self, data): """ Perform Huffman decoding on data Args: data(str): data to be Huffman decoded Returns: decoded string """ current_node = self.root decoded_data = "" if self.root.is_leaf(): # edge case: if root is also the character node, that is, only one node present in huffman tree for char in data: decoded_data += self.root.letter return decoded_data for char in data: if char == '0': current_node = current_node.left else: current_node = current_node.right if current_node.is_leaf(): decoded_data += current_node.letter current_node = self.root return decoded_data def test_Huffman_coding(test_case_num, input_string, test_case_str): print(f"\nTest case {test_case_num}: {test_case_str}\n") HT = HuffmanTree() encoded_data = HT.encode(input_string) decoded_data = HT.decode(encoded_data) print ("The size of the data is: {}\n".format(sys.getsizeof(input_string))) print ("The content of the data is: {}\n".format(input_string)) print ("The size of the encoded data is: {}\n".format(sys.getsizeof(int(encoded_data, base=2)))) print ("The content of the encoded data is: {}\n".format(encoded_data)) print ("The size of the decoded data is: {}\n".format(sys.getsizeof(decoded_data))) print ("The content of the encoded data is: {}\n".format(decoded_data)) if __name__ == "__main__": test_inputs = [("aaabbbbccd", "Input string has characters of varying frequencies"), \ ("aabbccdd", "Input string has characters of equal frequencies"), \ ("zzzzzzz", "Only one character present in input string")] for idx, test_case in enumerate(test_inputs): test_Huffman_coding(idx+1, test_case[0], test_case[1])
51cadc47f14714ba709577739b9785f1375c212b
Frank-en-stein/DataShall
/4.py
1,203
3.6875
4
Text = "Dude!!!! And I thought I knew a lotttt. Phewwwww!\ I won’t back down. At least I understand now Daaata Science \ is much more than what we are taught in MOOOCs. That is allllright. \ I won’t get demotivated. I’ll work harder and in noooo time, I’ll \ get better & be backkk next time." result = [Text[0], Text[1]] for i in range(2, len(Text)): if Text[i] == Text[i-1] and Text[i] == Text[i-2]: continue result.append(Text[i]) result = ''.join(result) print(result) #complexity analysis line by line: #7 > list initialization: Constant complexity, O(1) #8-11 > loop N = Length of string "Text" - 2 times: # 9,11 contains conditional check performed in constant complecity, O(1) # 11 contains list append operation which is also constant time operation, O(1) # So, 8-11 has a complexity of O(1) * (N-2) = O(N-2) approximately, O(N) #12 > joining N element list into a string performed in linear time O(N) #13 > printing N element string in linear time, O(N) #-------------------------------------------------------------------------------------- #TOTAL = O(1) + O(N) + O(N) + O(N) = O(1) + 3*O(N) #Ignoring contants, Approximately, O(N)
1d469389efddafcbd0ba208f285c6c973f39bc27
mash716/Python
/base/slice/slice0004.py
240
3.640625
4
# 開始位置と終了位置を指定することで範囲内の要素を取得することができます # 開始位置:0~4 # 終了位置:1~5 test_list = ['https','www','python','izm','com'] print(test_list[3:5])
b8db3e492e3e303851f3a6236099bcc45e5bce5b
krolmarcin/PythonLearn001
/Lessons/lesson17.py
518
3.703125
4
lista = list(range(10)) nowa = [i * 2 for i in lista] nowa2 = [i + 2 for i in lista if i % 2 == 0] #dodawanie działa po sprawdzeniu ifa: nowa3 = [i + 1 for i in lista if i % 2 == 0] print(lista) print("Nowa lista, arg * 2:", nowa) print("Nowa2:", nowa2) print("Nowa3 (nieparzyste bo dodawanie działa po sprawdzeniu if:\n", nowa3) #Formatowanie ciągów String argumenty = ["Marcin", 39] tekst = "Czesc mam na imię {imie} i mam {wiek} lat. \n{imie}.".format(imie = argumenty[0], wiek = argumenty[1]) print(tekst)
4aa7c6a3d8267169c26e61d72fd6b6e819d26a6f
desenvolvefacil/SSC0800-2019-02-Introducao-a-Ciencia-de-Computao-I
/SSC0800 (2019-02) - Introdução à Ciência de Computação I/EX 002 - Lista 1 - Dados e Expressões - Operações Aritméticas.py
594
3.828125
4
''' Escreva um programa em pn2thon para realizar adição, subtração, multiplicação , divisão e modulo de dois números. Input: 12, 5 Ouput: A soma dos números dados é : 17 A subtração dos números dados é : 7 O multiplicação dos números dados é : 60 A divisão dos números dados é : 2.400000 O modulo é = 2 ''' #le os valores inteiros n1, n2 = map(int,input().split(" ")) #Soma print("x+y =",(n1 + n2)) #Subtração print("x-y =" ,(n1 - n2)) #Multiplicação print("x.y =" ,(n1 * n2)) #Divisão print("x/y =", round(n1 / n2,6)) #Modulo print("x mod y =",(n1 % n2))
dacc3d740aafc3b9b803d2737721fa4d46ccb909
poojasgada/codechefsolns
/Practice-Easy/Easy-AMMEAT2.py
1,106
3.546875
4
''' Created on Jul 3, 2013 @author: psgada ''' import sys from math import floor #Ha, we dont really need to find primes def primes_sieve_way(n): prime_dict = {} for i in range(2, n+1): prime_dict[i] = True for i in range(2, n+1): for j in range(i+i, n+1, i): prime_dict[j] = False #print prime_dict count = 0 for i in prime_dict.keys(): if prime_dict[i] == True: count += 1 return count def get_input(): num_cases = int(sys.stdin.readline().strip()) for i in range(0, num_cases): num_list = map(int, sys.stdin.readline().strip().split()) if num_list[1] == 1: print 1 continue if num_list[1] > floor(num_list[0]/2): print -1 continue init_val = 2 for i in range(0, num_list[1] -1): print init_val, init_val += 2 print init_val get_input()
8be0c3e4a2699ddf77ba405ee17baca05ae7475e
AbhinavPelapudi/leetcode_problems
/Facebook/linked_list/ reorder_list.py
1,527
4.09375
4
# time: O(n) # space: O(n) # Reorder List # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None """ Given 1->2->3->4->5 reorder it to 1->5->2->4->3. double_ll = [[1, N], [2,1], [3,2], [4, 3], [5, 4]] double_ll = [[4, 3], [5, 4]] double_ll = [[4, 3]] new_parent = 5 parent = 4 1->N 2->3->4 1->5->2->3->4 double_ll = [] new_parent = 4 parent = 3 1->5->2->N 3 1->5->2->4->3 """ class Solution: def reorderList(self, head: ListNode) -> None: """ Do not return anything, modify head in-place instead. """ double_ll = [] #this will imitate a doubley linked list current = head prev = None while current: #fill doubley ll double_ll.append([current, prev]) prev = current current = current.next double_ll = double_ll[(len(double_ll) // 2) + 1:] #remove and include only nodes that will be swapped current = head while current: #while you can move through linked list if double_ll: new_next, parent = double_ll.pop() #pop of double_ll next_node = current.next #store next_node parent.next = None #remove relationship with parent current.next = new_next #general swaps new_next.next = next_node current = new_next.next continue current = current.next #continue until the end of the linked list
57dbe8819e480b5eec4d3ebee741be470f46029c
amankn/Day--2-Start-Code
/main.py
560
4.0625
4
#Data Types #String print("Aman"[3]) print("123" + "345") print("12" + "18") #Integers print(123 + 345) # How to put commas in large Integers - python we use underscores print(3_45_000) #FloatingPoint print(3.124) #Boolean print(True) print(False) #TypeError, Type Conversion num_char = len(input("What is your name : ")) print(type(num_char)) # Number to String print("Your name has " + str(num_char) + " characters.") # Number a = 123 print(type(a)) print(str(a)) a = float(123) print(70 + float("1000.45")) print(str(70) + str(100))
8059fee40edfad48c46ded1e1a34128ee4a2e85b
epangar/automate-the-boring-stuff-with-python
/Basics/TicTacToe/tictactoe.py
482
3.546875
4
import random board = { "UL": " ", "UM": " ", "UR": " ", "ML": " ", "MM": " ", "MR": " ", "DL": " ", "DM": " ", "DR": " ", } def print_board(): print(board['UL'] + '|' + board['UM'] + '|' + board['UR']) print('-+-+-') print(board['ML'] + '|' + board['MM'] + '|' + board['MR']) print('-+-+-') print(board['DL'] + '|' + board['DM'] + '|' + board['DR']) def toss_coin(): return ['False','True'][random.randint(0,1)] #while(" " in board.values()):
b5cbc61d5070481fa9cfa55d74918563ba7ebec8
KetanMehlawat/python-programs
/temperature conversion.py
1,621
4.25
4
while True: print "Press 1 to continue" print "press 0 to exit" ch=input("enter your choice") if ch>1 or ch<0: print ("please press correct button") continue elif ch==1: while True: print"Menu" print"1.From celcius to fahrenheit" print"2.From fahrenheit to celcius" print"3.From celcius to kelvin" print"4.From kelvin to celcius" print"5.From kelvin to fahrenheit" print"6.From fahrenheit to kelvin" print"0.Exit" ch=input("enter your choice ") if ch<0 or ch>6: print"please enter correct choice" continue elif ch==1: t=input("temperature in celcius ") f=((9/5.0)*t)+32 print "temperature in fahrenheit is ",f elif ch==2: t=input("temperature in fahrenheit ") c=((t-32.0)*(5/9.0)) print "temperature in celcius is ",c elif ch==3: t=input("temperature in celcius ") k=t+273.0 print "temperature in kelvin is ",k elif ch==4: t=input("temperature in kelvin ") c=t-273.0 print "temperatur in celcius is ",c elif ch==5: t=input("temperature in kelvin ") f=((9/5.0)*t)+32 print "temperature in fahrenheit is ",f elif ch==6: t=input("temperature in fahrenheit ") k=((t-32)*(5/9.0))+273 print "temperature in kelvin is ",k else: break else: break
a45e9d3eecb1936f5fea8b6b648cc15cfbdff137
Audio/SPOJ
/LASTDIG/solution.py
214
3.6875
4
# http://aditya.vaidya.info/blog/2014/06/27/modular-exponentiation-python/ lines = int(input()) for i in range(lines): ab = input().split(' ') a = int(ab[0]) b = int(ab[1]) print( pow(a, b, 10) )
21b858e51b841c168779eb9393f13398fad1fd20
yuwinzer/GB_Phyton_Algorithms
/les_01/task_07.py
1,297
3.65625
4
# 7. По длинам трех отрезков, введенных пользователем, определить возможность существования треугольника, # составленного из этих отрезков. Если такой треугольник существует, то определить, является ли он разносторонним, # равнобедренным или равносторонним. l_1, l_2, l_3 = [int(i) for i in input("Введите длины трех отрезков a, b, c: ").split()] if l_1 + l_2 - l_3 < 0 or l_1 - l_2 + l_3 < 0 or - l_1 + l_2 + l_3 < 0: print('Из этих отрезков невозможно построить треугольник') elif l_1 == l_2 and l_1 != l_3 or l_1 == l_3 and l_1 != l_2 or l_2 == l_3 and l_1 != l_2: print('Из данных отрезков может быть построен равнобедренный треугольник') elif l_1 == l_2 == l_3: print('Из данных отрезков может быть построен равносторонний треугольник') else: print('Из данных отрезков может быть построен разносторонний треугольник')
6ec2c4481a0e90ed24d88cc86de8e8d2567d5862
TheheiWorld/example
/com.juststand.study/oo/reflect_test.py
338
3.765625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # author : juststand # create_date : 2018/12/18 下午4:03 class Dog(object): def __init__(self, name): self.name = name def eat(self): print("%s is eating" % self.name) d = Dog("dog") choice = input(">>>").strip() if hasattr(d, choice): getattr(d, choice)()
aeb069d66f949e7f9d2d0e81441abb7d42f7ed1a
explocomposer/TP
/Année binaire.py
646
3.75
4
année = int(input("Saisissez une année: ")) if 4 % année == 0: bissextile = True elif 100 % année == 0: bissextile == True elif 400 % année == 0: bissextile = True print("L'année est bissextile") else: bissextile = True print("L'année est bissextile") # Si une année n'est pas multiple de 4, on s'arrête là, elle n'est pas bissextile. # Si elle est multiple de 4, on regarde si elle est multiple de 100. # Si c'est le cas, on regarde si elle est multiple de 400. # Si c'est le cas, l'année est bissextile. # Sinon, elle n'est pas bissextile. # Sinon, elle est bissextile.