blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
9fcae71930edcd89c155e87502e173e4c36186bc
darth-c0d3r/letterboxd-lists
/util.py
1,621
3.578125
4
import requests from bs4 import BeautifulSoup def get_soup(link): """ Get the soup for the HTML from link using requests. """ page = requests.get(link) return BeautifulSoup(page.content, 'html.parser') def get_films_on_page(link, page_no): """ return the list of films on current page """ all_films = [] ...
9e3e68424aabe6d77977a831d893b679bbb084a2
Herrizq/Color-game
/main.py
2,720
3.625
4
from tkinter import * import random root = Tk() #int, str etc. Colors = ["red", "green", "blue", "pink", "orange", "yellow", "black", "grey","magenta"] score_number = IntVar() score_number.set(0) time_num = IntVar() time_num.set(60) #Commands def change(x): global text if time_num.get() == 60: ...
bfea92143c2df4029288b4c781a8bfce28832891
brandonharris177/Computer-Architecture
/coding_challange.py
668
4.65625
5
# Given the following array of values, print out all the elements in reverse order, with each element on a new line. # For example, given the list # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] # Your output should be # 0 # 1 # 2 # 3 # 4 # 5 # 6 # 7 # 8 # 9 # 10 # You may use whatever programming language you'd li...
6f664e1c5ac800f0a4e3c6c174cbe2bfa0e21add
michaelcwatts123/InterviewPrep
/LeetCode/maxProduct.py
951
3.625
4
# Given an integer array, find three numbers whose product is maximum and output the maximum product. class Solution: def maximumProduct(self, nums: List[int]) -> int: if(max(nums) < 0 or min(nums) >= 0): total = max(nums) nums[nums.index(total)] = -sys.maxsize for i in ...
a7cb31b0ccf4a751365c9606771eef628de341ea
kreno911/python-tools
/comma.py
456
3.84375
4
#!/usr/bin/python # Add commas to long #s ## Usage: ./comma.py 123456 ## returns: 123,456 import os, sys # Number needs to be a string, not an int (int not iterable) def comma(number): e = list(number) for i in range(len(e))[::-3][1:]: e.insert(i+1,",") retur...
7ec121d75584a283e0de357a898898b3fefcfb7f
amoran0861/ProgramArchive
/rivers.py
485
4.21875
4
#Aidan Moran #Print rivers and their locations def RiverList(): rivers = { "USA": "Mississippi River", "Brazil": "Amazon River", "China": "Yangtze" } for place in rivers.keys(): print(rivers[place], "is in", place) print("Locations:") for place in rivers.keys():...
010614d8cdd0dac48cea9c50856008095a08c951
uriberger/reserach_methods_in_software_engineering
/char_ind_to_str.py
1,410
3.96875
4
""" The function receives a mapping of char->list of indices. It should build the implied string. For example: if the input is: 'g' -> [2] 'd' -> [0] 'o' -> [1] The output should be 'dog'. Features tested: - List and dictionary comprehension vs. loops """ def long_char_ind_to_str(char_to_ind_dic): ind_to_char_...
917ac9e099b3d7b932b1b18bae166e8828b09e26
JohnCetera/Python-Programs
/try, except - practice.py
458
4.21875
4
hours = input("total hours worked: ") rate = input("pay rate: ") try: hr = float(hours) rt = float(rate) if hours <= str(40): pay = hr * rt print(pay) elif hours >= str(40): base_pay = float(40 * rt) overtime = int(hr - 40) overtime_rate = int(rt * 1.5) ...
ffe9ade759225b05c684dd0096c2624863c8388d
fredzs/Python-Mp3TagSpider
/Utility/ListFunc.py
415
3.5
4
# class ListFunc(object): @staticmethod def compare_2_lists(list1, list2): compare_result = False if len(list1) == len(list2) > 0: for item in list1: if item.lower() in [i.lower() for i in list2]: continue else: ...
4554afec1fbc9dfb87c9206093597b019e4b3958
adamwinzdesign/Sprint-Challenge--Data-Structures-Python
/ring_buffer/ring_buffer.py
978
3.53125
4
class RingBuffer: def __init__(self, capacity): self.capacity = capacity self.data = [] self.oldest = 0 def append(self, item): # if current length of self.data is less than the provided capacity, simply add that item to data if len(self.data) < self.capacity: ...
e9227166aa61957df852b87682a09891a40309ac
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/bob/fe6e1e28feed47d88a81f1e42ee77aa3.py
402
3.6875
4
class Bob: """A teenager.""" def hey(self, statement): """Communicate with Bob.""" statement = statement.strip() if not statement: return "Fine. Be that way!" if statement.isupper(): return "Woah, chill out!" elif statement.endswith('?'): ...
df14696a460a3d2be10b009e44b4181631eb163b
Mureke/Advent-of-code
/2020/day_3/day3_1.py
663
3.53125
4
if __name__ == '__main__': with open('data.txt', 'r') as f: lines = [line.strip() for line in f.readlines()] total_width = len(lines[0]) total_height = len(lines) height = 0 width = 0 answer = 0 while height < total_height: try: i...
056615a7cac4d1b22fff3c786a459b9cc2e20d20
404-html/coursework
/Extreme Computing/EXC-CW1-stuff/task4-reducer.py
386
3.5
4
#!/usr/bin/python import sys prevline = "" linecount = 0 #Basically same stuff in task 2 for line in sys.stdin: line = line.strip() if (prevline != line): if linecount > 0: print("{0}\t{1}".format(prevline,linecount)) prevline = line linecount = 1 else: lineco...
36eb1a8f833c5f7006d2aed10112c424df30e41b
mdallow97/InterviewPrep
/Arrays/matrix_spiral.py
674
3.578125
4
# matrix_spiral.py def matrixSpiral(matrix): result = [] while matrix: # go right for item in matrix.pop(0): result.append(item) if not matrix or not matrix[0]: break # go down i = len(matrix[0])-1 for j in range(len(matrix)): result.append(matrix[j].pop(i)) if not matrix: break # go le...
c24776f4330ee2ec2db63413e9ec3ead2b3157c2
pb0528/codelib
/Python/lesson/range_test.py
240
3.703125
4
#Range(begin,end,step) 范围内按照补偿递增 按照[,)方式递增 for i in range(1,100): print(i) for i in range(100,0,-1): print(i) #while 与C++大致相似 sum,num = 0,2 while num<100: sum+=num num+=2 print(sum)
a1c9585367e48719ed7e048a42264140ed78e68d
frontendcafe/py-study-group
/ejercicios/CodeWars/AmitSna/are_arrow_functions_odd.AmitSna.py
114
3.515625
4
odds = lambda nums: [num for num in nums if num%2==1] def odds(nums): return [num for num in nums if num%2==1]
d49308677232fe4ac4a45ec769035bddbffbd26d
roque-brito/ICC-USP-Coursera
/icc_pt1/exe_extras/objetos_na_memoria_ex1.py
2,196
3.984375
4
# lista de temperaturas # Qual o dia das temperaturas mais baixa e mais alta: def MinMax(temperaturas): print('A menor temperatra do mê foi: ', minima(temperaturas), '°C') print('A maior temperatra do mê foi: ', maxima(temperaturas), '°C') def minima(temps): min = temps[0] i = 0 while i...
2c1bd67e90dce07adcee512e6a8a989f2742508a
shahramg92/Class-Exercises
/Week-1/Python-Exercises-1/madlib.py
146
4.15625
4
name = input("What is your name?") subject = input("What is your favorite subject?") print("{0}'s favorite subject is {1}".format(name, subject))
01483b5d0688a0c92474c6a46483a260ef863881
ceuity/algorithm
/boj/python/1978.py
436
3.53125
4
if __name__ == '__main__': n = int(input()) prime_list = list(map(int, input().split())) count = 0 flag = 0 if n == len(prime_list): for i in prime_list: if i == 1: continue for j in range(1, i + 1): if i % j == 0: ...
bcec382d31e81523e3388b3b999584cde8b536d6
rpotter12/learning-python
/section3: python statements/3-whileLoops.py
591
4.03125
4
# while loops will continue to execute a block of code while some conditions remains true # a while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition # SYNTAX # while some_boolean_condition: # code x=0 while x<5: print(f'x: {x}') x=x+1 # print ...
ee3c84095a4fb5fb2fe454f4a40a6cd207935aac
Lmineor/Sword-to-Offer
/bin/22.py
368
3.546875
4
class Node: def __init__(self,data,_next = None): self.data = data self._next = _next def __repr__(self): return str(self.data) def ChainTable(Head,index): num = [] root = Head while root: num.append(root) root = root._next if index > len(num): re...
0ef5ab05c9bd487301a5d0bd404f5dc1d356106d
Ewenwan/Algorithms-2
/Cantor expansion/应用_字符串比大小.py
1,287
3.5625
4
""" 现在有"abcdefghijkl”12个字符,将其所有的排列中按字典序排列,给出任意一种排列,说出这个排列在所有的排列中是第几小的? eg: input: 第一行有一个整数n(0<n<=10000); 随后有n行,每行是一个排列; 3 abcdefghijkl hgebkflacdji gfkedhjblcia output: 输出一个整数m,占一行,m表示排列是第几位; 1 302715242 260726926 """ from functools import reduce # 阶乘计算1 def factorial(n): return reduce(lambda x,y: x*y, (x for x...
02c308555c43402f2e16cec5ad7af2124e216ffb
bolod/bioEuler
/src/OLD/BioTree.py
2,418
3.546875
4
class BioTree(): def __init__(self, bio_node, parent=None): self.bio_node = bio_node self.parent = parent if (bio_node != None): self.left = BioTree(None) self.right = BioTree(None) def __repr__(self): return str([str(value) for value in self.vectorialize...
2976abf84df765e48f3fe44b07131d77c0ac175d
syurskyi/Python_Topics
/095_os_and_sys/examples/ITVDN Python Essential 2016/00-read_file.py
804
3.9375
4
"""Пример открытия файла для чтения""" def read_file(fname): """Функция для чтения файла fname и вывода его содержимого на экран """ # Открытие файла для чтения file = open(fname, 'r') # Вывод названия файла print('File ' + fname + ':') # Чтение содержимого файла построчно for line in file: # Вывод ...
a5d4f12f5fd533109924ce58b7bc18835e868693
Samboy218/6903-Tools
/AES/encrypt.py
2,246
3.671875
4
#Author: Will Johnson #Date: 11/20/18 #project: AES tool #Use Case: Encrypt/Decrypt large strings with AES #!/usr/bin/python import sys import bitWise import binConv #substitutes a matrix of bytes with another matrix of bytes #This function can be changed. It just has to do the inverse of #the sub bytes in the dec...
7ac2e2a9f5dfe686b7046b5e44267dfc00f2c06b
naraekwon/CodingInterviewMastery
/ds_algos_primer/python/heaps.py
4,617
4.375
4
""" Title: Heap Solutions This file contains the template for the Heap exercisess in the DS & Algos Primer. If you have not already attempted these exercises, we highly recommend you complete them before reviewing the solutions here. """ from queue import PriorityQueue from typing import List """ Exercise 1.1: Imple...
722bbcd33295b622712cdbb37f4ac3532da0da47
firoza90/leetcode
/linked_list_reverse.py
806
4.125
4
""" https://leetcode.com/problems/reverse-linked-list/ Given the head of a singly linked list, reverse the list, and return the reversed list. """ from linked_list import ListNode, createList class Solution: def reverseList(self, head: ListNode) -> ListNode: if not head: return head pt...
523c53d9120b52c29b4b34230256a225b3b7ea47
lxjthu/uband-python-s1
/homeworks/B21562/homework-14item/homework08.py
1,222
3.78125
4
#!/usr/bin/python # -*- coding: utf-8 -*- # @author: xxx def main(): tup = (1,2,3,4) #取值 print tup[2]#记得这里要打中括号[],和列表一样下标从0开始,不能同时取两个0,1,想要同时取多个值只能用切片 # 切片 print tup[0:1]#切片左边是闭区间,右边是开区间,即右边的实际取值会比写出来的下标少一位 print tup[2:]#右边什么都不写,默认取到最后一位 print tup[:3]#左边什么都不写,默认从第一位开始数 # 是否存在某值 print (1 in tup) #存在,...
bc992a4c79d7a6f3886e7078baabf10bff455cb8
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_118/1949.py
1,630
3.734375
4
import math from time import time, clock INPUT_FILE = "./input3.txt" RESULT = "" fair_cache = {} square_cache = {} def is_fair(number): return number == int(str(number)[::-1]) def is_fair_cached(number): if number in fair_cache: return fair_cache[number] fair_cache[number] = is_fair(number) ...
39e1a9ebad70ba5a060ae7e279af91ec35941b32
Pluppo/pynet-lessons
/examples/time_test.py
186
3.828125
4
#! /usr/bin/env python3.6 import time start_time = time.time() #Test: time.sleep(1.2) elapsed_time = time.time() - start_time print('Time elapsed: {} seconds'.format(elapsed_time))
caae45f27d2c652abdbe3bc9ef3bfb60b2c87f22
bh107/bohrium
/bridge/bh107/bh107/util.py
574
3.546875
4
# -*- coding: utf-8 -*- """ ======================== Useful Utility Functions ======================== """ import operator import functools def total_size(shape): """Returns the total size of the values in `shape`""" return 0 if len(shape) == 0 else functools.reduce(operator.mul, shape, 1) def get_contiguo...
3433b72eab28b3ae2d520572593548d611a84717
nirmal2209/HackerRank
/Python/16) Numpy/Array Mathematics.py
1,556
3.84375
4
""" Basic mathematical functions operate element-wise on arrays. They are available both as operator overloads and as functions in the NumPy module. import numpy a = numpy.array([1,2,3,4], float) b = numpy.array([5,6,7,8], float) print a + b #[ 6. 8. 10. 12.] print numpy.add(a, b) ...
f476f22cffb67b686135728a49db035225e82b86
Lmineor/Sword-to-Offer
/bin/38.py
524
3.6875
4
def Permutation(string,i): if string == None: return if string[i] == '\n': print(''.join(string[:i])) else: for j in range(i,len(string)-1): string[j],string[i] = string[i],string[j] #将前面的字符依次与后面进行交换 Permutation(string,i+1) ...
8693e877aeee9e5214174782d619e4efef6c6e45
PJC-1/data_structures_and_algorithms_in_python
/Data_Structures/Linked_List/sort_linked_list.py
885
3.953125
4
class Node: def __init__(self, value): self.value = value self.next = None def __repr__(self): return str(self.value) class SortedLinkedList: def __init__(self): self.head = None def append(self, value): """ Append a value to the Linked List in ascendin...
87f35c3e2f979316f9e9398f4e39145daa47be3e
MarkMeretzky/Python-INFO1-CE9990
/monkey1.py
1,130
3.9375
4
""" monkey1.py Demonstrate how they programmed before they invented lists. """ import sys while True: try: year = input("Please type a year: ") except EOFError: sys.exit(0) try: year = int(year) except ValueError: print(f"Sorry, {year} is not an integer.") con...
54a999f95764e416c5b0ecd6637fc93b36ebc7ac
lxw15337674/Language_learning
/python/basic_gramma/IO/serialize.py
1,448
4.09375
4
#serialize (序列化) """变量从内存中变成可存储或传输的过程称之为序列化 序列化之后,就可以把序列化后的内容写入磁盘,或者通过网络传输到别的机器上。 反过来,把变量内容从序列化的对象重新读到内存里称之为反序列化,即unpickling。 Python提供了pickle模块来实现序列化。""" import pickle d = dict(name='bob',age=20,score=88) print(pickle.dumps(d)) """pickle.dumps()方法方法把任意对象序列化成一个bytes,然后,就可以把这个bytes写入文件。 或者用另一个方法pickle.dump()直接把对象序列化后写入一个...
e40840c3cd2944a69adefd48829117eca6ab84bc
PdxCodeGuild/class_emu
/Code/Larry/python/lab11_v3_simple_calculator.py
1,751
4.28125
4
# filename: lab11_v3_simple_calculator.py ''' Lab 11: Simple Calculator Let's write a simple REPL (read evaluate print loop) calculator that can handle addition, subtraction, multiplication, and division. Ask the user for an operator and each operand. Don't forget that input returns a string, which you can convert to ...
851eac30fa710a86684ac28dcd38d3ff0e5ca966
gabrielavirna/python_data_structures_and_algorithms
/my_work/ch10_design_techniques_&_strategies/dijkstra_shortest_path_greedy.py
4,870
4.125
4
""" Dijkstra's shortest path algorithm ----------------------------------- - a greedy algorithm; it finds the shortest distance from a source to all other nodes or vertices in a graph. The worst-case running time: O(|E| + |V| log |V|), where |V| is the number of vertices and |E| is the number of edges. """ # Dijkstra...
a41d39d67fcc8e3922a916d9acea42a69e5dbc90
YashCK/Python_Basics
/String_Slices.py
825
4.28125
4
# String Index # Python indexes the characters of a string, every index is associated with a unique character. # For instance, the characters in the string ‘python’ have indices: # The 0th index is used for the first character of a string. Try the following: s = "Hello Python" print(s) # prints whole string pri...
37b6bfab93d848acc859149990719e002eee5d71
thomas-vanderwal/Python_101
/Section_2/time_module.py
370
3.859375
4
import time #ctime function will convert a time in seconds since the epoch is a string representing local time print(time.ctime()) print(time.ctime(1384112639)) #sleep function allows us to suspend execution of scripts a given number of seconds for x in range(5): time.sleep(2) print('Slept for 2 seconds') p...
b70c5290c73dc3cf2562a5db81a8d0be05956997
NikeSmitt/python_main_course
/hw1/task3.py
2,142
3.875
4
# 3. Узнайте у пользователя число n. Найдите сумму чисел n + nn + nnn. # Например, пользователь ввёл число 3. Считаем 3 + 33 + 333 = 369 def task3_amend(user_input): value = int(user_input) result = 0 candidate = 0 for n in range(3): candidate *= 10 candidate += value result +...
1b42a099f5cd26c5183ba169f363c1de74242702
Lei-Tin/OnlineCourses
/edX/MIT 6.00.1x Materials/n^c and c^n.py
237
3.671875
4
# -*- coding: utf-8 -*- """ Created on Sun Mar 14 21:11:55 2021 @author: ray-h """ from time import sleep c = 2 n = 0 while True: n += 1 print('c^n = ' + str(c**n)) print('n^c = ' + str(n**c)) sleep(1)
ba0f3a2c609a3700739962f9342112f11bd2eba1
glredig/bioinformatics
/gc_count.py
696
3.65625
4
def gc_count(): """Basic GC Count function """ a = 0 t = 0 g = 0 c = 0 type = raw_input("Please enter the data entry type (1=txt file, 2=direct entry): ") if type == "1": filename = raw_input("Please enter the path to the txt file: ") file = open(filename, "r") dna = file.read() else: dna = raw_input(...
c8e33907b8a4cc5f92122e8f36e54c0827e71660
amittewari31/Python
/Web Development/Python/Regular expression.py
985
3.78125
4
import re patterns = ['term1', 'term2'] text = 'this is the string with term1, and not the other' for pattern in patterns: print('I am searching for ', pattern) if re.search(pattern, text): print('MATCH') else: print('DID NOT MATCH') # ===================================================...
63ae812001a1cc2884be9d2aa936baed893b16df
SimeonTsvetanov/Coding-Lessons
/SoftUni Lessons/Python Development/Python Fundamentals June 2019/Problems and Files/12. EXAM PREPARATION/Exam Preparation 1/01. Sino the Walker.py
2,415
4.40625
4
""" Basics OOP Principles Check your solution: https://judge.softuni.bg/Contests/Practice/Index/967#0 SUPyF Exam Preparation 1 - 01. Sino the Walker Problem: Sino is one of those people that lives in SoftUni. He leaves every now and then, but when he leaves he always takes a different route, so he needs to kn...
54a343d7282facc42d64bfcc73f301ddbac9480a
rafaelperazzo/programacao-web
/moodledata/vpl_data/59/usersdata/149/40379/submittedfiles/testes.py
97
3.796875
4
# -*- coding: utf-8 -*- import math i=int(input('digite i:')) while i<10: print(i) i=i+1
92f699c3be6b158af1c30931e0303d71614fc715
stormchasingg/leetcode-desktop
/fibonacci.py
601
3.546875
4
# generator for fibonacci & Yanghui triangles def fib(max): n, a, b = 0, 0, 1 while n < max: yield b a, b = b, a + b n = n + 1 return 'done' def triangles(): n = 0 yield [1] prev = [1, 1] yield prev while n < 100: res = [1] * (n + 3) for i in range(len(res)): if i == 0 or ...
58c5c1784498c9b1c805cc5cba1a601ba9d1bc0c
kyoder17/pythonIQT
/lab3e_fibonacci.py
616
4.03125
4
""" CPT Klye Yoder Lab3e Fibonacci 07 Sept 2018 """ def fib(c): if c<=1: return c else: return fib(c-1)+fib(c-2) n=raw_input("Enter a number for Fibonacci ") while(True): try: n=int(n) break except ValueError: n=raw_input("Please enter an integer: ") ...
3c2f853503beabbdcd8290ece996e804f6e0fb48
fqx9904/Python_Game_Autoplay_Strategy--CSC148
/Labs/lab2/grade.py
3,614
3.953125
4
""" grade module """ from typing import Any class GradeEntry: """Represent a general entry with student grade information. course_id - a course iddentifier in which the grade earned weight - credit weight of the course grade - no value until we know whether numeric or letter value is used """ ...
bfb7f6bb209dcf90a2dc2c320b48f462d3de14b4
quocphan95/np-trend-detection
/activations.py
649
4.28125
4
import numpy as np """ Activation functions Each class contains 2 class function: calc: calculate the output from the input derivative: calculate the derivative of the output w.r.t the input """ class Relu: @classmethod def calc(x): return (x>0).astype(np.int32) * x @classmethod def deriv...
ee96c539fdaad60c066a17cf98d8e3beb6c3ce3a
vamshireddy08/python-practice-programs
/build_in_functions.py
1,001
3.625
4
def count_match_index(l): inc=0 for count,val in enumerate(l): if count==val: inc=inc+1 print inc count_match_index([0,2,2,1,5,5,6,10]) def d_list(l): d={} for count,ele in enumerate(l): d[ele]=count print d d_list(['a','b','c']) def concatenate(l...
948f1fe483d51b3cf21fb95c33ee6b11e40511f6
xyzhangaa/ltsolution
/MultiplyStrings.py
638
3.703125
4
###Given two numbers represented as strings, return multiplication of the numbers as a string. ###Note: The numbers can be arbitrarily large and are non-negative. # Time: O(m * n) # Space: O(m + n) def MultiplyStrings(A,B): if A == '0' or B=='0': return '0' A = A[::-1] B = B[::-1] arr = [0 for _ in range(le...
377e320020ac0816d64a13bcbcb1900ef73710ae
jinammaheta/python
/practicals/11.py
338
3.5
4
import math a,b,c=map(int,input("Enter Coefficients a,b,c\n").split()) d=(b*b)-(4*a*c) if d==0: print("Both roots are same") r=-b/2*a print("Root is:r={}".format(r)) if d<0: print("No Roots") if d>0: r1=(-b+math.sqrt(d))/2*a r2=(-b-math.sqrt(d))/2*a print("Roots are:r1={} , r2={}...
8597d1f6c96c30fef134e75566e112b259a33157
lettucemaster666/Python3_Bootcamp
/control_flow.py
3,178
4.40625
4
""" Purpose -------- Introduction to Control Flow Summary ------- Introduces if, elif, else statements to control conditions of code. Operators will be introduced in evaluating true or false of the control flow statements. Structure of condition statement -------------------------------- if something_is_true: ...
f8cd435bb4eb1f693117ddec64c25f1d41f744f4
rm-hull/charlotte
/sweetie.py
464
3.515625
4
#!/usr/bin/env python import wiringPy import time wiringPy.setup() for pin in range(0,8): wiringPy.pin_mode(pin, 1) wiringPy.digital_write_byte(255) print "whats your name?" name = raw_input() print "hello " + name doubles = [1,2,4,8,16,32,64,128] snooze = 0.1 while (True): for no in doubles: wiringPy.digita...
0e82f387cb38568a32084f8236f291119d6274e9
aayush-bhardwaj/CodeTo500
/Code001_SwapCase.py
1,139
4.0625
4
#DAY04_21DEC2016_Code001.py ''' NOTES : 1. help(str.istitle()) - The terminal help opens up 2. istitle() - Check if a string is camel case 3. upper() - convert to upper case 4. lower() - convert to lower case 5. isupper() - check if a string is in uppercase 6. islower() - check if a string is in lowercase 7. split a...
bb981155f8617643edcc6cb37e86705390ff34ae
mfisher29/innovators_class
/Class6/application1/lesson006.py
7,497
3.9375
4
print("Going through the data structure....") import json json_file = 'death.data' contents = open(json_file,'r').read() json_data = json.loads(contents) columns = json_data['meta']['view']['columns'] column_names = [col['name'] for col in columns] data_columns={col["name"]:col for col in columns if col.has_key("tab...
e7cfdb32b49e498d4a12596555801b6ef78f54f5
sunjiebin/s12
/week7/02类组合使用.py
2,010
3.71875
4
#!/usr/bin/env python # Python version: python3 # Auther: sunjb '''我们可以直接在构造函数里面将一个实例化的对象传进去, 这样就相当于实现了类的继承,这对于多个参数不同的函数继承 是很有用的''' class School(object): def __init__(self,name,addr): self.name=name self.addr=addr self.students=[] self.teacher=[] self.staffs=[] def enroll...
69b0d44bc5e428139e13160dc4721e62a780c5d8
tafarib1/python-caveiratech
/aula5.py
228
3.921875
4
numero = input('coloque o numero de pessoas da festa:') pessoas = 0 lista = [] while pessoas <= int(numero): pessoa = input('coloque o nome de quem vai: ') pessoas += 1 lista.append(pessoa) for i in lista: print(i)
47e8e9dde6d1aa16abcf9fe5e569e446bb010568
sofiadurkan1/ITF-Fundamentals
/python/class_notes/2021_05_24_FILES/reading_files.py
2,279
3.953125
4
""" import os os.system("cls") my_file = open("first_file.txt") # this syntax opens a 'txt' file print(type(my_file)) print() print(my_file) my_file.close() """ """ import os os.system("cls") my_fie = open("fishes.txt", 'r') print(my_fie.read()) # displays the entire text content my_fi...
280a6e7ba31047f5cd1eab441fed2f3a313681c4
DevanshiPatel12/PythonAssignmentCA2020
/Task-6/Qn-2.py
517
4.34375
4
# Define a class named Shape and its subclass Square. # The Square class has an init function which takes a length as argument. # Both classes have an area function which can print the area of the shape where Shape’s area is 0 by default. class Shape: Area = 0 def Area(self): return 0 class Square(Shap...
c7e09631a54d836401b15228f1312e388fb0d86b
anishmarathe007/Assignment
/test_palindrome.py
713
3.765625
4
import unittest from palindrome import isPalindrome, reverseString class TestPalindrome(unittest.TestCase): def test_for_revFunction(self): self.assertEqual(reverseString('anish'),'hsina') self.assertEqual(reverseString('1'),'1') self.assertEqual(reverseString('12321'),'12321') ...
6a7a9a5315bd6ea7387985f7a1de98f6febe6a8a
muhammad-masood-ur-rehman/Skillrack
/Python Programs/zigzag-pattern-start-with-base-program-in-python.py
946
4
4
ZigZag Pattern - Start with Base Program in Python ZigZag Pattern - Start with Base: Two positive integer values X and Y are passed as input to the program. The program must print the output based on X and Y values as shown in the Example Input/Output section. Boundary Condition(s): 1 <= X, Y <= 1000 Input Format: The...
0b297be71b7e9b9e721445781bf984d35faaff68
Krokette29/LeetCode
/Python/4. Median of Two Sorted Arrays.py
4,176
4.15625
4
class Solution: """ There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). You may assume nums1 and nums2 cannot be both empty. Example 1: nums1 = [1, 3] nums2 = [2] ...
1f88005cef7d4943688f6beb2776d50a9004ace0
jeff-ceiling-zero/git-demo
/fizzbuzz.py
493
3.828125
4
def generate_list_of_numbers(): return range(1, 100) def num_to_fizz_string(number): if number % 3 == 0 and number % 5 == 0: return 'FizzBuzz' if number % 3 == 0: return 'Fizz' if number % 5 == 0: return 'Buzz' return str(number) def run_fizz_buzz(): numbers = gener...
d6fc864140420cd4ceae915368b91b687d7950c4
nalwayv/bitesofpy
/bite_119/bite_119.py
1,187
4.09375
4
""" Bite 119. Xmas tree generator """ from typing import List def generate_xmas_tree(rows=10) -> List[str]: """Generate a xmas tree of stars (*) for given rows (default 10). Each row has row_number*2-1 stars, simple example: for rows=3 the output would be like this (ignore docstring's indentation):...
71c4cc9fbac92125e33c56541860764f2343701b
BRGoss/Treasure_PyLand
/Puzzles/Completed/reverse_words.py
406
4.4375
4
#DESCRIPTION: Reverse the words in a sentence rather than all letters #ALGORITHM: Define a function called split_words that takes a string # as its input. The output is the inputs words put in reverse # order. #Example: Input = 'A long long time ago' Output = 'ago time long long A' def sp...
851e575ed87159b3a755753d4d07fb2dfd42dce3
garne041/phData_interview
/source_code.py
16,749
3.640625
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn.linear_model import LogisticRegression from sklearn.metrics import classification_...
4b43f9ec035c211a09d94bc6d73f894cefe082d0
abiraja2004/IntSys-Sentiment-Summary
/optimization/mcmc_optimize.py
2,152
3.734375
4
import numpy as np ''' See: https://en.wikipedia.org/wiki/Stochastic_tunneling, which can be performed by correct choice of f and accept_prob_func f(X, s), where X is a matrix whose rows are inputs, returns y, s', where y[i] = f(X[i], s[i]), and s'[i] is the "state" of f (s can be None if not needed by f) given for t...
e92bcae027bd4a65f022242f5eb8e7453a7477f1
aqing1987/s-app-layer
/udacity/ml-engineer-basic/accessing-file-and-network/scripting/read-write-files/test-read-with-int.py
289
3.609375
4
# if you pass the read method an integer argument, it will read up to that # number of characters, output all of them, and keep the 'window' at that # position ready to read on. with open('./camelot.txt', 'r') as song: print(song.read(2)) print(song.read(8)) print(song.read())
c3211b35fe1e4c519995604650626f2d4c3ccd90
Legolas1086/bug_bounty
/find_previous_better/find_previous_better.py
555
3.546875
4
def previousBest(n,ranks): stack = [] previous_greater = [] for i in range(n): while stack: if stack[-1] > ranks[i]: previous_greater.append(stack[-1]) break else: stack.pop() if not stack: previous_greater...
1df8704a6a1def80be918990bab83752c3338e87
frestea09/latihan-python-november
/src/inputBilanganRill.py
372
3.78125
4
from __future__ import print_function def main(): bilanganPertama = float(input('Bilangan Pertama : ')) bilanganKedua = float(input('Bilangan Kedua : ')) hasil = bilanganPertama * bilanganKedua print('Bilangan Pertama : %f'%bilanganPertama) print('Bilangan Kedua : %f'%bilanganKedua) print('Hasi...
6964db8c6a407006d1aea29c1833598ee7196e15
MineRobber9000/aaf_elo
/predict.py
397
3.765625
4
import forecast team = input("Team?: ") opponent = input("Opponent?: ") winner,confidence = forecast.forecast(team,opponent) if not winner: print("I expect a tie!") elif winner==team: print("The {} are gonna blow the {}'s socks off!".format(team,opponent)) else: print("The {} are gonna blow the {}'s socks off!".f...
be8aa89d4d7b2526493012c4eb35486bff5e58fb
maleks93/Python_Problems
/prblm_56.py
2,337
3.78125
4
# https://leetcode.com/problems/merge-intervals/description/ # Time complexity: O( N*log(N) ) # Space complexity: O( N ) class Solution(object): def merge(self, intervals): """ :type intervals: List[List[int]] :rtype: List[List[int]] """ temp = self.sort(intervals)...
ce313252b917a9bdc2f9391a69887f0204b1eb6c
developersage/PythonProjects
/password-manager-start/main.py
4,093
3.578125
4
from tkinter import * from tkinter import messagebox from random import choice, randint, shuffle from pyperclip import copy import json import string import pandas as pd # try: # df = pd.read_csv("data.csv") # except FileNotFoundError: # df = pd.DataFrame(columns=["Website", "Email/Username", "Password"]) # ...
07bef416f4aa3426157b69dfda6d31b7ba553028
jw1121/RestCRUD
/market/sqlite.py
1,267
3.53125
4
import sqlite3 class MarketModel(object): def __init__(self, database="../docs/market.db"): self.database = database self.conn = sqlite3.connect(self.database) self.cur = self.conn.cursor() def insertMarket(self, data): sql_str = ("INSERT INTO market({0}) VALUES('{1}')").for...
7e5a5e63755b4a9e24bfb7d8a0ac7d1c04f5c27e
LeoImenes/SENAI
/1 DES/FPOO/Exercicios1/10.py
174
3.75
4
a=int(input("Digite o valor da área a ser revestida em m²: ")) v=13 m=0.37 p=a/m t=p*v print("Será necessario {} kg de pedra mineira e custará {:.2f} reais".format (p,t))
517de7e19a8fa1ac38f9b25365564799d1633b99
jinxinbo/base-model
/pycode set/4/U_smart.py
142
3.578125
4
def cal(sum,*args): print(type(args)) print(args) for i in args: sum=sum+i**2 return sum asum=cal(2,2,3,4) print(asum)
01732a9444f6c59679d4f2f07da649ee5013290e
henokalem/teamge
/user/josh/currentlyUseless/Turnout.py
1,836
3.71875
4
import RPi.GPIO as GPIO import time # Class for controlling class Turnout: # Constructor def __init__(self, turnout_id, straight_pin_num, turn_pin_num): self.turnout_id = turnout_id self.straight_pin_num = straight_pin_num self.turn_pin_num = turn_pin_num self.current_state = "s...
68c67d60e3f398e1678a325dab5066073a00f2c6
shraysidubey/pythonScripts
/DFS.py
933
3.71875
4
class Graph: def __init__(self,node): self.graph = [] for i in range(node): self.graph.append([]) def addEdge(self,source,destination): self.graph[source].append(destination) def DFS(self,s): print("DFS") visited = [False] * (len(self.graph)) sta...
4406ce6ab7eacce83daa6ad6a8696db8a41c510c
FrankUSA2015/Leetcode-algorithm
/Valid Parentheses.py
965
3.953125
4
# -*- coding: utf-8 -*- #题目见:https://leetcode-cn.com/problems/valid-parentheses/ #解答思路: # https://leetcode-cn.com/problems/valid-parentheses/solution/zhu-bu-fen-xi-tu-jie-zhan-zhan-shi-zui-biao-zhun-d/ #解法: # 利用入栈和出栈的方法,实现对括号的比较。 #学到的知识: # 可以利用list来模拟栈,出栈用list自带的函数pop(),入栈用append() # i in str_dict,可以判断i这个关键词是否在字典中。 cla...
09a53f4fe5c9c0cefef0a648f180100090854e84
Farheen2302/ds_algo
/algorithms/dp/word_break.py
1,630
3.984375
4
# Refer : # http://www.geeksforgeeks.org/dynamic-programming-set-32-word-break-problem/ def check_word(dictionary, word): if len(word) == 0: return True for i in range(len(word)): prefix = word[:i + 1] suffix = word[i + 1:len(word)] if prefix in dictionary and check_word(dictionary, suffix): return True ...
084662764764b78c4e5da745c991bd4ee8e3b0c3
nnhamoinesu22/Python-Challenge
/PyPoll/main.py
1,579
3.609375
4
import os import csv election_data = os.path.join('02-Homework','03-Python','Instructions','PyPoll', 'Resources', 'election_data.csv') election_data_csv = "election_data.csv" #election_analysis = os.path.join("analysis", "election_analysis.txt") total_votes = 0 candidate_name = "" candidate_votes = {} candidate_perc...
5d9d903093addac7fb833abde3624228b6e12890
jeremypedersen/pythonBootcamp
/code/class5/dictionary_functions.py
422
4.4375
4
# You create a new dictionary like this d = {} # You can add new items like this d['bananas'] = 5 d['apples'] = 2 d['oranges'] = 'we have no oranges' print(d) # You can use regular functions like "len", "min", and "max" # like you did for lists, but remember these functions will # look at the KEYS (item names) in t...
039797c9cb7273d832bb35561c9d408d8dfb91d3
kira-Developer/python
/062_Function_Scope.py
386
3.9375
4
# -------------------- # -- Function Scope -- # -------------------- x = 1 # global Scope def one(): global x x = 2 print(f'print variable from function scope {x}') def two(): x = 4 print(f'print variable form function scope {x}') print(f'print variable from global scope {x}') one() two() print(f...
75f203ba0dda0ca8b08b67a584a1dab618a6dfc1
pratikgchaudhari/python-demo
/testing/test_cities.py
550
3.59375
4
import unittest from city_functions import get_formatted_name class NamesTestCase(unittest.TestCase): """Tests for 'city_functions.py'. """ def test_city_country(self): formatted_name = get_formatted_name("New York","United States") self.assertEqual(formatted_name,"New York, United States") ...
12b57a9c20f6d14d2cd1b53cd1bd7d49e3b20f34
UA83/LibrarySystemCA2
/mixed.py
922
3.703125
4
from Book import Book list_of_book = [Book('10', 'Python BG', '2019', '123456789123', 'Ulisses Alves'), Book('20', 'Python MT', '2018', '987654321987', 'Stephanie Enders'), Book('30', 'Python AA', '2019', '143567833456', 'Suki Dog')] #display all books #add book id, title, year, isbn...
d298ac5f9a020affa54bb08bcc55c837d7d31ad9
fernandoseguim/python_excript
/instruction_break.py
210
3.765625
4
print("Início da execução do laço") i = 0 while(i < 10): i = i + 1 if (i % 2 == 0): continue print("o número %d é impar" %i) else: print("else") print("fim da execução laço")
adfeef6dddf767359953a830abdf46f27add4862
nhatsmrt/AlgorithmPractice
/LeetCode/205. Isomorphic Strings/Solution.py
609
3.71875
4
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: # Time and Space Complexity: O(N) bimap = Bimap() for i in range(len(s)): if not bimap.put(s[i], t[i]): return False return True class Bimap: def __init__(self): self.forward,...
5448334fd7a1312cd047ccc3ce4d6d930ba3e15b
h-ohsaki/dtnsim
/dtnsim/mobility/levywalk.py
2,056
3.578125
4
#!/usr/bin/env python3 # # A mobility class for Levy walk. # Copyright (c) 2011-2015, Hiroyuki Ohsaki. # All rights reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 ...
80962f364c29a47d2b388d727562152b121a48f3
nosaj-xqr/leetcode
/110. 平衡二叉树.py
870
3.765625
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None ''' 讨论区题解分析: 1、使用self.res创建全局变量 2、之所以要新定义一个函数,是因为此函数要用来返回最大值,保证递归的正常执行,而最终结果为布尔值,要根据递归过程中的结果来判定, 这也是为什么设置全局变量的用意 ''' class Solution: def isBalanced(self...
a979c04321718921ed62645d3ab4084ee417d12d
jiaweiyu2009/flightServiceApp
/test.py
1,602
3.75
4
class Flight: def __init__(self, fid=-1, dayOfMonth=0, carrierId=0, flightNum=0, originCity="", destCity="", time=0, capacity=0, price=0): self.fid = fid self.dayOfMonth = dayOfMonth self.carrierId = carrierId self.flightNum = flightNum self.originCity = originCity se...
1cb682f05f7f70673a557db097c8d9feb9fef7bf
tobinSen/python01
/python01/myFirstPython.py
653
4.5
4
""" 1.定义变量 语法:变量名 = 变量值 2.使用变量 3.看变量的特点 """ # 定义变量:存储数据TOM my_name = 'TOM' print(my_name) # 定义变量 schoolName = '黑马程序员,我唉Python' print(schoolName) """ 1.验证数据到底是什么类型 """ num1 = 1 num2 = 2.2 # int print(type(num1)) # float print(type(num2)) # str 单引号和双引号都可以 a = 'hello world' print(type(a)) b = True print(type(b)) c = [1,...
e3ac8af3d1df8ad76f2882be2357e105a4132948
zkevinbai/LPTHW
/ex48.py
413
4.34375
4
stuff = raw_input('> ') words = stuff.split() first_word = ('verb', 'go') second_word = ('direction', 'north') third_word = ('direction', 'west') sentence = [first_word, second_word, third_word] """This is just an example, but that's basically the end result. You want to take raw input from the user, carve it into wo...
9a98ec2cb098dc9ff3443897032599504a4c8223
austburn/advent-of-code-17
/4/anagrams.py
997
4
4
import sys def anagram(a, b): if len(a) != len(b): return False matches = 0 for letter in a: try: b.index(letter) except ValueError: return False else: matches += 1 return matches == len(a) def has_anagrams(phrase): for i, p i...
f734417e2b85abbc67197a34d7b2c5d1f38421cd
saubhagyav/100_Days_Code_Challenge
/DAYS/Day20/Sort_Dictionary_Keys_and_Values_List.py
275
3.859375
4
def Sort_Keys_and_Values(Test_dict): return {key: sorted(Test_dict[key]) for key in sorted(Test_dict)} Test_dict = {'Code': [7, 6, 3], 'Challenge': [2, 10, 3], 'is': [19, 4], 'Best': [18, 20, 7]} print(Sort_Keys_and_Values(Test_dict))
00092bc605bd33fd1fde3539a2e94bc72754ea92
Flood1993/ProjectEuler
/p108.py
3,147
3.53125
4
# yn + xn = xy # given some n, how do we calculate how many solutions are there? # n = xy / (x+y) # Let's say n = 4 # there are 3 solutions # 5,20 # 6,12 # 8,8 # x, y, n >= 0 # n=6. how many solutions? # how many x, y, exist so that x*y/(x+y) == 6? # x*y must be a multiple of n # How many are there for n=7...
30f651179204f233190ebdbd7b79dd62678db72c
Krenair/cryptopals
/set2/challenge9.py
306
3.75
4
def pad(pt, block_length): padding_length = block_length - (len(pt) % block_length) return pt + (padding_length * chr(padding_length).encode('ascii')) if __name__ == "__main__": input = b"YELLOW SUBMARINE", 20 output = pad(*input) print('output', output) print('len', len(output))
76268472a17fe750a6406dfc5a05165e3055b489
vikramlance/Python-Programming
/Leetcode/problems/problem0102_binary_tree_level_order_traversal.py
1,198
4.09375
4
""" Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). For example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its level order traversal as: [ [3], [9,20], [15,7] ] """ from collections import deque...
fe20f74ca7e554b8f23166297c379a59a822d0e3
lshicks13/adventofcode2019
/day3.py
1,880
3.625
4
#Read in the directions from the file and separate them into 2 paths def get_paths(txtfile): with open(txtfile) as f: f = f.read().splitlines() path1 = f[0].split(',') path2 = f[1].split(',') return path1, path2 # Get all the points from the given paths def get_points(path): step ...