blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
efdf2c9e99d32e24ba5db7f4e5beeb96bf89131c
yaolizheng/leetcode
/236/lca.py
608
3.859375
4
from tree import TreeNode def lca(root, a, b): if not root or root.value == a or root.value == b: return root l = lca(root.left, a, b) r = lca(root.right, a, b) if l and r: return root return l if r is None else r if __name__ == '__main__': root = TreeNode(3) root.left = ...
45207aafb93e656a25202e61fc18a0bd5660ca84
garandria/bijective-image-transformation
/src/imageT.py
3,552
3.640625
4
""" """ from math import gcd from PIL import Image from transformation import * class imageT: """ Image processing for bijective transformation class """ def __init__ (self, image, fct_transformation, fname="transformated"): """ Builds the object :parameter: an image ...
8c76a4049565ca4f345e9e9034ff1391455f5055
Aye-Aye-Dev/AyeAye
/lib/ayeaye/pinnate.py
8,903
3.6875
4
import json class Pinnate: """ Dictionary or attribute access to variables loaded either from a JSON string or supplied as a dictionary. >>> a = Pinnate({'my_string':'abcdef'}) >>> a.my_string 'abcdef' >>> a['my_string'] 'abcdef' >>> a.as_dict() {'my_string': 'abcdef'} ob...
3f71b3a13c5765c742a4055f6f7e6f37248052ca
OsAlex/algo_python
/lesson_6/2.py
3,063
3.75
4
# 1. Подсчитать, сколько было выделено памяти под переменные в ранее разработанных программах в рамках первых трех уроков. # Проанализировать результат и определить программы с наиболее эффективным использованием памяти. # Примечание: Для анализа возьмите любые 1-3 ваших программы или несколько вариантов кода для одно...
9ce26ed28f29934ddf846c65d0b8e640cb1155c3
maxechterling/qbb2017-answers
/day3-lunch/sort.py
439
3.640625
4
#!/usr/bin/env python import random nums = [x for x in range(3, 100)] print nums key = 14 checked = [] for i, n in enumerate(nums): checked.append([i, n]) while True: midInt = len(checked)/2 - 1 mid = checked[midInt][1] if mid == key: print 'Found it at index %d!' % checked[midInt][0] ...
372d1d7963dcf64b6a0913690af7ab8425b644f2
QAMilestoneAcademy/PythonForBeginners
/Quizzes/Quiz_BasicConcepts.py
732
4.59375
5
# 1. What does this code output? print(1 + 2 + 3) #2. What does this code output? print((4 + 8) / 2) #3.What is the result of this code? print(7%(5 // 2)) #4.Complete the code to create a string containing a double quote. print("__") #5.Fill in the missing part of the output. print("""First line second line""") ...
6ffe8f344087d58cf95c02373c18bb264f7aee3d
BooYang-CS/python3_code
/11/11_2.py
2,499
4.46875
4
#collections #collections是python内建的一个集合模块,提供了许多有用的集合类 #1.namedtuple p=(1,2)#用一个元组tuple表示不变集合,很难看出这个tuple是用来表示一个坐标的 from collections import namedtuple Point=namedtuple('Point',['x','y']) p=Point(1,2) print(p.x) print(p.y) print(p[1])#但是p还是一个元组tuple只不过是一个定制版的tuple print(isinstance(p,tuple)) #namedtuple是一个函数,它用来创建一个自定义的t...
f1551bfb4edc0e99fe23ee0505b10b2ff8dc8b36
devinlimit/Clarusway_aws_devops_workshop
/python/coding-challenges/vowels.py
295
3.703125
4
text1 = input("Please enter a string: ") text = text1 + " " textlist = list(text) vowelslist = ["a", "e", "o", "ö", "ı", "i", "u", "ü"] result = "negative" j = 0 for i in textlist: if (textlist [j] and textlist [j+1]) in vowelslist: result = "positive" j += 1 print(result)
e9f2135bb11cf02ca6e3da7766151f3323aa1a6d
Claudio911015/StockPriceCrawler
/WebLinkedList.py
4,402
3.84375
4
# -*- coding: utf-8 -*- """ Created on Wed Feb 7 09:21:31 2018 @author: zerow """ import datetime class WebNode: def __init__(self, WebPage, Time): """ Initialize class """ self.WebPage = WebPage self.Time = Time self.pNext = None class WebList: def __init__(self): ...
fcb3ebc3606d20dcf9648e57067bd708060b7230
rafaelperazzo/programacao-web
/moodledata/vpl_data/29/usersdata/123/9688/submittedfiles/atividade.py
161
3.765625
4
# -*- coding: utf-8 -*- from __future__ import division import math n= int(input('Insira um número:')) cont=0 while n>0: n=n//10 cont=cont+1 print cont
7e00f12c4a1a34fda744ed990095ba90616b948d
tinoking63/Projects
/submission_001-toy-robot/try.py
324
4.09375
4
# print("* Move Forward " + str(size)) # print("* Turn Right " + str(degrees) + " degrees") for j in range(4): degrees = 90 for k in range(360): # print("* Move Forward " + str(length)) # print("* Turn Right " + str(degrees) + " degre...
59a7c5a9e4fcd0c8151f11a755c000fe9187b10e
UtileHomme/Programming_Codes
/Python_by_mosh/app5.py
2,153
4.46875
4
# How to get input from a user - 18.67 # name = input('What is your name? ') # # print('Hi ' + name) # How to get age from birth year # birth_year = input('Birth year: ') # gives the datatype # print(type(birth_year)) # # age = 2019 - int(birth_year) # gives the datatype of age # print(type(age)) # print(age) # ...
fb86d67007c2e4d205545e7c83831ff784361698
BITMystery/leetcode-journey
/334. Increasing Triplet Subsequence.py
777
3.578125
4
import sys class Solution(object): def increasingTriplet(self, nums): """ :type nums: List[int] :rtype: bool """ stack = [] minSecondNum = sys.maxint for num in nums: if num > minSecondNum: return True if not stack: stack...
57a8e8180dc136fadbf0e8171f8f9a2aa0ff342c
lizzzcai/leetcode
/python/string/1297_Maximum_Number_of_Occurrences_of_a_Substring.py
2,458
3.734375
4
''' 13/06/2020 1297. Maximum Number of Occurrences of a Substring - Medium Tag: String, Bit Manipulation Given a string s, return the maximum number of ocurrences of any substring under the following rules: The number of unique characters in the substring must be less than or equal to maxLetters. The substring size...
d1f759a8af11320ef39b2ff6809655108f761dbf
IMDCGP105-1819/text-adventure-Barker678
/AoA-chapter-2.py
9,822
3.640625
4
import time import random class WEAPONS(object): def __init__(self): self.WEAPONS = { 'Fist': (3,8), 'stick': (4,9), 'pulse_baton': (5,10), 'alien_blaster': (5,12), } self.current_weapon = WEAPONS['Fist'] def add_WEAPONS(self,name, weapon): ...
fa6062263065f4a29e61692354f90cd3c7e2ac24
why1679158278/python-stu
/python资料/day8.21/day16/demo02.py
157
3.796875
4
""" 内置生成器 zip """ list01 = ["张无忌", "赵敏", "周芷若"] list02 = [1001, 1002] for item in zip(list01, list02): print(item)
d979a8dfa4bd1e6a2da3f03083b1c19c87078946
aman1310verma/TWOC-day4-
/program4.py
449
4.21875
4
m_dict={} size = int(input("\nEnter number of keys in the dictionary:")) for i in range(size): print("Key-Value #{}".format(i+1)) key=input("Enter name of key:") value = input("Enter key value:") m_dict[key] = value print() print("\nOriginal dictionary is:", m_dict) copy_dict={} for key,value in...
e6334378d185f20330bcb68936c01bebda65c953
go2bed/python-oop
/oop/oop/Main.py
465
3.71875
4
from oop.oop.Book import Book class Dog(object): species = 'mammal' def __init__(self, breed, name): self.breed = breed self.name = name def area(self): return self.species def set_name(self, name): self.name = name def get_name(self): return self.name ...
93889dc5074765f96533494079c439df270b6cba
FunkGG/Leetcode
/day2/25_reverseKGroup_95.64%.py
661
3.71875
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverseKGroup(self, head: ListNode, k: int) -> ListNode: out = l = ListNode(0) nodelist = [] while head: nodelist.append(head...
d3e45a5677184a3c8a8929bf5eef3457f0080baf
Animesh0515/Library-Management-System
/display.py
763
3.703125
4
def display(list_2d): print("\t\t\t"," ","Welcome to the Library") print("\t\t\tHere are the list of the Books ","\n") dash='-'*95 print(dash) print("S.NO\t\t","Book Available\t\t\t","Author\t\t\t","Quantity\t","Price") print(dash) for i in range(len(list_2d)): print(i+1,end="\t\t ...
58ed036871c38b34a0552b31a2f354ed3bc44374
i-syang/AutomateTheBoringStuffWithPython
/chapter_8/8_2_3_write_file.py
458
3.5
4
#!/usr/bin/python3.5 filename = "/home/isyang/Code/AutomateTheBoringStuffWithPython/chapter_8/8_2_3_write_file.txt" baconFile = open(filename, 'w') # 创建写 baconFile.write('hello world\n') baconFile.close() baconFile = open(filename, 'a') # 加, append baconFile.write('aaaaaaaaaaaaaaaaaaaaaaaaaa') baconF...
5905d05acc28165b79ee5bfc328e019b6c47ea69
vbuzato/Exercises-Python
/ex016.py
304
4
4
from math import floor, ceil num = float(input('Digite um número: ')) print('O número {:.2f} tem a parte inteira {}.'.format(num, floor(num))) print('O número {:.3f} arredondado para cima é {}.'.format(num,ceil(num))) # O comando floor arredonda para baixo # O comando ceil arredonda para cima
d38253d1a41cc9ee3c08267a31c13b9f373266d3
samensah/Pattern-Avoidance
/pattern_distribution.py
7,628
4.03125
4
__author__ = 'samuel' from itertools import permutations import numpy as np from itertools import * #import sys #sys.stdout = open('/home/samuel/Dropbox/Files/Essay Combinatorics/AIMSEssay/myoutput.txt', 'w') mesh_pattern = np.array([[0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 1, 0]]) def word(n): """ ...
8b00e6626dc7cf34e6a14304175b870cb6813362
carisatinie/emotion_bias
/classifiers/masc/graphs.py
1,378
3.53125
4
from matplotlib import pyplot as plt import numpy as np ''' MASC Graphs ''' ''' Graphs the F1 scores of each feature set as a bar chart. Outputs 3 graphs: one for male, female, and both genders. Uses the results from running model on the test set after tuning on training and validation sets. ''' objects = ('Tukey', ...
e051aa47441e92302a3d848a6bbe28b63ae53ca3
szbrooks2017/holbertonschool-higher_level_programming
/0x06-python-classes/1-square.py
218
3.828125
4
#!/usr/bin/python3 """ a Square with size, private instance attriute size, no type/value""" class Square: """a class that creates a single attribute""" def __init__(self, size): self.__size = size
d6728ed091a933e18fd3315f1d8f185917883ca7
CoderPrabal/Datastructure
/anti_diagnol.py
457
3.640625
4
def solve(A): length_of_array = len(A) no_of_anti_diagnol = (2 * length_of_array) - (1) empty_lists = [[] for _ in range(no_of_anti_diagnol)] print(empty_lists) for i in range(0, length_of_array): for j in range(0, length_of_array): value = A[i][j] sum_index =...
e89286410630a0a1abdb45a1c155d824db4e7731
itsjunqing/fit1008-introduction-to-computer-science
/source_code/dp/dp_fib.py
1,623
3.65625
4
# using normal recursive method def fib_normal(n): return fib_aux_normal(n) def fib_aux_normal(n): if n == 0 or n == 1: return 1 else: return fib(n-1) + fib(n-2) # using tail recursion where it passes the base case into the auxilary method def fib(n): return fib_aux(n, 0, 1) def fib_aux(n, before_last, last)...
854845a12251ecd26f1b77b24e79c5ac979f2bd3
anaskhan28/Python-practice-codes
/Chapter 12/01_try.py
350
4.09375
4
while(True): print("Press q to Quit the match") a = input("Enter the number\n") if a == 'q': break try: print("Trying.....") a = int(a) if a > 6: print("Your number is greater than 6") except Exception as e: print(f"The value should be number: {e}") ...
5543387fdb324c11046c107d41b0fe8f81a4ab31
BuddhaRandom/yars-revenge
/ship.py
1,975
3.578125
4
#import pygame from asprite import ASprite from animated_facing_sprite import AnimatedFacingSprite import options class Ship(AnimatedFacingSprite): """The player's sprite ship Moves in eight directions with screen wraparound -- see move() docstring """ def __init__(self, sprite_s...
032f542201f2bc8f61877290055e0f271cb932d1
giladmishne/bf
/spell_checker.py
1,498
3.78125
4
import re import sys from os.path import isfile from bf.bloom_filter import BloomFilter DEFAULT_WORD_LIST = '/usr/share/dict/words' # A simple application of the bloom filter: load a word list, store it in a filter, and spell-check # a different file against it. def tokenize(in_file): """Iterates over words in...
10065cf452ddc6ef9d99bf9da8d8811f99bc03fe
DilyanTsenkov/SoftUni-Software-Engineering
/Python Fundamentals/Mid exams/01_Spring_Vacation_Trip.py
1,031
3.90625
4
days_trip = int(input()) budget = float(input()) group = int(input()) fuel_price_km = float(input()) food_expenses_person_day = float(input()) hotel_person_night = float(input()) hotel = group * hotel_person_night * days_trip if group > 10: hotel *= 0.75 food = group * food_expenses_person_day * days_t...
9642c099a7f4222e1315b3dbc8ae36915764c44a
zihuaweng/leetcode-solutions
/leetcode_python/1056.Confusing_Number.py
885
3.71875
4
#!/usr/bin/env python3 # coding: utf-8 # Time complexity: O() # Space complexity: O() # https://leetcode.com/problems/confusing-number/ class Solution: def confusingNumber(self, a: int) -> bool: src = a sub = {0: 0, 1: 1, 9: 6, 8: 8, 6: 9} b = 0 while a > 0: if a % 10 ...
02d28f6b0677a66fd8466f7fe40f79cb651a7ea8
guilhermeaugusto9/100daysofpython
/Day 17/main.py
709
4.1875
4
class User: """User class""" def __init__(self, id=None, username=None): """Constructor to initialize attributes""" self.id = id self.username = username self.followers = 0 self.following = 0 def follow(self, user): self.following += 1 user.followers...
1d31176ffb345a6444a1333e101bdc6f632ce322
Rxdxxn/Rezolvare-If-While-For
/RB2.py
126
3.796875
4
n=eval(input("introduceti un numar:")) s=0 y=1 for n in range(1, n+1): y*=n s+=y print("Suma este egala cu:", s)
317f9684750d001b48d1768b06f67652cf2ffb81
zhix9767/Leetcode
/code/Word Search.py
1,169
3.546875
4
class Solution(object): def exist(self, board, word): """ :type board: List[List[str]] :type word: str :rtype: bool """ if not self.preCheck(board, word): return False for i in range(len(board)): for j in range(len(board[0])): ...
3422db15e2995bf71ae47b5321c72f001b2a0f06
almacro/snippets
/python/libvirt/basic/using_getHostname.py
437
3.59375
4
''' Example 8. Using getHostname This example demonstrates the getHostname() method. This can be used to obtain the hostname of the virtualization host as returned by gethostname(). ''' import sys import libvirt uri = 'qemu:///system' conn = libvirt.open(uri) if conn is None: print(f"Failed to open connection...
6a92b02fcfa0df1a3030243c03582c0ca0100b58
c-machado/DataStructuresPython
/ArraySequences/ArrayExample.py
906
4.25
4
import copy student_name_list = ['Rene', 'Joseph', 'Janet', 'Jonas', 'Helen', 'Virginia'] # temp has a reference to the same element that exists on student_name_list temp = student_name_list[2:3] #print(temp) primes = [2, 3, 5, 7, 11, 13, 17, 19] # copy to reference the same objects of primes list temp = primes[3:6]...
f3762d4e767dffec3fbc715801250e7125a8c7e7
Felipe0042/mineracao-dados-complexos-unicamp
/INF-0617/TrabalhoFinal/ex1/reducer.py
788
4
4
#!/usr/bin/env python import sys import calendar cur_temp = -999 month_with_max = None city_with_max = None def get_month_name(month_number): return calendar.month_name[int(month_number)] def print_out(month_param, city_param): print("('%s', '%s')" % (get_month_name(month_param), city_param)) for line i...
abb95c292e64c01df017b75abb825ca84687644b
ma7salem/python-fundamentals
/#8 user input/demp.py
217
3.75
4
x = int(input("Enter First Number")) y = int(input("Enter Secont Numper")) z = x + y print("the result:", z) ch = input("Enter a Char")[0] print("Your Char is", ch) val = eval(input("Enter an exper")) print(val)
6cae7b819c249cfac49373123fa74a81fc7cb008
vick-hub/week2
/problem8.py
396
4.0625
4
import os import sys import random def main(): t = random.randint(0, 9) y = int(input("Enter a number: ")) # we're to apply what we learned; this has not been introduced if y < t: print("The number is less than random number") else: print("The number is not less than random number"...
0093b1a1c510b4d364f28469a1568153b2c729cc
jay-trivedi/greyatomlib
/greyatomlib/descreptive_analysis/q03_pearson_correlation/build.py
541
3.546875
4
# Default Imports from greyatomlib import pandas as pd dataframe_1 = pd.read_csv('data/house_prices_multivariate.csv') house_price = dataframe_1.loc[:, 'SalePrice'] dataframe_2 = pd.read_csv('data/house_prices_copy.csv').loc[:, 'SalePrice'] weight_of_nasa_space_shuttle = dataframe_2.loc[:, 'SalePrice'] # Return the ...
5d83d9fae27793c4c90a6bc05b00b18044c429c0
backslash112/python-practices
/list_to_tree/list_to_tree_1.py
1,472
3.765625
4
# # 问题:将一个排序好的数组转化成一个搜索二叉树? # 思路:二叉树最好情况下是一棵平衡二叉树,所以,从已排序的数组的中间位置开始往两边取数据进行构建二叉树。 # 所以第一步是将排序好的数组转换顺序,从中间开始往外取数的顺序,例如,[1,2,3,4,5] -> [3,2,4,1,5] # 思路不对,正确思路查看 list_to_tree_3.py # import sys def getMiddleIndex(n): if n % 2 == 1: return int((n - 1) / 2) else: return int(n / 2) middleIndex = -1 ...
f58d44a0d57aa9292e65f8da3f3dbedc00788e56
Spiderjockey02/CodeSnippets-Python
/files/quick_sort.py
1,140
3.984375
4
#array declaration arr=[] n=int(input("Enter the array size: ")) #getting the array size #function to get user inputs def userinputs(arr): for i in range(n): v= int(input("Enter a number: "))#add the elements to the array arr.append(v) #function for partition def partition(arr,start,end): i=st...
175a6b864a4d9b1e6dfe6680f8f5d2e87580000f
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/shodges/lesson09/cli_main.py
6,284
3.546875
4
#!/usr/bin/env python3 from donor_models import DonorCollection import atexit marmots_ledger = DonorCollection('marmots') def send_thank_you(): """ User interface allowing the user to: * Enter a donor - Special values: list to list all donors, quit to return to main menu * If the donor does not...
3961cf8fa94638c66a1df37308ee6330f449480a
luisalejandrojaramillo/NxU_Fundamentos-de-Programaci-n-en-Python
/2. Tipos de Datos e Instrucciones Básicas/Leccion4/Ejercicio1.py
407
3.84375
4
from datetime import datetime def main(): nombreC=input("Nombre de la Criptomoneda: ") cantCripto=float(input("Cantidad acumulada de la Criptomoneda: ")) cotizacion=float(input("Cotización por US$ del día de la Criptomoneda: ")) fecha = datetime.now() print("La fecha completa y hora en la que obtuvo...
485c5b87eda60bdc39eb791ae3c1a0154ee55ae4
UjjwalJain02/Turtle-Race
/main.py
954
4.1875
4
import random from turtle import Turtle, Screen screen = Screen() screen.setup(width=500, height=400) user_bet = screen.textinput(title="Make your bet", prompt="Which turtle win the race? Select the color:") print(f"You made a bet on {user_bet} color turtle") is_race_on = False turtles = [] colors = ["red", "orange",...
f031b9e0bcdadcea8170aaee244eae3f96118de4
georgewashingturd/leetcode
/No_493_Reverse_Pairs.py
3,379
4.34375
4
############################################################################### # 493. Reverse Pairs ############################################################################### # this is similar to count number smaller than self problem No 315 however # when we do the merge we want to separate the counting of smal...
0715d659e82909f712004a997efcce2450fb9424
rohitrnath/EPAi3
/Session-11-Iterators/polygon_sequence.py
1,536
3.8125
4
from polygon import Polygon class Polygon_sequence: def __init__( self, largest_num_edges, circumradius): if largest_num_edges < 3: raise ValueError("Polygon require atleast 3 or more edges/vertices!") self.largest_num_edges = largest_num_edges self.circumradius = circumradiu...
eef335dccf1ab2a8156c6996032fe13cf30e0dc7
zspatter/network-simulation
/network_simulator/BloodType.py
3,116
3.5625
4
from __future__ import annotations from network_simulator.compatibility_markers import BloodTypeLetter, BloodTypePolarity class BloodType: """ A class representing a given blood type. Possible blood types: O-, O+, A-, A+, B-, B+, AB-, AB+ """ def __init__(self, blood_type_letter: Bl...
22167fb4feba0501a29c0f11af5e7d3472f46ffa
MapleStory-Archive/maplestory2_autofarmer
/Keys.py
2,249
3.671875
4
import time import C #Wait Function is for the beginning of the program def Wait(timeIn): time.sleep(timeIn) def upLeft(timeIn): C.PressKey(0xC8) C.PressKey(0xCB) time.sleep(timeIn) C.ReleaseKey(0xC8) C.ReleaseKey(0xCB) time.sleep(0.1) def upRight(timeIn): C.PressKey(0xC8) C.Press...
551c60d9afc09af7f738e0165717d7cfd703a00e
CobaltGoldCS/loginSystem
/Login.py
2,358
4.03125
4
from pathlib import Path from TestText import * print('Welcome to my super secret password holder') User = input('First, my program has to make sure its me: ' ) filepath = "C:\\Users\\dylan\\Python\\Login system\\" PassWD = input('Next, the password of course, this is the password to end all passwords: ') Pas...
ceb0c1fbe584fa90420d89086f7d0f1327fd32e5
freddimsc/geekbrains_python
/lesson2/hw_2_5.py
773
4.21875
4
#. Реализовать структуру «Рейтинг», представляющую собой не возрастающий набор натуральных чисел. # У пользователя необходимо запрашивать новый элемент рейтинга. # Если в рейтинге существуют элементы с одинаковыми значениями, # то новый элемент с тем же значением должен разместиться после них. my_list = [7, 5, 3, 3, 2]...
6880f432aaf73ab74b874bf7e71ee06a10f80da1
kayjayk/algorithm-solution
/Exam3009.py
441
3.6875
4
from collections import defaultdict def filter_only_one(n_list): n_dic = defaultdict(int) for i in n_list: n_dic[i] += 1 for key in n_dic.keys(): if n_dic[key] == 1: only_one = key break return only_one x_list = [] y_list = [] for i in range(3): x, y = map...
8e1da71537181ff8234592f8bc747c904326d8d3
Maaaatts/Pandas
/Problem_1.py
345
3.703125
4
# -*- coding: utf-8 -*- """ Created on Sat Nov 23 22:53:42 2019 @author: Matthew Rabanes """ import pandas as pd cars = pd.read_csv('cars.csv') first = cars[0:5] last = cars[27:32] print('The first five cars are: \n \n' +str(first)) print('--------------------------------------------') print('The l...
af606ed6908eb3af22d7547a8cd0a40dbd51d381
PatNicholson/DeepUno
/objects.py
7,401
3.90625
4
""" This file defines all the major classes that will be used: Card: represents an UNO card in the deck Deck: represents a list of cards Player: treated as an abstract or super class that each AI player will implement Game: represents the state of a single game (the one that is currently being played) Weights o...
288b4250c17ff8b85234181cbefb326163b8a385
ctsan/powersets
/powerset.py
379
3.625
4
#!/usr/bin/env python from itertools import combinations from sys import argv def set_printer(name,s): l = list(s) print(name, " = " ,sorted(l, key=len)) initial_set = set(argv[1:]) final_set = set() for i in range( len(initial_set) + 1 ): final_set |= set ( combinations( initial_set, i) ) ...
4f35816e4bab38ff4d161d9edb9877c00b53f162
lajanugen/errata_analysis_eecs573
/src/text_processing.py
2,475
3.765625
4
''' This file will include all general text processing functions. ''' import csv import re import string import sys from nltk import sent_tokenize from nltk.tokenize import word_tokenize import errata ''' Take in a string and split into sentences; strip all non-ascii characters and lower-case all text; then tokenize...
880fade70977ebf10bc4498eb9252f83f0e95bed
pngisnotgif/python
/Core Python Programming/6-10.py
478
3.8125
4
# 6-10 def capital_reverse(s): new_s = '' for i in s: if i.islower() : new_s += i.upper() elif i.isupper() : new_s += i.lower() else: new_s += i print s,'==>',new_s def capital_reverse_v2(s): print s,'==>',s.swapcase() if __name__=='__m...
5e33078802633b25084a29a92fe7fb080bb9ecd6
cuiboautotest/learnpython3
/算法练习/面试/数字前后加符号.py
158
3.515625
4
s='Jkdi234klowe90a3' s1='' for i in s: if i.isdigit(): s1+='*'+ i +'*' else: s1+=i print(s1) s2=s1.replace('**','') print(s2)
bd4c59d3c0f6e22833f64f99b096c7bc29792fc0
IvanChavez1997/Modelos-y-Simulaciones
/Movimiento Ondulatorio.py
1,373
3.578125
4
# -*- coding: utf-8 -*- """ Created on Sat Nov 14 17:58:54 2020 @author: Ivan """ import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation ####### SIMULACIÓN DE MOVIMIENTO ONDULATORIO #### ### CREAMOS LA GRAFICA CON TRES SUBGRAFICAS### fig = plt.figure(figsize=(10,...
2fe4935a8b2ba511e7c26177fd3e6fbbc4694b2f
dspolyar/Main
/Library_CopyFunction.py
4,263
4.125
4
""" SOURCE: http://stackoverflow.com/questions/6527633/how-can-i-make-a-deepcopy-of-a-function-in-python **Cannot find the official documentation for `types.FunctionType` Must have named arguments somehwere, and cannot find with google DESCRIPTION: Makes a deep copy of a function in python ...
bcbaa0f4ed5a8be1b395d313c3cd7dc67803c7ee
miAndreev/Programming101-2
/w0/f6-count_cars_words_or_lines/solution.py
794
3.90625
4
from sys import argv, exit def count_chars(file_name): file = open(file_name, 'r') content = file.read() words = content.split(" ") count = 0 for el in content: count = count + len(el) file.close() return count def count_words(file_name): file = open(file_name, 'r') coun...
986b6776f87a895044b3acd0ea1233eabfb3f3a6
agatanyc/RC
/algorithms_DS/python/collatz_2.py
913
4.3125
4
!/usr/bin/env python # The following iterative sequence is defined for the set of positive integers: # # n -> n/2 (n is even) # n -> 3n + 1 (n is odd) # # Using the rule above and starting with 13, we generate the following sequence: # # 13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1 # # It can be seen that this ...
c04e861e8c74d785041168b3f795fe5239d3eba7
zhujunzhujunzhu/Python001-class01
/week04/practice/demo1.py
3,181
3.9375
4
''' https://blog.csdn.net/qq_38251616/article/details/84752080 1 写csv文件 2 读csv文件 3 DataFrame 遍历 合并 4 行 查找 删除 5 重复项 6 元素 7 排序 ''' import os import pandas as pd ''' 写文件: 关于这里可以看到的是 任意多组列表 可以利用字典映射索引 可以设置mode 是否加上索引 可以添加上分隔符sep mode = a 代表不覆盖原有的内容的 practice/csv/test0.csv 当写路径时 如果csv不存在时会报错 ''' # a = [1, 2, 3] # b ...
76955f23e5f4befe9c55a230425d6be8296f5f42
RGMishan/flaskPython
/practicePython/dictionary.py
201
4.03125
4
#python dictionary #Key Values Pair ages = {"Mishan": 20, "Regmi": 21} #ages is a dictionary ages["Nishan"] = 50 # Adding in dictionary ages["Mishan"] += 1 #Changing values in dictionary print(ages)
8b9526bd7d0b8a1beb897333c393d7542377d445
Seorimii/PythonStudy2019
/mar_24/0324_71.py
233
3.5625
4
def getPrime(x): if x%2==0: return for i in range(3,int(x/2),2): if x%i==0: break else: return x listdata = [17, 19, 113, 1113, 1119] ret = filter(getPrime,listdata) print(list(ret))
35d919b0e00afaddc160d91d8c6e2816ca30835a
atakanozguryildiz/HackerRank
/time_conversion.py
320
3.8125
4
s = input() is_am = "AM" in s first_two_digits = s[:2] if is_am: if first_two_digits == "12": print(("00" + s[2:-2])) else: print(s[:-2]) else: if first_two_digits == "12": print(s[:-2]) else: pm_hour = str(int(first_two_digits) + 12) print((pm_hour + s[2:-2]))
3a171f0270fba11c89cc79a853b6cd7370ec9e03
RoslinErla/ekki
/ordered_insetion.py
377
3.546875
4
import random from random import * class rand: gen = Random() def switch(lis,index): temp = lis[index] lis[index] = lis[index + 1] lis[index + 1] = temp def ordered_insertion(lis,value): index = len(lis) -1 lis.append(value) while index >= 0 and lis[index] > value: switch(lis,ind...
42f50ba634f2422627db6c0d52b95b74105859c9
poojamadan96/code
/dict/list-set-dict.py
192
4.0625
4
#Make set and list from Dictionary dict={'a':1,'b':2,'c':3,'d':4,'e':5} li=[] sets=set() for x,y in dict.items(): li.append(x) sets.add(y) print("List = ",li) print("sets = ",sets /
353ed9f761dca29a31891c2e2d070380f357d687
papermerge/hocron
/hocron/line_pattern.py
2,630
3.984375
4
import re class LinePattern: """ line_pattern is a list with at least two elements - a string, which is a label and a regular expression compiled pattern (instance of re.Pattern) - the value to extract. String and regular expression can be in any order. The order matters for correct matching. ...
26a8e7b9ded3c7785895e08fa2eb2a8c228a4ab9
cuiboautotest/learnpython3
/10_hanshu/args_dif_kwargs.py
376
3.640625
4
def function1(*args): print(args, type(args))#用来将参数打包成tuple给函数体调用 def function2(**kwargs): print(kwargs, type(kwargs))#打包关键字参数成dict给函数体调用 def function3(arg,*args,**kwargs):#顺序必须是固定的 print(arg,args,kwargs) function1(1) function2(a=2) function3(6,7,8,9,a=1,b=2,c=3) function1() function2()
3feea041c00e9679cf399d90785656fad195cf02
tenkgrow/conceptual-backup-system
/backup_system.py
5,271
3.546875
4
#!/usr/bin/python3 import subprocess import linecache import os def stripend(strip): mod = strip.replace('\n','') return mod def ynchoice(user_input): while ((user_input is 'y' == False) or (user_input is 'n' == False)): print("The character you entered could not be recognized!") user_input ...
20a482ce543102caafd9995e22317b9182a46130
nishahiremani18/python
/python2.py
4,525
3.8125
4
Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:43:08) [MSC v.1926 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> #Araays and lists >>> a='hello python' >>> a[0] 'h' >>> a[1:2] 'e' >>> a[2:6] 'llo ' >>> a[-1] 'n' >>> a[-3] 'h' >>> a[-4] 't' >>> a...
df4f63d50f4d4786f8f0d760fbd83198b84b4c6c
fukenist/learn_hard_way
/test6.py
782
4
4
print("""You enter a dark room with two doors. Do you go through door #1 or door #2?""") door = input("> ") if door == "1": print("There's a giant bear here eating a cheese cake.") print("What do you do?") print("1. Take the cake.") print("2. Scream at the bear.") bear = input("> ") if bear == "1": print('Ya...
6189417113c869bfd4ab70defeae2ebed2a22adc
f904/my-lesson-python
/домашка.py
259
3.890625
4
while True: a = int(input()) b = int(input()) v = input() if v =='*': print(a*b) if v =="+": print(a+b) if v =="-": print(a-b) if v =="/": if b!=0: print(a/b) l
842983102cd8d2f8555cfd50a426eebc03acc085
pauloalwis/python3
/leia.um.numero.inteiro.e.mostre.sua.tabuada.py
193
4.03125
4
numero = int(input('Digite um número para ser apresentado sua tabuada!')) print(20 * '=') for i in range(0, 11): print('{} x {:2} = {}'.format(numero, i, (numero * i))) print(20 * '=')
2fb9bf701114f9c68980ad246a5ef38b4afc82ad
mananjay19/p109
/p109.py
1,409
3.671875
4
import pandas as pd import csv import statistics df = pd.read_csv('StudentsPerformance.csv') datalist = df ['reading score'].tolist() datamean=statistics.mean(datalist) datamedian=statistics.median(datalist) datamode=statistics.mode(datalist) datastd=statistics.stdev(datalist) print('mean,meadian,mode,stdev for r...
5ef0369db81ade386b8208358f2b8e1d39bed1ea
liuperic/automate_the_boring_stuff_with_python_solutions
/ch_19/practice_projects/custom_seating_cards.py
1,051
3.625
4
#!/usr/bin/env python3 # custom_seating_cards.py - From practice project in ch 15, add image to custom card # Extension of ch 15 project. import os from PIL import Image, ImageDraw, ImageFont def seating_card(guest_list): """Custom invitation card for each guest""" os.makedirs('custom_cards', exist_ok=True) ...
afe78628f7063002ce4d243cb917c45a9fad1b5a
Iongtao/learning-python3
/learning/base8_input.py
1,861
3.75
4
# !/usr/bin/env python3 # coding=utf-8 qanda = [ { "q": "1+1等于几?", "a": "2" }, { "q": "你是几号入职的?例如:9月24号", "a": "11月2号" }, { "q": "我和你认识多久了", "a": "不知道" } ] # 声明一个变量作为 提示信息 question = '请输入你想回答的问题序号,例如:1\n' # indexs用来去得到序号列表 indexs = [] # 把问题遍历出...
b712570b9d650553562fbcac43a17e65bae817c3
maomao905/algo
/maximum-length-of-repeated-subarray.py
4,242
3.921875
4
""" N: A length, M: B length brute-force O(NM*min(N,M)) space: O(1) iterate A's letter and check if it exists in B one by one and it matches, continue expanding until unmatched A = [1,2,3,2,1] B = [3,2,1,4,7] """ from typing import List class Solution: def findLength(self, A: List[int], B: List[int]) -> int...
dad8a73ce62f291d6572423d0d718172a7b5e5ef
BrentLittle/WebDevPython
/Sec 2 - Python Refresher/10_Loops/loop.py
622
3.8125
4
number = 7 while True: userIn = input("Would you like to play? (Y/n): ") if userIn == "n": break usernum = int(input("Guess our number: ")) if usernum == number: print("You guessed correctly") elif abs(number - usernum) == 1: print("You were one off.") else: ...
2359f8ea0aa6fc905cbaefb9a466c866f8cbfffb
Everfighting/leetcode-problemset-solutions
/valid-parentheses.py
1,169
3.5625
4
#给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。 # #有效字符串需满足: # #左括号必须用相同类型的右括号闭合。 #左括号必须以正确的顺序闭合。 #注意空字符串可被认为是有效字符串。 # #示例 1: # #输入: "()" #输出: true #示例 2: # #输入: "()[]{}" #输出: true #示例 3: # #输入: "(]" #输出: false #示例 4: # #输入: "([)]" #输出: false #示例 5: # #输入: "{[]}" #输出: true # 法一 class Solution: def isValid(self, s...
bbf55624dc3f7737deca1f1f0d6f320d81558d6d
yaodecheng0217/Fengbian-
/练习/9-1.py
664
3.78125
4
''' @Author: Yaodecheng @Date: 2019-12-06 20:14:52 @LastEditors: Yaodecheng ''' #定义两个函数:第一个函数功能为根据工作月数返回奖金额, def reward(month): if month<5: return 500 elif 6<=month<=12: return 120*month else: return 180*month #第二个函数功能为打印出'该员工来了XX个月,获得奖金XXX元'。 def printall(name,month): print ('{...
d89177817be2a664fb12d476001a3a52f0c8ac6d
yangjiahao106/LeetCode
/Python3/1206_设计跳表.py
1,753
3.6875
4
import random class Node: def __init__(self, val=0): self.val = val self.right = None self.down = None class Skiplist: def __init__(self): left_nodes = [Node(-1) for i in range(16)] for i in range(15): left_nodes[i].down = left_nodes[i + 1] self....
9a209abe218f68ba7077e33d8baa0fb63f5b9836
dinosaurz/ProjectEuler
/id007.py
740
3.9375
4
import time def isPrime(num): ''' Return whether a number is prime Using Joah Gestenberg's algorithm from www.koding.com num: number to be tests ''' if num % 2 == 0: return False for p in xrange(3, int(num ** 0.5) + 1, 2): if num % p == 0: return ...
b8d4e0cbd4132b7f0ff1cdb3081defad00eb37e0
kimsappi/website-status
/src/classes/IntervalParser.py
1,105
3.875
4
allowedIntervals = ['second', 'seconds', 'minute', 'minutes', 'hour', 'hours'] class IntervalParser: """ Returns number of seconds interval given as string (e.g. '5 seconds', '1 hour'). """ def __new__(cls, interval: str) -> int: try: arr = interval.split(' ') except: raise Exception('Ti...
a9fda6c1c22bd32f312109327ed53ed4df84a6e2
Chairmichael/ProjectEuler
/Python/Complete/0006b - Sum square difference.py
703
3.84375
4
''' The sum of the squares of the first ten natural numbers is, 1**2 + 2**2 + ... + 10**2 = 385 The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)**2 = 55**2 = 3025 Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 =...
62d0f88f2a7efceff3878180dc57b667ac27eda6
deskninja/Various
/temp.py
1,363
3.71875
4
def main(): getKey = list1, players = getScores() numbers = [] highlow = list1.sorted() def getScores(): nameandScores = [] total = 0 nameandScore = "start" nameandScore = str(input("Enter the name and score of the next player: ")) if nameandScore == "": #Checks to see if the f...
89e81c34cb0da39b696a6fdc842368f60e681612
TechHouse-rj/Mini_Projects
/Fluid Simulaor/script.py
7,551
3.71875
4
import sys import pygame from math import sqrt from random import random as rand from math import pi class Particle(object): def __init__(self, pos): # Scalars self.density = 0 # Forces self.position = pos self.velocity = Vec2(0,0) self.pressure_force ...
afa44b3a9572bdc79c4b69faf1d6de6c9288c3e4
vikassry/pyWorkspace
/rovers.py
1,350
3.671875
4
DIRECTIONS = { 'N' : {'L':'W', 'R':'E'}, 'W' : {'L':'S', 'R':'N'}, 'S' : {'L':'E', 'R':'W'}, 'E' : {'L':'N', 'R':'S'} } MOVE_COORDINATES = { 'N' : [0, 1], 'S' : [0,-1], 'W' : [-1,0], 'E' : [1, 0] } def move(rover, moves): for move in moves: if (move=='L') or (move=='R'): rover['direction'] = DIRECTIONS...
868f525d4c792a1936420fba2918e3ba446b3faf
poponzu/atcoder1
/LeetCode/permutations.py
260
3.828125
4
# itertoolsなかったらきつい? # import itertools class Solution: def permute(self, nums):# List[List[int]]: per = list(itertools.permutations(nums)) return per num = [1,2,3] per = list(itertools.permutations(num)) print(per)
dca28ddb8c14ff5a810415a2890112994f3e0ac9
skebix/think-python-implementation
/Exercises/Chapter 4/e5.py
606
4.53125
5
__author__ = 'skebix' ''' Make a more general version of circle called arc that takes an additional parameter angle, which determines what fraction of a circle to draw. angle is in units of degrees, so when angle=360, arc should draw a complete circle. ''' from swampy.TurtleWorld import * from math import pi world =...
c6236ea2edaa217061d66a0b03020c5c8d898fcb
yuuhei340/sample-streamlit-yuhei
/Greeting.py
487
3.625
4
class Student: def __init__(self,name): self.name=name def calculate_avg(self,date): sum=0 for num in date: sum+=num avg=sum/len(date) return avg def judge(self,avg): if(avg>=60): result="passed" else: resul...
d1453cbfb092465a9acd31c3394d82829a43473c
huezune2000/Learn-Python-Offline
/PYTHON/Learn Python/Level_0/8) While 1.py
643
4.53125
5
#### #Now that you know a little about how variables #can be defined and redefined we'll cover our first #type of loop. The 'while' loop #### #the 'while' loop says that as long as something #that you define is true, it should perform an #operation #For Example x = 0 while (x<10): print (x) x += 1 ...
fc055d418b2df7407722048c251cf47790916727
vash050/start_python
/lesson_2/shcherbatikh_vasiliy/z_2.py
1,150
3.90625
4
# Для списка реализовать обмен значений соседних элементов, # т.е. Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д. # При нечетном количестве элементов последний сохранить на своем месте. # Для заполнения списка элементов необходимо использовать функцию input(). my_list = [1, 2.2, 'str', [1, 'str'], {'...
69565f9b222dcd8b4b546344cf4ec81bb67d977a
SarthakRana/Machine-Learning-A-Z
/Data Preprocessing/Data_preprocessing.py
2,014
3.796875
4
#Dataset Preprocessing #----------------Importing Libraries--------------# import pandas as pd # For importing datasets and managing datasets import matplotlib.pyplot as plt import numpy as np # contains mathematical tools which helps in calculations #--------------- Importing the Dataset--------------...
4be56b99065ff64d097864899a9738881738eedf
luuuumen/algorithm013
/Week_02/hw.py
2,876
3.515625
4
# coding:utf-8 from collections import deque import heapq class Solution(object): # 两数之和 def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ # dic = dict(zip(nums, range(len(nums)))) dic = {} ...
0daf860d687880c51d8d9e892368bacee9f4db09
icurious/Automate-The-Boring-Stuff-With-Python
/Chapter 4/Comma Code.py
236
3.828125
4
def comma_code(user_list): string_with_and = ",".join(user_list[:-1]) + " and " + user_list[-1] print((string_with_and)) user_input = input("Enter your list: ") user_list = user_input[1:-1].split(",") comma_code(user_list)
20323f546afbb48c5f632db6ed39a0fce315c005
geraldo-sousa/Francisco-Vieira
/p1-lp1/Teste-de-conhecimento-inicial/intersecaoentrelistas.py
546
3.78125
4
''' Interseção entre listas ''' lista1 = [] lista2 = [] intersecao = [] tamanho = 40 i = 0 while(i < tamanho): value = input() if(value != ''): if(i < 20): lista1.append(int(value)) else: lista2.append(int(value)) i += 1 for value1 in lista1: for value2 in ...
acf9308b0b83aabc60c9032e8942394d19727fc9
sbudax/Python
/basics/basicsModule.py
1,836
3.859375
4
#Using Builtin Modules #Usage: import sys # sys.builtin_module_names # import time # import os # while True: # if os.path.exists("file.txt"): # with open("file.txt") as file: # print(file.read()) # else: # print("file does not exist") # time.sleep(5) ...