blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
99629aaaa61fb288f2b28edf9bf8b4ef4791537a
danielzengqx/Python-practise
/CC150 5th/CH9/9.11.py
2,423
4.21875
4
# Given a boolean expression consisting of the symbols 0, 1, &, |, and ^, and a desired boolean # result value result, implement a function to count the number of ways of parenthesizing the expression # such that it evaluates to result #example: #input: f(1^0|0|1, true) #output: the number of ways #method, 1^0|0|1 ...
293d9f5a447f22babf3392df7c58a64da3b2dd48
danielzengqx/Python-practise
/CC150 5th/CH18/18.4.py
296
3.953125
4
#Write a method to count the number of 2s between 0 and n. def counter(n): sum3 = 0 while n != 0: #print n if n %10 == 2: sum3 += 1 n = n/10 return sum3 def main(): n = 102 i = 0 sum2 = 0 while i <= n: sum2 += counter(i) i+=1 print sum2 if __name__ == "__main__": main()
0bef4ff4cff25257b754b8a611d127c90a9c8153
danielzengqx/Python-practise
/CC150 5th/CH18/18.1.py
1,078
4.21875
4
#Write a function that adds two numbers. #You should not use + or any arithmetic operators. #There is an example->this is based 10 # 1. Add 759 + 674, but “forget” to carry. I then get 323. # 2. Add 759 + 674 but only do the carrying, rather than the addition of each digit. I then get 1110. # 3. Add the result of th...
2fae847ff972b40ae6ca7658e5717dc147584a6c
danielzengqx/Python-practise
/CC150 5th/CH18/18.8.py
461
3.90625
4
Given a string s and an array of smaller strings T, design a method to search s for each small string in T. def main(): String testString = “mississippi” String[] stringList = {"is", "sip", "hi", "sis", "mis"} #APPROACH 1, hashmap store all the small strings 2, brute force testString and cheak the hashmap for every...
3a5df1c350b28b6b2daadf7131dc3acf3510aea1
danielzengqx/Python-practise
/CC150 5th/CH7/7.4.py
1,102
4.25
4
#Write a method to implement *, - , / operations. You should use only the + operator. #general tricks for * and / # 1), first calculate the value # 2), second calculate the sign of the value def check_sign(num1, num2): #this is for checking the input sign sign = True sign1 = 0 sign2 = 0 if...
1eb235058e2f2ca3768340bff1e06c73de6eeefb
danielzengqx/Python-practise
/1 min/Check premutation.py
220
3.703125
4
#In premutation the order does matter #'abc', 'bac' -> yes a = 'abbc' b = 'baac' def checking(): global a, b a = ''.join(sorted(a)) b = ''.join(sorted(b)) if a == b: print "yes" else: print 'No' checking()
4b0fb88d35331de779a1187c4f1244716ca72aca
danielzengqx/Python-practise
/CC150 5th/CH5/5.3.py
2,663
3.6875
4
#Given an integer, print the next smallest and next largest number that have the same number of 1 bits in their binary representation. #1), question is want the next number with same number of 1 bits for both up counting and down counting #2), the first approach is brute force, I will show the code here #3), 110001110...
53ce4e5525efb62d8091c939685e0e4334392f6e
danielzengqx/Python-practise
/CC150 5th/CH4/4.9.py
2,324
4.03125
4
#you are given a binary tree in which each node contains a value. Design an algorithm to print all paths which sum up to that value. Note that it can be any path in the tree - it does not have to start at the root. #build up the BST class Node(object): def __init__(self, data, parent = None, left=None, right=None):...
7cab202ec5cdcbdef160d10fcc5069b6b2579c44
danielzengqx/Python-practise
/CC150 6th/2.2.py
399
3.578125
4
#Return Kth to last class Node: def __init__(self, data): self.data = data self.nextNode = None node1 = Node(1) node2 = Node(2) node3 = Node(3) node4 = Node(7) node5 = Node(8) node1.nextNode = node2 node2.nextNode = node3 node3.nextNode = node4 node4.nextNode = node5 #input k = 2 i = 0 index = node1 while i...
e07591dd42b35944bc9465d537fd9284d3e27b7e
danielzengqx/Python-practise
/2016 interview/Amazon/first round.py
1,566
3.5
4
# Enter your code here. Read input from STDIN. Print output to STDOUT import sys #read the data data = sys.stdin.readlines() length = int(data[0]) def helper(line): line = line.split() line = map(lambda s:int(s), line) return line matrix = map(helper, data[1:]) def matrix_process(matrix, length): for ...
a5ca78ba7b3ab81581ac338f32de66fb1cafd8ae
danielzengqx/Python-practise
/CC150 6th/1.8.py
680
3.53125
4
#Zero matrix #identify the zero and set boolean for the zero place matrix = [[1, 2, 3], [4, 2, 6], [7, 8, 9], [10, 11, 0]] def matrix1(): global matrix N = len(matrix) M = len(matrix[0]) for i in range(0, N): for j in range(0, M): if matrix[i][j] == 0: #column matrix[i][0] = 'False' #row mat...
3c4c86c37cc543d9ff4aedba601c6d2211e8edba
danielzengqx/Python-practise
/CC150 5th/CH18/18.9.py
796
3.9375
4
#Numbers are randomly generated and passed to a method. Write a program to find and maintain the median value as new values are generated. #for the program, if we only need to insert one element in either maxheap or minheap, this only takes about O(log(n)) to maintain import heapq listForTree = [1,2,3,4,5,6,7,8,9,1...
9774df98435dc7b6bfa295dd36c9a58666b94068
danielzengqx/Python-practise
/CC150 5th/CH1/1.4 & 1.5.py
1,484
3.5
4
def true_length(): a = "hi, I am Richard " size = 5 if(len(a)<size): add = len(a)-size a = a.replace(" ", "%20") for i in range(0, add): a += "%20" print a elif len(a)>size: a = a[0:size] a = a.replace(" ", "%20") print a ...
c8551b0ba3427eab85b5ce7403134e2328beee00
danielzengqx/Python-practise
/2016 interview/r practise/median in unsorted list.py
816
4.03125
4
#round two #find median in unsorted list -> quick select in the unsorted list def quickSelect(list1, start, end, pos): mid = (start+end)/2 #divide the list1 by Value of mid -> partition left = [item for item in list1 if item < list1[mid]] right = [item for item in list1 if item > list1[mid]] ...
7c210dba45150177d8dd9347f50b485655e4deef
danielzengqx/Python-practise
/1 min/building BST.py
925
4.0625
4
#build up the BST class Node(object): def __init__(self, data, parent = None, left=None, right=None): self.data = data self.parent = parent self.left = left self.right = right def insert(self, data): #check the root data first if self.data: ...
f7c93024633b3cc378a875f8e0f8e4e5293f14a0
danielzengqx/Python-practise
/CC150 6th/4.1.py
1,251
3.984375
4
#BFS #This is a undirected map graph = {'A': ['B', 'E'], 'B': ['A', 'C'], 'C': ['B', 'D'], 'D': ['E', 'C'], 'E': ['A', 'D']} visited1 = set() visited2 = set() class Queue: def __init__(self): self.item = [] def enqueue(self, item): self.item.extend(item) def dequeue(self): return se...
d09b486ca9035973409daed7dd7adc8b4a3cbfa6
danielzengqx/Python-practise
/2016 interview/r practise/happy number.py
565
3.9375
4
#round 1 #Happy number, sum of the power of 2 for each digit == 1 at the end #1^2 + 9^2 = 82 #8^2 + 2^2 = 68 #6^2 + 8^2 = 100 #1^2 + 0^2 + 0^2 = 1 def happynum(num): #prevent an infinite loop numset = set() while num != 1 and num not in numset: numset.add(num) sum = 0 #sum the new ...
0e0156821aa764f64f4344d6ee2f36cec5ef89fa
Makhanya/PythonMasterClass
/Functions/exercises/multiple_letter_count.py
255
4.03125
4
''' multiple_letter_count("awesome") # {'a': 1, 'e': 2, 'm': 1, 'o': 1, 's': 1, 'w': 1} ''' # flesh out multiple_letter count: def multiple_letter_count(string): return {x: string.count(x) for x in string} print(multiple_letter_count("awesome"))
18c6a0c0663c60b881552e7367abdbad54f6518a
Makhanya/PythonMasterClass
/boolean&ConditionalLogic/positiveornegetice.py
1,495
4.5
4
# Positive or Negative Checking # In this exercise x and y are two random variables. # The code at the top of the file randomly assigns them ( # we'll learn how it works later on). For now, just leave it alone: ) # 1. If both are positive numbers, print "both positive". # 2. If both are negative, print "b...
a8f2050d712f032111b62958b55615f780847bdf
Makhanya/PythonMasterClass
/section36/partTwo/repeat.py
167
3.796875
4
def repeat(string, num): if (num == 0): return '' i = 0 newStr = '' while (i < num): newStr += string i += 1 return newStr
e52842f9229a77006005739b16ff38411e75bbb3
Makhanya/PythonMasterClass
/Functions/first_function.py
355
3.609375
4
# def sing_happy_birthday(): # print("Happy Birthday To You") # print("Happy Birthday To You") # print("Happy Birthday Dear You") # print("Happy Birthday to you") # sing_happy_birthday # def print_square_of_7(): # print(7**2) # print_square_of_7() # def square_or_7(): # return 7**2 # resu...
25617a763707474dc6eafd84501d3f47a0f14ecb
Makhanya/PythonMasterClass
/lists/listBasic.py
448
4
4
# Initially create an empty list called instructors instructor = [] # Add the following strings to the instructors list # "Colt" # "Blue" # "Lisa" instructor.append("Colt") instructor.append("Blue") instructor.append("Lisa") # Run the tests to make sure you've done this correctly! "Colt" in instructor "Blue" in instruc...
3cbd7e3d43b087eb619871ff73c90ca272b1f90f
Makhanya/PythonMasterClass
/Functions2/colours.py
749
3.515625
4
# # def fav_colour(**people): # for person, colour in people.items(): # print(f"{person}'s favorite colour is {colour}") # fav_colour(makhanya="purple", hlumela="red", koza="blue") # fav_colour(makhanya="purple", hlumela="red", koza="blue", johnathen="silver") # fav_colour(makhanya="purple") def special_g...
4bd124f54ebd4d3735eac374e796a6008dcdd112
Makhanya/PythonMasterClass
/dictionary/accessDatadictionaryExercise.py
727
4.34375
4
# artist = { # "first": "Neil", # "last": "Young" # } # # Accessing Individual Values # # instructor["name"] # # print(artist) # full_name = artist["first"] + " " + artist["last"] # print(full_name) # # How to iterate of a dictionary # Accessing All values in a dictionary # Use.values() # fo...
aeeaf929c973ac76d1bb81564f84b6dc45cc5171
Makhanya/PythonMasterClass
/regEx/re_module.py
160
3.578125
4
""" Using REGEX with Python """ import re pattern = re.compile(r'\d{3} \d{3}-\d{4}') res = pattern.search('Call me at 415 555-4242!') print(res.group())
5b8db2ecec5023e6d39c33adae95e5a53125fead
Makhanya/PythonMasterClass
/regEx/parsing_bytes_exercise.py
847
3.828125
4
""" Parsing Bytes Exercise Write a function called parse_bytes that accepts a single string. It should return a list of the binary bytes contained in the string. Each byte is just a combination of eight 1's or 0's. For example: parse_bytes("11010101 101 323") # ['11010101'] parse_bytes("my data is: 10101010 11100...
3927d92d1747e77110b8d633ea473ea9da4a6f12
Makhanya/PythonMasterClass
/dictionary/dictionaryMethods.py
2,197
4.3125
4
# # Dictionary Methods # working with dictionaries is very # common - there are quite a few things # we can do! # Clear # Clears the dictionary # d = dict(a=1, b=2, c=3) # d.clear() # d # {} # print(d) # Copy # Copy the dictionary but have different address in memory # d ...
b57ddb1eca13d47996a4fbc16cce597842d19bc6
Makhanya/PythonMasterClass
/regEx/phone.py
1,108
3.96875
4
import re def extract_phone(input): phone_regex = re.compile(r'\b\d{3} \d{3}-\d{4}\b') match = phone_regex.search(input) if match: return match.group() else: return None def extract_all_phones(input): phone_regex = re.compile(r'\b\d{3} \d{3}-\d{4}\b') return phone_regex.finda...
058c998f0c3be158ddb8a13459250c4c439cbfdc
Makhanya/PythonMasterClass
/Functions2/thePurpleTest.py
351
3.640625
4
def contains_purple(*args): if 'purple' in args: return True else: return False print(contains_purple(25, "purple")) print(contains_purple("green", False, 37, "blue", "hello world")) print(contains_purple("purple")) print(contains_purple("a", 99, "blah blah blah", 1, True, False, "purple")) p...
d06d89d51d0ce6e7a58f55fb58d7f48c9030fd4a
Makhanya/PythonMasterClass
/http/dad.py
854
3.640625
4
from pyfiglet import figlet_format from termcolor import colored from requests import get from random import choice print(colored(figlet_format("DAD Jokes 2000"), color="red")) url = "https://icanhazdadjoke.com/search" key_word = input("Let me tell your a joke! Give me a topic: ") response = get( url, headers=...
4e6687fb7a767243a5d8cb51c2bb5a63954afb68
Makhanya/PythonMasterClass
/Lambdas/sorted.py
249
3.5625
4
songs = [ {"title": "happy birthday", "playcount": 1}, {"title": "Survive", "playcount": 6}, {"title": "YMCA", "playcount": 99}, {"title": "Toxic", "playcount": 31} ] print(sorted(songs, key=lambda s: s['playcount'], reverse=True))
acd3534b47984489ba66fad08701fe52378a6e1a
Makhanya/PythonMasterClass
/OOP2/polymorphism.py
1,385
3.875
4
""" Polymorphism A key principle in OOP is the idea of polymorphism- an object can take on many(poly) form(morph) While a formal definition of polymorphism is more difficult, here are two important practical applications: 1.The same class method works in a similar way for different classes...
8ba61193d66678212c9237b02a0105ab6d01b563
Brian-Yee/montecarlo-sudoku
/src/backtrack.py
1,474
4.03125
4
#!/usr/bin/env python3 """ Function for implementing the backtracking algorithm for solving sudoku systems. """ from collections import deque import numpy as np def backtrack(sudoku, indexer): """ Solve sudoku system with backtracking algorithm. Arguments: sudoku: np.array A sudoku pu...
3a4dba2207fb759bce3a0acbf59c67c4487e7ec3
ashipems/Python-projects_Adira
/hangman.py
3,718
4.0625
4
import random def get_word(): words = ["apple", "banana", "mango"] choice = random.choice(words) return choice def play(word): print("Let's play Hangman!") tries = 6 print(display_man(tries)) guess_word = "_" * len(word) print(guess_word) guessed = False guessed_letters = []...
03c19a6e7f23840a4b9586531d04f517c0d58863
sandykrishdaswani/hunterset1
/14.py
196
3.546875
4
from itertools import permutations puru=input() queen=permutations(puru) r=[] for i in list(queen): s="".join(i) if s not in r: r.append(s) for i in r: print(i)
e055b6a9b473407ca37bb35f6b72983e5ac1f66b
hobart2018/python123
/base/CalStatisticsV1.py
810
3.703125
4
def getNum(): nums = [] iNumStr = input("请输入数字(回车退出)") while iNumStr != "": nums.append(eval(iNumStr)) iNumStr = input("请输入数字(回车退出)") return nums def mean(numbers): s = 0.0 for i in numbers: s += i return s / len(numbers) def dev(numbers, mean): sdev = 0.0 ...
168db7dc3c3c5102fd6161b84abada2bb66cbc2d
hobart2018/python123
/circular_list.py
1,828
3.796875
4
class ListNode: def __init__(self, data): self.data = data self.next = None class CircularList: def __init__(self): self.head = None self.tail = None self.size = 0 def append(self, data): node = ListNode(data) if self.head == None: self.h...
966749402a6618399cc03cde7d0325b9b0e15ade
emukhtarov1/Skills-Programming---Group-Project
/Financial Analysis - Skills_Programming.py
7,282
3.9375
4
#!/usr/bin/env python # coding: utf-8 # In[1]: #This program lets the user choose a number of listed stocks taken directly from Yahoo Finance. It utilises the data from Yahoo Finance to compare the portofolio of stocks chosen based on a number of financial and operational KPIs # In[2]: pip install yfinance # I...
b9dab075ac04b78bfc42e8fbd4e5f6976248ba23
synsyh/TriangleYS
/TestTriangle.py
3,339
4.125
4
# -*- coding: utf-8 -*- """ Updated Jan 21, 2018 The primary goal of this file is to demonstrate a simple unittest implementation @author: jrr @author: rk """ import unittest from Triangle import classifyTriangle # This code implements the unit test functionality # https://docs.python.org/3/library/unittest.html h...
80b76cb11f5b5b96f61b4d32e33492b7c111311f
mahirAkay/revrec
/helpers.py
3,674
3.671875
4
from __future__ import division import random import math from datetime import datetime, timedelta from calendar import isleap """ ------------------- HELPER FUNCTIONS ------------------- """ def daterange(start_date, end_date): """A generator that yields an iterator containing dates within the specified date rang...
e0b40bc158edc1c4893108be11cc2467bb71f4c9
jrocha2/PuzzleCP
/main.py
1,419
3.671875
4
import pygame import sys from puzzle import Puzzle if __name__ == '__main__': w = 600 h = 600 pygame.init() pygame.display.set_caption("Course Project 3: Interactive Puzzle") #need a loop in case the user hits the back button outer_loop = 1 while outer_loop: screen = pygame.display.set_mode((w, h)...
37c1719ea3fd0043b7dfacdc28500ff6f5e6aaf4
arnawldo/Data-Structures-And-Algorithms
/Algorithmic-Toolbox/week3/covering_segments.py
1,180
3.921875
4
# Uses python3 '''Given a set of n segments {[a 0 , b 0 ], [a 1 , b 1 ], . . . , [a n−1 , b n−1 ]} with integer coordinates on a line, find the minimum number m of points such that each segment contains at least one point. That is, find a set of integers X of the minimum size such that for any segment [a i , b i ] ther...
7e82c1440fc97adeaf861b4bdd6d65039972958b
arnawldo/Data-Structures-And-Algorithms
/Algorithmic-Toolbox/week3/fractional_knapsack.py
936
3.671875
4
# Uses python3 import sys def get_optimal_value(capacity, weights, values): value = 0 W = capacity #list of lists containing value, weight, value per kg = density wvd = [[v, w, float(v/w)] for v, w in zip(values, weights)] #sort list according to density wvd = sorted(wvd, key=lambda x: x[2], ...
012dede484375689d4777d3aa0c8ef3598c0d05c
arnawldo/Data-Structures-And-Algorithms
/Algorithmic-Toolbox/week4/inversions.py
1,123
4.0625
4
# uses python3 ''' The goal in this problem is to count the number of inversions of a given sequence.''' import sys def merge(b, b_inversions, c, c_inversions): # b and c are sorted # create empty array for merged b and c d = [] inversions = b_inversions + c_inversions while (len(b) != 0) and (l...
fdb38b4848aafe4c95818a70ee8f22f60967f5d0
IrvACD/Practice_PyCharm
/if_statements.py
199
3.984375
4
hot_day = False cold_day = False if hot_day: print("It's a hot day. Drink plenty of water!") elif cold_day: print("It's a cold day. Wear warm clothes.") else: print("It's a lovely day!")
65e5e5b4fe9dd00c468e66d75fe60ded8ed59097
Ze1598/data-projects
/demos/streamlit/streamlit_iris_demo.py
2,626
3.6875
4
# >> streamlit run streamlit_iris_demo.py import streamlit as st import pandas as pd from sklearn import datasets from sklearn.ensemble import RandomForestClassifier # Global variables # --------------------------------------------------------------- # Possible classes/flower types (ordered as in the dataset) CLASSES ...
f9db185c7ea88f8da5343bca5cf8cc324b579101
LITdrive/aadc2018
/src/aadcUserPython/pathPoints/drawPath.py
3,228
3.796875
4
import matplotlib.pyplot as plt from PIL import Image import numpy as np import pandas as pd # CONFIG this Suff here ;) ###################################### MAP_LENGTH = 5.020 #in m MAP_HIGHT = 4.020 #in m mapImg = 'ourMap.jpg' ################################################################# points = [] # functio...
2c6a98934bcfd7c7433c613fec647642ea777f83
rdsr/cs212
/final_exam/Polynomials.py
10,206
4.65625
5
""" UNIT 3: Functions and APIs: Polynomials A polynomial is a mathematical formula like: 30 * x**2 + 20 * x + 10 More formally, it involves a single variable (here 'x'), and the sum of one or more terms, where each term is a real number multiplied by the variable raised to a non-negative integer power. (Remember...
1dda5da0d88b7d6aa780248cafe3f912785075d0
PJFinnerty/Peter-Finnerty-Programming-and-Scripting-Project
/Analysis.py
43,770
3.71875
4
# Peter Finnerty - Project 2020 # Write a program called analysis.py that: # • outputs a summary of each variable to a single text file, # • saves a histogram of each variable to png files, and # • outputs a scatter plot of each pair of variables. #----------------------------------------------------------- import ma...
9c531f475cb2836dfbf7b6fa5f67bca3103ee823
CatAnderson/python_pub_lab
/pub_lab/src/customer.py
442
3.625
4
class Customer: def __init__(self, name, wallet): self.name = name self.wallet = wallet self.drinks_in_hand = [] self.age = 20 def add_drink_to_customer_hand(self, drink): self.drinks_in_hand.append(drink) def alter_customer_wallet_amount(self, drink_price): ...
eda68a74f3d3d2116dab1434aeb52f4d5013cb58
chapman-cs510-2016f/cw-08-datacats
/cplaneJulia.py
5,113
4.03125
4
#!/usr/bin/env python3 import cplanenp import pandas as pd import numpy as np import matplotlib.pyplot as plt """ Julia Plane Class This module class extends the cplanenp class by creating the complex grid of numbers, then transforming the plane using the class' Julia function, and turning it to the julia complex pla...
8d2ae542d9a56d563dd29ad2ddc90b02b619b7ff
daianasousa/Gerador-de-Comprimentos
/Desafio_Adicione_+_cumprimentos.py
516
4
4
from random import * print("Gerador de Cumprimentos") print("--------------------") adjetivos = [ "maravilhoso", "acima da média", "excelente" , "muito bom", "perfeito", "magnifico" ] hobbies = [ "anda de bicicleta", "programar", "fazer chá", "comer" ] nome = input("Qual é o seu nome?: ") print( "Aqui está o seu cum...
6a9426f4b90f78099819b6b9bff648f2daf362fd
jukim20/Python_Practice
/Day14/test14_01.py
533
4.03125
4
# 변수의 생명주기 : 지역변수 , 전역변수 # 1) 전역변수 : 프로그램이 시작해서 종료될때 메모리에서 해제 # 2) 지역변수 : 함수안에서 생성되서 함수가 종료될때 해제 def test(): num = 10 num = 20 test() while True: sel = input("quit 을 입력하세요 ") if sel == "quit": break test() test() print(num) def test2(num): num * num return num num = test2() prin...
fe1093c94febeeaec4c2e2ba822b43d09ac4cacf
jukim20/Python_Practice
/Day17/Dictionary17_01.py
2,254
3.59375
4
# 딕셔너리 (dictionary) """ 1. 사전에서 "단어를 기준으로 해설" 을 찾듯이 "키를 기준으로 값" 을 찾는 기능을 제공한다. ==> 키(인덱스)를 내가정한다. 2. 구조 { key1 : value1 , key2 : value2 , key3 : value3 ...} 3. key 는 변하지않는다. 4. 순서가 없다 """ lst = [1, 2] # 값만저장할수 있고 인덱스 는 자동으로 0~ 순차적으로 저장 print(lst[0]) dict1 = {0: 1, 1: 2, 2: 3, 3: 4} print(dict1[0]) dict1 = {"0":...
5d88200aca0605e2440b6a032867cfc927fba858
jukim20/Python_Practice
/Day20/GUI20_03.py
767
3.734375
4
from tkinter import * """ StringVar() : 문자열 IntVar() : 정수 DoubleVar() : 실수 BooleanVar() : 논리값 (True, False) """ win = Tk() str1 = StringVar() n1 = IntVar() b1 = BooleanVar() d1 = DoubleVar() # 변수 매개가 만들어짐 def print_msg(): str1.set("버튼1") # str1 = '버튼1' ==> str1.set("버튼1") s1 = "버튼1" print("현재 클릭된 버튼 : ...
03e1fd2721b34d7281ac29bc8ec455734e2d51b5
jukim20/Python_Practice
/Day03/if03_02.py
643
3.8125
4
# 산술연산자 ==> (+) (-) (*) (/) (%) # 대입연산자 ==> (=) # 비교연산자 """ 1. a == b : a 와 b 가 같으면 True 2. a != b : a 와 b 가 다르면 True 3. a > b : a 가 b 보다 크면 True 4. a < b : a 가 b 보다 작으면 True 5. a >= b : a 가 b 보다 크거나 같으면 True 6. a <= b : a 가 b 보다 작거나 같으면 True """ print(10...
b581dd735a8bbe60a0747452ca6b161a34c0af53
jukim20/Python_Practice
/Day10/list10_01.py
1,460
3.8125
4
import random # 리스트 함수 # 1. 추가 (append) *** lst = [1, 2, 3] lst.append(5) print(lst) lst = [] # 문제 1) 위 리스트 (빈 리스트) 에 랜덤 0~100 사이의 숫자 4개를 저장해보세요. (반복문 사용) i = 0 while i < 4: num = random.randint(0, 100) lst.append(num) i += 1 print(lst) # 2. 확장 (extend) 리스트 + 리스트 # append 와 다른 점: 리스...
a374b831233c016a3d7fd65d03c6ad8b220c2713
jukim20/Python_Practice
/Day03/test03_03.py
954
3.71875
4
# 숫자 2개를 입력받고 더하기를 출력하세요 # 응용문제 3) 월급을 입력받고 연봉을 구해보세요 (세금 10% 제외) # 예) 출력 ==> 월급 ==> 20 , 연봉 에서 10% 제외한금액 (???) # 응용문제 1) 숫자하나를 입력받고 양수인지 음수 , 0 인지 출력 해보세요 # 응용문제 2) 성적 (0~100 ) 하나 입력받고 60이 넘으면 합격 이하면 불합격 출력 # 성적을 입력하세요 >>> 60 ==> 합격 , 59 ==> 불합격 , (-10 , 101) ==> 잘못입력했습니다 # 0~100 # 들여쓰기를 2번 적용할수 있다 ...
b5026001d08f2ad8ca8c48aaf1be6eb9c5154aae
jukim20/Python_Practice
/Day19/numpy19_01.py
1,010
3.765625
4
import numpy as np # as ==> numpy 를 앞으로 np 로 부르겠다 (다섯글자가 너무 기니 두글자로 줄임) """ list() dict() 보다 상위호환 """ data1 = [6, 7, 8, 9, 10] # 리스트를 만들어서 넘파이 배열에 집어넣음 arr1 = np.array(data1) # 넘파이 배열에 집어넣음 print(arr1) # [ 6 7 8 9 10] print(arr1.shape) data2 = [[1, 2, 3, 4], [5, 6, 7, 8]] print(data2) arr2 = np.array(data2) ...
e19ba3da63be4186797c93aec5668a8b1ebdaeef
jukim20/Python_Practice
/Day04/if04_02.py
794
3.984375
4
# 문제 1) 양수 음수 0 을 구분하는 식을 만들어보세요. num = int(input("숫자를 입력하세요 >>> ")) if num > 0: print("양수입니다.") elif num < 0: print("음수입니다.") else: print("0입니다.") # 문제 2) 짝수 홀수를 구분하는 식을 만들어보세요. if num % 2 == 0: print("짝수입니다.") else: print("홀수입니다.") # 문제 3) 숫자 2개를 입력받고 ??가 ??보다 크다 or 작다 출력 num...
a9c5523fc2a5a5b5dc9288d42acddcbd16a06f42
jeffrey1227/Data-Structures-using-Python
/Stack(Array).py
565
3.859375
4
class Stack(): def __init__(self): self.array = [] def peek(self): return self.array[-1] def push(self, value): self.array.append(value) return def pop(self): if len(self.array) == 0: return None returnValue = self.array.pop() return...
5733d5b210cb5f59411a250c63e5d0aa0e3726ee
ivanrosolen/learning-python
/banco.py
920
3.890625
4
#!/usr/bin/python def menu(): saldo = 0.00 cheque_especial = 100.00 end = False while end == False: print 'SALDO ATUAL: R$ ',saldo option = input('Opcoes:\n1) Saque\n2) Deposito\nDigite a opcao desejada:') if option == 1: valor_saque = input('Solicitado saque, d...
734063ebe0464cbfad062608a727603c37a3907a
Avinashluhana/Python_practice
/bubble_sort.py
279
3.90625
4
list = [4,3,1,5,5,6,7,2] def sort(list): for i in range(len(list)-1,0,-1): for j in range(i): if list[j] > list[j+1]: temp = list[j] list[j] = list[j+1] list[j+1] = temp sort(list) print(list)
acbee959684843d274c8e2e15d1807013984d049
arj119/Project-Euler
/EULER 14.py
347
3.765625
4
number = 0 for i in range(1000000, 0, -1): count = 0 starting = i while i != 1: if (i % 2) == 0: i = i/2 count = count + 1 else: i = (3*i) + 1 count = count + 1 if count > number: number = count print(starting) print('fini...
6bd70eb07d4e3a8a856868104eaed80f0c87b204
Pernillo918/CursoPython
/ht2.py
1,495
4.53125
5
''' Ejercicio1 Escribir un programa que almacene una cadena de caracteres de contraseña en una variable, ingresada por el usuario, pregunte al usuario por la contraseña e imprima por pantalla si la contraseña introducida por el usuario coincide con la guardada en la variable sin tener en cuenta mayúsculas y minú...
e3444dd72dbf700a007037def2fe1a0a4d8da8ac
Invertseven/Network_Automation
/Python_Scripts/Random code/AutoTemplate.py
2,498
3.734375
4
import getpass import telnetlib HOST = "Localhost" user = input("Enter your telnet Username: ") password = getpass.getpass() #Telnet to multiswitches when using a file called myswitches f = open ('myswitches') for IP in f: IP=IP.strip() print ("Get running config from switch " + (IP))#Output of what is being ...
e3d0940dab2a06af3b938c50813ed6f15913bd46
kdoria/DijsktraVisualization
/dijkstraProject/board.py
2,734
3.71875
4
import pygame import random from .constants import * from .node import Node import time class Board: def __init__(self, win): self.board = [] self.win = win # Create the Grid def __draw_squares(self): self.win.fill(WHITE) for row in range(1, ROWS): pygame.draw....
3f2ba5752163af7006be247dfa4da58c437d059c
jiwonchoe/mayaPy
/num.py
466
3.875
4
import itertools as its import string def alphabetCycle(alphabetCase,countNumber): if alphabetCase == 'lower': alphabetList = list(string.ascii_lowercase) else: alphabetList = list(string.ascii_uppercase) returnList = [] alphabetIts = its.cycle(alphabetList) for y,x in enumerate(...
e0fcd5905560579a832dca97e2b8d7c54e98cf63
fritzo/kazoo
/test/synchronize.py
25,228
3.625
4
#!/usr/bin/python import main from numpy import * from matplotlib import pyplot def smooth(x, radius, iters=1): if iters == 0: return x ix = cumsum(x, 0) sx = (ix[radius:, :] - ix[:-radius]) / radius return smooth(sx, radius, iters - 1) # ----( beat functions )------------------------------...
5dd6deea2117e9856a7f081c4fe9e3d147eb5f6c
fritzo/kazoo
/test/detect.py
4,598
3.765625
4
import math, numpy import Image, ImageDraw def draw_circle(draw, center, radius, **kwds): x, y = center draw.ellipse((x - radius, y - radius, x + radius, y + radius), **kwds) # ----( image processing )----------------------------------------------------- def square_blur(x, radius): "square blur kernel...
af30202b1094db96564df5657e9a52cdcefd06f8
fgokdata/exercises-python
/continue/while.py
344
4.03125
4
import random # import ??? xnum = random.randint(1, 100) num = int(input('please enter a number between 1 and 100:')) while num != xnum: if num < xnum: print(f' {num} enter a greater number ') num = int(input()) else: print(f' {num} enter a smaller number ') num = int(input()...
f9e39a7b089094853f0734eea05ed7e232cc95cf
fgokdata/exercises-python
/project_ecu/fibonacci.py
1,273
3.984375
4
# By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. even_sum = 0 x = [1, 1] # Fibonacci sequence starts with 1,1... while (x [-2] + x [-1]) < 4000000: # Check if the coming number is smaller than 4 million if (x [-2] + x [-1]) % 2 == ...
f1134eff7d65cdfab5845cbe1eecf77c65d3cd9f
fgokdata/exercises-python
/continue/ifelse.py
119
3.59375
4
age = 10 if age >= 18: print('you can fly') elif age <= 10: print('you can go') else: print('go')
0402d42bea9bb878844d7bd2083d9119c88847a3
fgokdata/exercises-python
/continue/continue.py
104
3.765625
4
number = 1 while number < 12: number += 1 if number % 2 == 0: continue print(number)
f80f2e71b3027549856f8d7f028cfdb8395a219e
RohanDeshpande1998/Algorithms
/Assignment/merge-sort+count.py
1,453
4.125
4
def sort(arr, count=0): if len(arr) == 1: #End Case return(arr, count) elif len(arr) == 2: #End Case if arr[0]<arr[1]: return(arr, count) else: temp = arr[0] arr[0] = arr[1] arr[1] = temp count = count ...
27f01d0329ea0fdda60c2015bd9579125b73d209
aakward/OR-Lab
/Lab07_16i190010/ex1b_reg.py
6,420
3.8125
4
import numpy #for the following statement to compile successfully, you need the scikit-learn package. #You can install it using pip install -U scikit-learn or condai$ from sklearn.datasets import load_digits digits = load_digits() #check the shape of digits data print(digits.data.shape) #check the shape of digits...
9970aa382ae78f285e919d15fec224430dde22d2
aakward/OR-Lab
/Lab_05_16i190010/ex3b.py
2,081
3.546875
4
import math import matplotlib.pyplot as plt def evalf(x): y=1+math.pow(0.5,x) print y return y def main(): m=[] m.append(evalf(1)) m.append(evalf(2)) while(abs(m[len(m)-1]-m[len(m)-2])>0.000000001): m.append(evalf(len(m)+1)) x_s=m[len(m)-1] print "The sequence ...
b7bd202ba70b9e9516a43f9f17b1d30a77be2ec2
kookmin-sw/capstone-2020-1
/src/analyze/analysis.py
7,460
3.609375
4
import numpy as np import matplotlib.pyplot as plt from konlpy.tag import Okt import operator def visualization(chatlist): plt.bar(range(len(chatlist)), chatlist) plt.show() def print_point_hhmmss(point): for i in range(len(point)): seconds = point[i][0] hours = seconds // (60 * 60) ...
ca7c6d592b32b27c332fbf61538f4b9548900605
ncturoger/LeetCodePractice
/Linked_List/Reorder_List.py
1,892
3.84375
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def reorderList(self, head): """ :type head: ListNode :rtype: void Do not return anything, modify head in-place instead. """ ...
2fd1d48f00220ea91277d143e42631bb2ea3b5bb
ncturoger/LeetCodePractice
/Linked_List/Merge_Two_Sorted_Lists.py
1,210
3.921875
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def mergeTwoLists(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ if l1 and l2:...
f74eb16c6cefbbb917296d15fbeedd19d134df24
ncturoger/LeetCodePractice
/Array_and_String/Fizz_Buzz.py
494
3.65625
4
class Solution(object): def fizzBuzz(self, n): """ :type n: int :rtype: List[str] """ result = [] for i in range(1, 1+n): word = "" if i % 3 == 0: word += "Fizz" if i % 5 == 0: word += "B...
d58c5ef5153b2f583c1ab4c0bb678dd4d052f7ae
ncturoger/LeetCodePractice
/Array_and_String/Reverse_Words_in_a_String.py
536
3.625
4
class Solution(object): def reverseWords(self, s): """ :type s: str :rtype: str """ word_list = [] word = "" for c in s: if c != ' ': word += c else: word_list.append(word) wo...
37aa4d36eeed7581036f93b6d36138309a010db8
ncturoger/LeetCodePractice
/Array_and_String/Find_the_Duplicate_Number.py
426
3.703125
4
class Solution(object): def findDuplicate(self, nums): """ :type nums: List[int] :rtype: int """ seen_dict = dict() for num in nums: if seen_dict.get(num): return num else: seen_dict[num] = ...
3fb4d0a36de9e2fa24ea113875fa8ea0dd0f0c9a
Geesilu/Hacktoberfest2021-2
/Python/el_gamal_encryption.py
1,092
3.6875
4
# In cryptography, the ElGamal encryption system is an asymmetric key encryption algorithm for public-key cryptography # which is based on the Diffie–Hellman key exchange. It was described by Taher Elgamal in 1985. # ElGamal encryption is used in the free GNU Privacy Guard software, recent versions of PGP, and other cr...
6fb3a9e6b2fa8122f39085e94f43e0779f7e45d2
Rohan-Chaudhury/Basic-GUI-using-tkinter-library-in-python
/button recognition.py
323
3.71875
4
from tkinter import * root= Tk() def leftc(a): print("left") def middlec(a): print("middle") def rightc(a): print("right") frame=Frame(root,width=300,height=250) frame.bind("<Button-1>",leftc) frame.bind("<Button-2>",middlec) frame.bind("<Button-3>",rightc) frame.pack() root.mainloop(...
e3035635dc72870c8fc63b8f4131e4ef90ae4aed
pedritoeldulce/PythonTutorial2021
/introduccion/concatenacion.py
147
3.75
4
name = "Paolo" lastname = "Perez" # Forma 1 print(f"Mi datos son {name} {lastname}") # Forma 2 print("Mis datos son {} {}".format(name, lastname))
daec621081e7974cfe69243c1e410740ff9558e5
HuShuangPing/Study
/day01/var2.py
224
3.6875
4
# -*- coding:utf-8 -*- # Author:HuShuangPing print("HelloWorld") #变量 name = "Alice" name2=name print("名字是:",name,name2) name = "Jack" print(name,name2) #变量的定义规则 #变量第一个不能是数字
1294055327e775888fbb001b1782c59191bbf0ee
HuShuangPing/Study
/day04/decorator_4.py
996
3.859375
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:HuShuangPing #书写装饰器 import time #定义一个高阶函数 def timer(func): #相当于test1=timer(test1) def deco(*args,**kwargs): #若调用的函数有参数则传入,无就不传入 start_time=time.time() func(*args,*kwargs) stop_time = time.time() print("the func run time ...
4e6380bb52f614f6e68433a4ef9fa6a3c65c8226
HuShuangPing/Study
/day03/file_op.py
3,100
3.765625
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:HuShuangPing #data = open("yesterday",encoding="utf-8").read() #Windows系统中是gbk的编码,该IDE中是utf-8进行编码,因此打开此文件需要进行转码 #文件打开后需要赋给一个变量,方便对文件进行操作 ''' f = open("yesterday",'w',encoding="utf-8") #文件句柄,包括文件名,字符集,大小,在硬盘的起始位置 #第二...
a481e896bec2ca97606c59d7d99000b6fb152b1e
HuShuangPing/Study
/day04/生成器并行.py
982
3.53125
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:HuShuangPing import time def consumer(name): print("%s 准备吃包子啦!" %name) while True: baozi = yield #[None] print("包子[%s]来了,被[%s]吃了!" %(baozi,name)) c = consumer("Jack") c.__next__() #输出结果:Jack准备吃包子啦 c.__next__() #输出结果:包子[None]来了,被[...
509d04356a460b5bccf40abc0be34b040f7575f2
HuShuangPing/Study
/day07--面向对象编程进阶/metaclass.py
1,883
3.5625
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:HuShuangPing class MyType(type): # 类的生成 调用 顺序依次是 __new__ --> __init__ --> __call__ def __init__(self, what, bases=None, dict=None): print("--MyType init---") super(MyType, self).__init__(what, bases, dict) def __call__(self, *args, **kw...
91bc883cad020a9e908354d9c1f16fdf1af769c2
HuShuangPing/Study
/day09--异步IO 数据库 队列 缓存/线程_ex1_5.py
562
3.625
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:HuShuangPing #计算启动50线程循环所花费的时间 # 在线程_ex1_3基础上加个for循环 import threading import time def run(n): print("task",n) time.sleep(2) start_time = time.time() t_objs = [] #存线程实例 for i in range(50): t = threading.Thread(target=run,args=("t%s"%i,)) ...
e12a3fa76c8a512dfa3c93cab80076497469eec2
vivianakinyi/Coding-Interviews-Prep
/arrays.py
3,533
4.25
4
# Find pairs in the array that equals sum given def sum_pairs(nums, sum): pairs = [] if nums < 2: print "Array too small" for i in range(0, len(nums)): diff = sum - nums[i] if diff in nums: pairs.append((diff, nums[i])) return set(pairs) # print "No pair adds up to ", sum nums = [3,4,1,2,9] # n...
857fdc2bc1a7e1e77f49cb75712181968f100de7
vivianakinyi/Coding-Interviews-Prep
/mergeSortInversions.py
3,521
3.78125
4
# def mergeSortInversions(arr): # if len(arr) == 1: # return arr, 0 # else: # a = arr[:len(arr)/2] # b = arr[len(arr)/2:] # a, ai = mergeSortInversions(a) # b, bi = mergeSortInversions(b) # c = [] # i = 0 # j = 0 # inversions = 0 +...
f3d64cc99b4b92d350c3c600b59cad84d100de17
vcamp314/pybus
/pybus/bus.py
1,244
3.78125
4
""" This is a very simple implementation of a event bus. Source: Longpoke's post on SO: https://stackoverflow.com/questions/1092531/event-system-in-python """ class Bus(list): """Event bus. subclass of list, conceptually representing a list of the event subscribers which are callable objects. Event...
95ca89b8cfd22fdc19c250410aedfc254d7ee951
code-infected/Python_Programming
/LAB/LAB 4/sequenceofword.py
425
4.375
4
#Prints the unique words in sorted form from a comma separated sequence of words #user will enter the seuence of word with seperate comma List = input("Please enter the separated words with comma: ") #split funtion will split or break the word and the data to a string array using a seperater enter_word = [word for...
7b69ab415010d1a166b2b370aac786bb3e054b47
code-infected/Python_Programming
/ICE/ICE2/String.py
320
4.21875
4
#Enter string and calculate the number of digits and letters string = input("Please enter any Alphanumeric value :") Digit=Letter=0 for i in string: if i.isdigit(): Digit=Digit+1 elif i.isalpha(): Letter=Letter+1 print("Number of Letters is:", Letter) print("Number of Digits is:", Digit)
e382fec0bf924072d5e4d0dfb19a428751acbaea
NJC-Spicy-Chef/CEBD-1100-slide-8-class-exercises
/Class exercise part 1.py
1,022
4.34375
4
# Suppose we have a class called "Receipt" and we wanted receipts to have "Items" in the receipt. # Items can be 1 or more. In other words, ONE receipt holds MANY items. # To achieve this, we can store the items in a LIST. # We can also use a method to add items to the list. # Class Exercise (Part 1) # This will use A...
e181f7279c4adcd51b40ce2b02ba0511a132ed92
jinlee4140/Python
/OOP/bank2.py
332
3.59375
4
class BankAccount: def __init__(self): self.balance = 0 def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance a = BankAccount() b = BankAccount() print a.deposit(100) print b.deposit(50) print b.withdraw(10) print a....
294ebcd6b166d243a230d1fc8de67a8f1a1032ec
Abdul-Nassar/Think-Python-Class
/Recursion-Exercises/fermat.py
545
4.03125
4
import sys def main(): prompt = 'Enter values for a,b,c,n : \n' a = int(raw_input(prompt)) b = int(raw_input()) c = int(raw_input()) n = int(raw_input()) if n>2: check_fermat(a, b, c, n) else: print "No, that doesn't work." def check_fermat(a, b, c, n): p = a**n print 'P: ',p q = b**n print 'Q: ',q ...