blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
33d49c739b206b24499031d73ecf7943ea6162f6
RJMathis/cs373
/notes/09-27.py
1,246
3.921875
4
# ----------- # Wed, 27 Sep # ----------- """ factorial() iteration reduce() more iteration """ class A : def __init__ (self, v) self.v = v x = A(2) # x = A.__init__(2) p = iter(x) # p = x.__iter__() a = ??? # must be iterable for v in a : ... a = ??? # must be an iterable over ite...
eea81c68241d8b3b68ef08b00e6615549c5f9887
StrugglingForBetter/LeetCode_Python
/47_Permutations_II.py
418
3.53125
4
class Solution: def permutationUnique(self, nums): if len(nums)==0: return [] if len(nums)==1: return [nums] res=[] nums.sort() previousNum=None for i in range(len(nums)): if nums[i]==previousNum: continue previousNum=nums[i] for j in self.permutationUnique(nums[:i]+nums[i+1:]): res.append...
c0b6909c8aafe82e2b09e07a6522d1cf3cc62d9e
StrugglingForBetter/LeetCode_Python
/21_Merge_Two_Sorted_List.py
789
3.890625
4
class ListNode(object): def __init__(self,x): self.val=x self.next=None def __repr__(self): if self is None: return " Nil" else: return "{} -> {}".format(self.val, self.next) class Solution(object): def mergeTwoLists(self,l1,l2): cur=dummy=ListNode(0) if not l1: return l2 if not l2: ...
f7b4f68ab01e2eec468dfa7a38135b80289ef917
StrugglingForBetter/LeetCode_Python
/49_group_anagrams.py
354
3.78125
4
class Solution: def groupAnagrams(self, strs): map={} for word in strs: sortedword=''.join(sorted(word)) map[sortedword]=[word] if sortedword not in map else map[sortedword]+[word] ret=[] for item in map: ret.append(map[item]) return ret if __name__=="__main__": print Solution().groupAnagrams(["eat...
18bdd134a9eef91fcaa6058578cb17d9f3d7cbc2
StrugglingForBetter/LeetCode_Python
/Regular_Expression_Matching.py
1,860
3.609375
4
class Solution(object): def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ m,n=len(s),len(p) #init dp dp[i][j] represents the matching status between s[i:] and p[j:] dp = [[False for i in range(n+1)] for i in range(m+1)] #the matching process starts...
18f38988d173e973ccf59d0e7b328df62c309c39
StrugglingForBetter/LeetCode_Python
/23_Merge_k_Sorted_Lists.py
800
3.828125
4
import heapq class ListNode: def __init__(self, x): self.val=x self.next=None def __repr__(self): if not self: return "Nil" else: return "{} -> {}".format(self.val,self.next) class Solution: def mergeKSortedLists(self,lists): heap=[] dummy=ListNode(-1) cur=dummy for node in lists: if node: ...
82c3d791f25b35b0de3673267672ced5771552de
bruntonspall/adventofcode
/2020/util.py
458
3.671875
4
def parse_groups(lines): result = [] group = [] for line in lines: if line == "": result.append(group) group = [] else: group.append(line) result.append(group) return result assert [['a', 'b']] == parse_groups(["a", "b"]) assert [['a', 'b'], ['c']...
c0ced71bc1ef01689981bdc9f5c0f227ac76226a
rosexw/Practice_Python
/1-character_input.py
842
4.125
4
# https://www.practicepython.org/ # Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old. # name = raw_input("What is your name: ") # age = int(input("How old are you: ")) # year = str((2018 - age)+100) ...
9465e88480f41c29260f6509b70b12bf2fc09aa4
Linda-test/mhr_scripts
/data/run_test.py
762
3.890625
4
import random,string src_digits = string.digits # string_数字 src_uppercase = string.ascii_uppercase # string_大写字母 src_lowercase = string.ascii_lowercase # string_小写字母 # count = int(input("请输入生成密码个数:")) # 随机生成数字、大写字母、小写字母的组成个数(可根据实际需要进行更改) digits_num = random.randint(1, 6) uppercase_num = random.randint(1, 8 - digits...
714f53be43040f07e0bbae217f387aefbad0b328
patelnisarg6478/assignment
/asnmnt2/armstrong.py
431
3.953125
4
from base import base class armst(base): def run(self): self.number = int(input("Enter a number: ")) sum = 0 temp = self.number while temp > 0: digit = temp % 10 sum += digit ** 3 temp //= 10 if self.number == sum: print(s...
3c9ac061839f1c4ceba16435dbd6e4e8902f185a
patelnisarg6478/assignment
/asnmnt2/base.py
171
3.578125
4
from abc import ABC, abstractmethod class base(ABC): def __init__(self,number): self.number = number @abstractmethod def run(self): return 0
fe1a8dfdaf6540d7991cecc64b53d9dceae226ae
alexjjseppala/a4
/main.py
9,546
3.625
4
# Image compression # # You'll need Python 2.7 and must install these packages: # # scipy, numpy # # You can run this *only* on PNM images, which the netpbm library is used for. # # You can also display a PNM image using the netpbm library as, for example: # # python netpbm.py images/cortex.pnm import sys, os, ma...
af84a06ccbaea2b1271fbdac47675563389d36a6
TeamYI/python
/numberGuessingGame/main.py
487
3.859375
4
# 숫자 맞추기 게임 # 조건 # 1.랜덤으로 숫자를 제시(1-100) # 2. 답을 입력받기 # 3. 업 앤 다운으로 힌트 제공 import random number = random.randint(1,101) while True: answer = input("숫자를 입력해주세요 : ") if not answer.isnumeric(): continue answer = int(answer) if number == answer: print("정답입니다") break elif numbe...
d8e38cc798b4d975c33e912c0c7964866210362c
Hoan1028/CodingBat-Solutions
/Python/Warmup-1/codebat_wm_missing_char.py
742
3.84375
4
#CodingBat Python Warmup-1>missing_char: def main(): #unit test print('Expected Values: \nktten, itten, kittn, i, H, ode, cde, coe, cod, chocolat \nActual:') print(missing_char('kitten', 1), missing_char('kitten', 0), missing_char('kitten', 4), missing_char('Hi', 0), missing_char('Hi', 1), missing_char('code', 0)...
d294e24b818d468eb7cc33a9ea7831ad3c2d6550
Hoan1028/CodingBat-Solutions
/Python/Warmup-1/codebat_wm_diff21.py
547
3.96875
4
#CodingBat Python Warmup-1>diff21: def main(): #unit test print('Expected Values: \n2, 11, 0, 2, 8, 18, 21, 20, 19, 22, 23, 58 \nActual:') print(diff21(19), diff21(10), diff21(21), diff21(22), diff21(25), diff21(30), diff21(0), diff21(1), diff21(2), diff21(-1), diff21(-2), diff21(50)) #Problem: #Given an int n, ...
190e41620dd26f3e91586863319abee353f17344
Lozy/leetcode
/02-SNIP.py
791
3.984375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # CODE: Swap Nodes in Pairs # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # @param a ListNode # @return a ListNode def swapPairs(self, head): if head == ...
ac2035a6ad82c6f41251c0d341451bbfabd4938f
josephdittli/Breakout
/Brick Game/Level.py
10,603
3.609375
4
# Each child class here represents a seperate level that the player can play through. from CollidableObject import * from Position import * import array from abc import ABC, abstractmethod WHITE = (255,255,255) BLACK = (0,0,0) RED = (255, 0, 0) YELLOW = (255, 255, 0) DARKRED = (100, 0, 0) LIGHTGREY = (200...
b9aae7da04c23355ac981714ed7fa24ffdf2c995
Kholdo/Tkinter
/c1.py
279
3.515625
4
#importamos la libreria import tkinter as tk #Creamos una instancia de la clase TK. Asi se crea la root window root = tk.Tk() #Añadimos algunos widgets frame = tk.Frame(root) frame.pack() #ejecutamos el metodo mainloop, que es el que mantiene la ventana visible root.mainloop()
479bf309baffac71e186587e448c4fdaf7236f27
Riddhiagrawal001/Deep-Learning-with-Python
/Recurrent_Neural_Networks/recurrent.py
2,663
3.6875
4
# -*- coding: utf-8 -*- """ Created on Mon May 18 20:25:28 2020 @author: KIIT """ #part-1 data preprocessing import numpy as np import matplotlib.pyplot as plt import pandas as pd #importing the dataset training_set=pd.read_csv("Google_Stock_Price_Train.csv") training_set=training_set.iloc[:,1:2].values...
724dee26df075f39f1e65353b1e986e072735a09
cesarandres8911/Python_exercises
/Web_Scraping/Test_Extract_All-UL_li_url.py
531
3.734375
4
# BeatifulSoup extract the desired data when provided with an HTML or XML document # urllib.request for opening and reading URLs from bs4 import BeautifulSoup import urllib.request # Get and assign all contents from web page to a variable. url = urllib.request.urlopen('https://www.alkosto.com/tv/televisores/ver/samsun...
2889b8ff3682d6c5c2b3345b5fed105a3a7a2b6c
BobbyTaylor82/PY-Game
/.old-verisons/main1.py
738
3.53125
4
import pygame # Initalize the pygame pygame.init() # create the screen # 800 W and 600 h #left to right 0 --> w # top to bottom 0 --> h screen = pygame.display.set_mode((800,600)) # caption and icon pygame.display.set_caption("Space Invaders") icon = pygame.image.load('ufo.png') pygame.display.set_icon(icon) # ...
349d8f6abe4ba35af97bc1402a0118eb1984ec3a
Ethan0pia/School-Work
/cs344-OperatingSystemsI/python/mypython.py
1,286
3.90625
4
########################################################################################################################### ##Author: Ethan Dunham ##Date:7/28/17 ##Assignment: Python project ##Discription: This program creates 3 files with random letters. Then it averages 2 random numbers. #############################...
5e3d8966d9a88678d1f43fcd0a828e8fa5defeb6
mwoitek/applied-machine-learning-python
/assignment_3/Assignment_3_local.py
8,950
3.578125
4
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # formats: ipynb,py:percent # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.8.0 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --...
5335dd09ee2a2e1e4cb4c087bee7eae4b1940b7b
kaue-pessoa/cursoemvideo-python
/cursoemvideo/ex014.py
178
3.578125
4
dia = int(input('Quantos dia com o carro? ')) km = float(input('Quandos quilomentos foram rodados? ')) v = (dia*60) + (km*0.15) print('O total a ser pago e de {:.2f}'.format(v))
c6c6b855c4ec0caaed05af022fd53699ba60d6be
kaue-pessoa/cursoemvideo-python
/pythonteste/aula09.py
331
3.71875
4
#frase = 'Curso em video python' #print(frase[:13]) #frase = ' Curso em video python ' #print(len(frase.strip())) #frase = 'Curso em Video Python' #print(frase.replace('Python', 'Android')) #frase ='Curso em Video Python' #print('Curso' in frase) frase = 'Curso em Vidio Python' dividido = frase.split() print(di...
b962afab4e5049bcd46254bfc7401d75fe7dfb35
mbasaran77/thread_demo
/utility_mdl.py
681
3.609375
4
import threading from time import sleep lock = threading.Lock() def deneme(number): # Sleeps a random 1 to 10 seconds lock.acquire() sleep(3) print("Thread " + str(number) + " slept for " + str(3) + " seconds") lock.release() class sayac(): d2 = 0 def __init__(self): self.d1 =...
19eac08b909a7b580130b163efa31b5f11e548a2
Bricegnanago/genetique_algo
/main3.py
586
3.78125
4
#!/usr/bin/python # -*- coding: latin-1 -*- from urllib3.connectionpool import xrange def permutliste(seq, er=False, k=0): """retourne la liste de toutes les permutations de la liste seq (rcursif) si er=True: limination des rptitions quand seq en a (ex: [1,2,2] """ n = len(seq) if k == n - 1: ...
0a56d5b9ca6983cc29dbe67a48ccb0b52ee9c4c3
BubbaHotepp/code_guild
/python/make_change2.py
606
3.65625
4
def quarters(x): y = x // 25 return y def dimes(x): y = (x - (quarters(x) * 25)) // 10 return y def nickels(x): y = (x - (quarters(x) * 25) - (dimes(x) * 10)) // 5 return y def pennies(x): y = (x - (quarters(x) * 25) - (dimes(x) * 10) - (nickels(x) * 5)) // 1 return y def main(): ...
01c16a7e485e683ba3dce9ee5701d3fb59971597
BubbaHotepp/code_guild
/python/random_password3.py
1,086
3.90625
4
import random import string def random_generator(x,y,z): counter = 0 while counter < x: y.append(random.choice(z)) counter +=1 def lowercase(x): lower = int(input('Enter the number of lowercase letters \ndesired for your password: ')) random_generator(lower,x,string.asc...
b96824853b54624a33730716da977019b9958c3d
BubbaHotepp/code_guild
/python/palindrome.py
505
4.1875
4
def reverse_string(x): return x[::-1] def compare(x,y): if x == y: return True else: return False def main(): user_input = input('Please enter a word you think is an anagram: ') print(user_input) input_reversed = reverse_string(user_input) print(input_reversed) x = co...
7a98eebde3fcb1f3f9a7da75f0ebca1b82c82afb
BubbaHotepp/code_guild
/python/average_numbers.py
272
3.8125
4
def main(): num_list = [5, 0, 8, 3, 4, 1, 6] run_sum = [] x = 0 for i in num_list: x += i run_sum.append(x) y = run_sum[-1] z = len(run_sum) print (f'Running sum is: {y}') print(f'Average is: {y/z}') main()
ef8c1e11905edd1de122e50cb06e0425a38d944f
BubbaHotepp/code_guild
/python/image_manipulation3.py
713
3.578125
4
from PIL import Image, ImageDraw def main(): width = 1000 height = 1000 img = Image.new('RGB', (width, height)) draw = ImageDraw.Draw(img) draw.rectangle(((0, 0), (width, height)), fill='white') draw.rectangle(((525, 400), (475, 700)), fill='blue') draw.rectangle((350, 550, 650, 500), fill...
905f958dbf8d7309f6cdbb57614d65f758263958
Choli4king/Dash_app2
/apps/prepared_csv2.py
932
3.75
4
import pandas as pd from pandas import DataFrame import csv def prepared_csv(location, location2): # read through a csv, change the row you need to then save it to a new file with open(location, 'r') as f: csv_reader = csv.reader(f, delimiter=',') title = next(csv_reader) lines = [...
e9f0d15702e71205e826bf7fdc0fe070539deddd
jz2010927/pycheck.io
/pycheck.io/ELEMENTARY/Popular words.py
707
3.75
4
def popular_words(text, words): dict1 = {} text1 = text.lower() for w in words: dict1[w] = text1.count(w) return dict1 if __name__ == '__main__': print("Example:") print(popular_words(''' When I was One, I had just begun. When I was Two, I was nearly new. ''', ['...
702b13fa684b62a12237f9418d56747e05e3b2ee
happyssun96/Python_Algorithm
/3장 탐색과 정렬/7.py
1,145
3.734375
4
# 순차 탐색 # 입력: 리스트 a, 찾는 값 x # 출력: 찾으면 그 값의 위치, 찾지 못하면 -1 def search_list(a,x): n = len(a) for i in range(0,n): if x == a[i]: return i return -1 v = [17, 92, 18, 33, 58, 7, 33 ,42] print(search_list(v, 18)) # 2 print(search_list(v, 900)) # -1 # 연습문제 7-1 def searching(a,x): n = len(a...
dd38c58a249f1f867368ad871b02ca321fd6b748
tab0r/Week0
/day3/src/library.py
2,621
3.953125
4
class Library(object): ''' A Library class. ''' def __init__(self, books=None): ''' INPUT: - books: iterable of strs (optional) Initialize a library with the given books. If no books given, initialize with no books. All books start checked in. ''' ...
e9bac2547bac4dc0637c3abee43a3194802cbddc
tab0r/Week0
/day2/src/dict_exercise.py
1,762
4.15625
4
def dict_to_str(d): ''' INPUT: dict OUTPUT: str Return a str containing each key and value in dict d. Keys and values are separated by a colon and a space. Each key-value pair is separated by a new line. For example: a: 1 b: 2 For nice pythonic code, use iteritems! Note: ...
53865978cd757741845cb390a3470cf037303034
tab0r/Week0
/day3/src/worldcup.py
2,441
3.6875
4
from datetime import datetime import os import sys class WorldCupResults(object): def __init__(self, directory): ''' INPUT: directory: str ''' self.directory = directory self.data = self._read_all(directory) def _read_all(self, directory): ''' ...
0801908af51842e1f27f166689909072b25b4fa4
koziscool/embankment_6
/e19.py
974
3.703125
4
import time regular_cal = { 1:31, 2:28, 3:31, 4:30, 5:31, 6:30, 7:31, 8:31, 9:30, 10:31, 11:30, 12:31 } leap_year_cal = { 1:31, 2:28, 3:31, 4:30, 5:31, 6:30, 7:31, 8:31, 9:30, 10:31, 11:30, 12:31 } def e19(): def advance_month( year, month, days_from_zero): if year % 4 == 0 and year != 1900: ...
7a9161a910443b6318ec9c2dd4e58c30fb81b0ce
ericshenshs/neurips20_3612
/supporting_functions.py
8,084
3.640625
4
""" A module that provides three supporting functions to help plot Figure 1 to Figure 3 in the paper. """ import numpy as np import activation_functions as af def square_length(psid, psip, lamb=10 ** -3, rho=2, af=af.ReLU): """ A function that returns the limiting squared length V and its limit R. The calc...
a9615bf9592c3e03aa00ec5459e9149b691645c9
momentum-morehouse/house-hunting-with-python-mjhow4
/house_hunting.py
782
4.03125
4
annual_salary = input("Enter Your Annual Salary: ") portion_saved = input("Enter the percent of your salary to save, as a decimal: ") monthly_salary_saved = (float(annual_salary)/12)*float(portion_saved) total_cost = input("Enter the cost of your dream home: ") portion_down_payment = 0.25 * float(total_cost) current_...
1bb6009cc4fcd7025398da4e324b495d3c25620f
Chey1111/pythonConversation
/convo.py
861
3.90625
4
# Copy and paste this online python compiler address # https://repl.it/languages/python3 # Then Copy and paste this code to that window's # editor and hit run > #pythonConversation 12/9/2019 print ("####################") print ("#Python Convesation#") print ("####################") conversation = 1 while conversati...
b350d4fc0a75b1e745d7d4dfd0d3eb29a8c121df
MykolaPavlenkov/Pavlenkov
/HomeWork/HomeWork1/task#6.py
779
4.375
4
x = int(input ('Введите с клавиатуры целое число x: ')) y = int(input ('Введите с клавиатуры целое число y: ')) print("1) Вывести на экран консоли оба числа используя только один вызов print ") print (x,y) print("2) вывод суммы чисел x + y =") c = x + y print (c) print("3) Выполнить целочисленное деление с помощью опер...
044d487a7ac59e14d9ef398f04d860098d1bef35
MHalamu/Pycharm
/DesignPatterns/FactoryPattern/main.py
1,157
3.9375
4
from abc import ABCMeta, abstractmethod class AnimalFactory(object): __metaclass__ = ABCMeta @abstractmethod def create(self): pass class Animal(object): __metaclass__ = ABCMeta @abstractmethod def make_sound(self): pass class Dog(Animal): def make_sound(self): ...
360f00f7d38fa89588606cf429e0c1e9321f8680
mounika123chowdary/Coding
/cutting_paper_squares.py
809
4.1875
4
'''Mary has an n x m piece of paper that she wants to cut into 1 x 1 pieces according to the following rules: She can only cut one piece of paper at a time, meaning she cannot fold the paper or layer already-cut pieces on top of one another. Each cut is a straight line from one side of the paper to the other side of t...
068985053a07a0032bc6b1ddc00f771b9240d453
texyh/bc-python-xv
/excercises/even_numbers.py
110
3.65625
4
def even_numbers(low,high): for i in range (low:high): if i%2 ==0: print i else: print "bad idea"
90073969bd4742af274d725bb507662016f59c37
debanjan-2002/Competitive-Programming
/CodeChef/Long Challenge - 2021-02(February)/Team_Name.py
653
3.578125
4
def union(list1,list2): temp=len(set(list1+list2)) return temp for t in range(int(input())): n=int(input()) input_arr=input().split() ans=0 except_first={} for i in input_arr: left=i[1:] if left in except_first: except_first[left].append(i[0]) else: ...
35110fad514915212c7ac89178d0b4315c44ddda
verpen/Course_Python
/lab01/main.py
1,577
3.703125
4
import math import sys def read_number(): try: x = float(input()) except: print('Неверный символ, повторите ввод: ') return read_number() return x print('Пенегина В. В. ИУ5-55Б') if len(sys.argv) == 4: try: a = float(sys.argv[1]) b = float(sys.argv[2]) ...
f8b8a9dfda10b33a09d484552ed336e466818df6
aerodinamicc/ml_kaggle
/cross_validation.py
3,126
3.5625
4
# -*- coding: utf-8 -*- """ Created on Tue Aug 18 21:34:29 2020 @author: shadow """ import pandas as pd # Read the data import os os.chdir("D:/git/ml_kaggle/") data = pd.read_csv('input/melbourne-housing-snapshot/melb_data.csv') # Select subset of predictors cols_to_use = ['Rooms', 'Distance', 'Landsize', 'Buildin...
1d107c095401f5e60b7df1cdb6d339c3d3ebd4cb
kschulth/micropython-tutorials
/micropython-tut-01-hello-world.ph.py
3,739
3.546875
4
from microbit import * display.scroll("Hello, MicroPython!") from microbit import* display.show(Image.SKULL) from microbit import * boat = Image("05050:" "05050:" "05050:" "99999:" "09990") display.show(boat) shopping=["Eggs"...
dde1c7556c2dd8839d6aa91235e1809c5710ce21
BenjaminNicholson/cp1404practicals
/cp1404practicals/prac_09/sort_files_2.py
713
3.859375
4
""" CP1404 Practical sort_files_2 Benjamin Nicholson Completed 22/10/2020 """ import os def main(): categories = {} os.chdir("FilesToSort") os.chdir("FilesToSort") for filename in os.listdir("."): if os.path.isdir(filename): continue file_extension = filename.split(".")[-...
12b9d7a90eb7d3e8fbec3e17144564f49698e507
BenjaminNicholson/cp1404practicals
/cp1404practicals/Prac_05/word_occurrences.py
401
4.25
4
words_for_counting = {} number_of_words = input("Text: ") words = number_of_words.split() for word in words: frequency = words_for_counting.get(word, 0) words_for_counting[word] = frequency + 1 words = list(words_for_counting.keys()) words.sort() max_length = max((len(word) for word in words)) for word in wo...
f130de72784cf53cf392a96a8cf09c111474bf5c
BenjaminNicholson/cp1404practicals
/cp1404practicals/Prac_05/hex_colours.py
528
4.28125
4
COLOURS = {'AliceBlue': '#f0f8ff', 'Aquamarine1': '#7fffd4', 'AntiqueWhite': '#faebd7', 'azure1': '#f0ffff', 'aquamarine4': '#458b74', 'azure4': '#838b8b', 'blue1': '#0000ff', 'BlueViolet': '#8a2be2', 'brown3': '#cd3333'} print(COLOURS) choice = input("Which colour do you want to pick? ") while ...
f33f8bd7c4d321bab77cb808fd26eecef8c795ca
HHariHHaran/Coding-File
/t.py
91
3.78125
4
x=int(input("Enter the first number")) y=int(input("Enter the second number")) print(x**y)
cddcbe1821f1813b09b9ee495e1d279228b155b1
HHariHHaran/Coding-File
/alphabets.py
106
3.8125
4
r=input() print(r) if(r>='a') print("alphabets:") elseif(r>='A") print("alphabets:") else print("No:")
40e7db4c4ab538a7ecaceb44569b873d8340f3a5
ihantola/pythonbirds-en
/phase.py
3,588
3.59375
4
# -*- coding: utf-8 -*- from itertools import chain from actors import ACTIVE # Games's Statuses VICTORY = 'VICTORY' DEFEAT = 'DEFEAT' ON_GOING = 'ON_GOING' class Point(): def __init__(self, x, y, character): self.character = character self.x = round(x) self.y = round(y) def __eq_...
a44221832be1eece6cbcbd78df99a8dcc4aea9ab
mcampo2/python-exercises
/chapter_03/exercise_04.py
539
4.59375
5
#!/usr/bin/env python3 # (Geometry: area of a pentagon) The area of a pentagon can be computed using the # following formula (s is the length of a side): # Area = (5 X s²) / (4 X tan(π/5)) # Write a program that prompts the user to enter the side of a pentagon and displays # the area. Here is a sample run: # En...
66106c9065c8dcabaa8a094326a2b601cdf07524
mcampo2/python-exercises
/chapter_03/exercise_11.py
523
4.34375
4
#!/usr/bin/env python3 # (Reverse numbers) Write a program that prompts the user to enter a four-digit int- # ger and displays the number in reverse order. Here is a sample run: # Enter an integer: 3125 [Enter] # The reversed number is 5213 reverse = "" integer = eval(input("Enter an integer: ")) reverse += str(...
09fb28996aa732c01df70d674a369fafa05e0939
mcampo2/python-exercises
/chapter_01/exercise_18.py
410
4.5
4
#/usr/bin/env python3 # (Turtle: draw a star) Write a program that draws a star, as shown in Figure 1.19c. # (Hint: The inner angle of each point in the star is 36 degrees.) import turtle turtle.right(36+36) turtle.forward(180) turtle.right(180-36) turtle.forward(180) turtle.right(180-36) turtle.forward(180) turtle....
b39fc4b4543d890072f04ce215d29dc50827c3ff
mcampo2/python-exercises
/chapter_03/exercise_16.py
2,135
4.53125
5
#!/usr/bin/env python3 # (Turtle: draw shapes) Write a program that draws a triangle, square, pentagon, # hexagon, and octagon, as shown in Figure 3.6b. Note that the bottom edges of # these shapes are parallel to the x-axis. (Hint: For a triangle with a bottom line # parallel to the x-axis, set the turtle's heading t...
b0c6434539536ee3c7db23fb6977ca940037d147
mcampo2/python-exercises
/chapter_03/exercise_02.py
1,594
4.53125
5
#!/usr/bin/env python3 # (Geometry: great circle distance) The great circle distance is the distance between # two points on the surface of a sphere. Let (x1, y2) and (x2, y2) be the geographical # latitude and longitude of two points. The great circle distance between the two # points can be computed using the follow...
a2bfeb6f2d313e1ac6adaba38de4d508acff7b0e
mcampo2/python-exercises
/chapter_01/exercise_12.py
778
3.984375
4
#!/usr/bin/env python3 # (Turtle: draw four squares) Write a program that draws four squares in the center # of the screen, as shown in Figure 1.18a. import turtle # SW turtle.right(90) turtle.forward(50) turtle.right(90) turtle.forward(50) turtle.right(90) turtle.forward(50) turtle.right(90) turtle.forward(50) # S...
e4c59a6991788b320fdfd4aeea0e8c894d403d39
mcampo2/python-exercises
/chapter_02/exercise_06.py
680
4.46875
4
#!/usr/bin/env python3 # (Sum the digits in an integer) Write a program that reads an integer between 0 and # 1000 and adds all the digits in the integer. For example, if an integer is 932, the # sum of all it's digits is 14. (Hint: Use the % operator to extract digits, and use the //) # operator to remove the extract...
ebb74354b22feb3d6d6a27b546111115d4ae8964
praisethedeviI/1-course-python
/fourth/pin_checker.py
788
4.125
4
def check_pin(pin): nums = list(map(int, pin.split("-"))) if is_prime_num(nums[0]) and is_palindrome_num(nums[1]) and is_a_power_of_two(nums[2]): message = "Корректен" else: message = "Некорректен" return message def is_prime_num(num): tmp = 2 while num % tmp != 0: ...
0e3f07c36ca5ab57fdbd8cc34b6c7aed9b21a71b
praisethedeviI/1-course-python
/third/counties_cities.py
237
3.734375
4
N = int(input()) cities = {} for i in range(N): country, *cities_tmp = input().split() for j in cities_tmp: cities[j] = country M = int(input()) for i in range(M): city = input() print(cities[city])
3ecbac99369228f92dcef89d334a4b45dd2c03c8
tmpbook/play-with-python
/yield/coroutines.py
329
3.734375
4
def printer(): counter = 0 while True: string = (yield) print('[{0}] {1}'.format(counter, string)) counter += 1 if __name__ == '__main__': p = printer() next(p) p.send('Hi') p.send('My name is 临书.') p.send('Bye!') # output: # [0] Hi # [1] My name is 临书. # [2] Bye!...
0f241e6bbcecfaf61320180174a1cf2a6f0e3f2b
EdwinJUGomez/CDA_2021_EdwinJUGomez
/02-python/q04/question.py
742
3.640625
4
## ## Programación en Python ## =========================================================================== ## ## La columna 3 del archivo `data.csv` contiene una fecha en formato ## `YYYY-MM-DD`. Imprima la cantidad de registros por cada mes separados ## por comas, tal como se muestra a continuación. ## ## Rta/...
6a5019513f3ce7ea6a4d7020e8d170d6c9d1bab8
WinterFor/WinterFor_Python_work
/sequence_base_counting.py
283
4.09375
4
#!/user/bin/env python # count "AT"/"TA"/"GC"/"CG" in a sequence sequence = input("Please Enter the sequence:") searching_number = ['AT', 'TA', 'GC', 'CG'] for base in searching_number: n = sequence.count(base) print('There have ' + str(n) + str(base) +' in the sequence.')
83b6f59af4bd23c69016f8f3c7fded5bac6934bb
shasdemir/algorithms
/L1/L1.py
4,055
3.96875
4
def russian(a, b): x = a; y = b z = 0 while x > 0: if x % 2 == 1: z = z + y y = y << 1 x = x >> 1 return z def countdown(x): y = 0 while x > 0: x = x - 5 y = y + 1 print y return y def time(n): """ Return the number of steps necessary to ca...
cfd9720ed9f77cfa8e50baa639d24e9fa7808755
BlyatTukan/ADIM
/Piotrek/babelki.py
611
3.59375
4
import random def Sortowanie(Lista): liczba = len(Lista) for Petla1 in range(liczba-1): for Petla2 in range(0, liczba-Petla1-1): if Lista[Petla2] > Lista[Petla2+1] : Lista[Petla2], Lista[Petla2+1] = Lista[Petla2+1], Lista[Petla2] Zbiór = [] x = random.randrange(0,20) ...
65378f3f4696073f33c1708935fc45f8deb2e5d1
ishaansathaye/APCSP
/programs/guessingGame.py
1,677
4.125
4
# from tkinter import * # # root = Tk() # root.title("Computer Guessing Game") # root.geometry("500x500") # lowVar = StringVar() # highVar = StringVar() # labelVar = StringVar() # guessVar = StringVar() # # def range(): # lowLabel = Label(root, textvariable=lowVar) # lowVar.set("What is the lower bound of the r...
26e30f292e7995041db81c2654e9443228229d6f
ishaansathaye/APCSP
/problems/sum13.py
682
4.03125
4
# Return the sum of the numbers in the array, returning 0 for an empty array. Except the number 13 is very unlucky, # so it does not count and numbers that come immediately after a 13 also do not count. # sum13([1, 2, 2, 1]) → 6 # sum13([1, 1]) → 2 # sum13([1, 2, 2, 1, 13]) → 6 def sum13(nums): sumOfArray = 0 ...
8e680f9a50ec6b6cf1cc025da0c7dc8fdd571a39
usamashafiq/small-health-management-system
/First.py
1,931
3.765625
4
def getdate(): import datetime return datetime.datetime.now() print(" HEALTH MANAGEMENT SYSTEM") print(" NUMBER OF MEMBER") print(" Rohan for 1") print(" Hammad for 2") x = int(input()) if x == 1: print("Hi Rohan") print("Choose the file : READ OR WRITE MODE WRIT...
da2f46363ed9fd4c5ab6645d000626fab2e35932
sholguinASC/All-Star-Code
/mash_up.py
936
4.0625
4
from random import * from time import sleep list1 = ["Sophia", "Angela", "Emily", "Olivia", "Isabella", "Stephanie", "Wendy"] #list2 = ["janitor", "Street Sweeper", ""] list3 = ["stick to a metro card", "buy a scooter", "just walk","buy a horse"] list4 = ["mansion","apartment","house","none, just go and live under ...
7e73cc0f67bc3be93ab600fcf2aa94c7a8cb78e9
dbane744/rougelike
/menus.py
6,949
3.625
4
import libtcodpy as libtcod """ This module encapsulates the different menus within the game. """ def menu(con, header, options, width, screen_width, screen_height): """ Creates a new console to hold any menus that may be used e.g the inventory. It then blits this menu to the root console. :param con:...
58ca2734e89ce5cc1b049185abb780d971772cea
Asish-Kumar/Python_Continued
/bubble_sort.py
342
3.984375
4
# list1 = [] # for _ in range(int(input("Enter number of elements: "))): # list1.append(int(input())) # take list elements from user input # # for i in range(0, len(list1)-1): # for j in range(0, len(list1)-i-1): # if list1[j] > list1[j+1]: # list1[j], list1[j+1] = list1[j+1], list1[j] # s...
920ed667628f9fbb5783d72dd234a372c1f0ab87
Asish-Kumar/Python_Continued
/CountingValleys.py
743
4.25
4
""" A mountain is a sequence of consecutive steps above sea level, starting with a step up from sea level and ending with a step down to sea level. A valley is a sequence of consecutive steps below sea level, starting with a step down from sea level and ending with a step up to sea level. example input : UDDDUDUU """ d...
6925977b4e9bc4e83a4a4b2666d5c65f2c334d48
kxtan/covid-tracker
/data_updater.py
742
3.5
4
import requests import pandas as pd import datetime as dt import time def download_data(url): r = requests.get(url, 'data/data_in_excel.xlsx') with open('data/data_in_excel.xlsx', 'wb') as f: f.write(r.content) def convert_excel_to_csv(infile, outfile): excel_file = pd.read_excel(infile) exce...
016fe4170470cfaf3fd745f753f5054580b8519a
othma125/EventsVRP
/ListsEdit.py
1,502
3.875
4
class motion: def __init__(self, Id1: int, Id2: int): """ Local search movement between two indexes :param Id1: :param Id2: """ self.Index1 = Id1 self.Index2 = Id2 def Swap(self, li: list) -> None: if self.Index1 != self.Index2: ...
12a3ba303c10cc509f8629d5e74a6da0fd146236
aleksandraandrea-zz/dotfiles
/make_dotfiles.py
3,319
3.703125
4
import glob import os from shutil import copy from argparse import ArgumentParser # These are all the files that are within this directory which are end with the # file extension `.dotfile`. this_file_dir = os.path.dirname(os.path.abspath(__file__)) file_dir = os.path.join(this_file_dir, 'dotfiles') FILES = glob.glob...
74c3f0115885b12b47fb5f8c7163fef555739ba5
jtrauer/AuTuMN_framework
/autumn_model/tool_kit.py
3,391
4.09375
4
""" Note that this module is intended only to contain stand-alone functions for use by multiple other modules. Object-oriented structures are not intended to be kept here. """ def find_first_list_element_at_least_value(list, value): """ Simple method to return the index of the first element of a list that is...
000607d33e08a946e1dad70965f401ada1654f9e
sublingbling/coding-everyday
/11_28_2016_binary-tree-maximum-path-sum/chang.py
836
3.734375
4
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param root: The root of binary tree. @return: An integer """ def maxPathSum(self, root): maxAnyToAny, _ = self.maxPathHelper(roo...
23f8add91d117ce101f0abe7bd12fffa18cacfdf
sublingbling/coding-everyday
/11_28_2016_binary-tree-maximum-path-sum/up.py
874
3.765625
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def maxPathSum(self, root): """ :type root: TreeNode :rtype: int """ def...
29bade0dfa0e5e8700a4cc27cc9038a6116c7453
sublingbling/coding-everyday
/11_16_2016-convert-sorted-array-to-binary-search-tree/chang.py
410
3.5
4
class Solution: """ @param A: a list of integer @return: a tree node """ def sortedArrayToBST(self, A): if A is None or len(A) == 0: return None mid = len(A) / 2 root = TreeNode(A[mid]) root.left = self.sortedArrayToBST(A[0:mid])...
f7b163605cd4a1ac6f7da54dbbda99c7e2f9c11c
rudyvallejos/GestionItems
/lib/python2.6/site-packages/webhelpers/pylonslib/flash.py
12,410
3.65625
4
"""Accumulate messages to show on the next page request. The ``Flash`` class is useful when you want to redirect to another page and also show a status message on that page, such as "Changes saved" or "No previous search found; returning to home page". THE IMPLEMENTATION DEPENDS ON PYLONS. However, it can easily be...
cb2ca7b19c3b96d04a3838482aa688a81982bb4a
rudyvallejos/GestionItems
/lib/python2.6/site-packages/webhelpers/html/grid.py
12,727
3.5
4
"""A helper to make an HTML table from a list of dicts, objects, or sequences. A set of CSS styles complementing this helper is in "webhelpers/html/public/stylesheets/grid.css". To use them, include the stylesheet in your applcation and set your <table> class to "stylized". The documentation below is not very clear....
29048a338f7630454e029280f3dd5fc0e7205093
Alex-Overlord/L2-S3
/SE/Python/Quizz/nbrPremPositif.py
438
3.609375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys ### Affiche les nombres premiers contenus dans les n premiers entiers positifs def estPremier(n) : b = True for i in range (2, n) : if n%i==0 : b = False return b def nbrPremPositif(n) : li = [] for x in range ...
5e36170af1209383fed6749d2c7302971cd6c354
dhalimon/Turtle
/race.py
1,883
4.25
4
import turtle import random player_one = turtle.Turtle() player_one.color("green") player_one.shape("turtle") player_one.penup() player_one.goto(-200,100) player_two = player_one.clone() player_two.color("blue") player_two.penup() player_two.goto(-200,100) player_one.goto(300,60) player_one.pendown() player_one.circl...
0331cd6f41a1a3b650a7b7780d56907d5f85ec49
johnduffy89/john
/Documents/APCSP/hellogit.py
792
3.9375
4
# comment print("Hello World!") a = 6 b = 5 print(a + b) #how to make a list myList = [1, 2, 3, 4, 3, 2, 1] #how to access elements of a list print(myList[0:6:2]) # from index 0 to 6, skip by 2 phrase = 'Catch the Dog' phrase[2] # t phrase[4] # h phrase[-1:0:-3] #how to write a function def sumFunction(a, b): ret...
a33bc22a60b7a6e633bd417c0e94ea203aa66728
ariadnimac/algorithms_in_python
/polyominoes/count_fixed_polyominoes.py
2,986
3.515625
4
import sys import pprint #method that creates graph def create_graph(n): g={} counter =0 for x in range(2-n, 0): counter = counter + 1 for y in range(1,counter+1): k1 = False k2 = False k3 = False k4 = False if (y>0 or (y==0 ...
b12ee0f091292654c403a930dc6e3a031793c548
mannygonzalezj/python
/comments/commentDrills.py
530
3.546875
4
''' For this assignment you should read the task, then below the task do what it asks you to do. EXAMPLE TASK: ''' #EX) Make a single line comment #This is a single line comment ''' END OF EXAMPLE ''' ''' START HERE ''' #1) Make a single line comment. #okay #2) Make a multi-line comment. ''' I can do that too '...
3f54cc3e719933a3b53ff0bc4048612363d68bd0
Quanghuy99/code_daily
/AreaRectangle.py
548
3.921875
4
class Rectangle: 'đây là rectangle class' # một phương thức dùng để tạo đối tượng (constrictor) def __int__(self,width,height): self.width = width self.height = height def getwidth(self): return self.width def getheight(self): return self.height #phương thức tí...
5c436ec176bf159de705b2f41b533122dc0b0365
Quanghuy99/code_daily
/shapearea.py
134
3.8125
4
def shapearea(n): area = 1 while n >1 : area = area + (n-1)*4 n=n-1 return print(area) n = 3 shapearea(n)
82d996e96daf173f66a60f46f31d25e461b7a9fe
hungnv21292/Machine-Learning-on-Coursera
/exe2/costFunctionReg.py
1,655
3.8125
4
def costFunctionReg(theta, X, y, lambda_reg): # COSTFUNCTIONREG Compute cost and gradient for logistic regression with regularization # J = COSTFUNCTIONREG(theta, X, y, lambda) computes the cost of using # theta as the parameter for regularized logistic regression and the # gradient of the cost w.r.t. to the para...
e346adc9388fadbb152c9c5698b5425a8f78afd1
hungnv21292/Machine-Learning-on-Coursera
/exe1/gradientDescent.py
1,511
4.125
4
import numpy as np from computeCost import computeCost def gradientDescent(X, y, theta, alpha, num_iters): #GRADIENTDESCENT Performs gradient descent to learn theta # theta = GRADIENTDESENT(X, y, theta, alpha, num_iters) updates theta by # taking num_iters gradient steps with learning rate alpha ...
853346d1d03ce59f43e2708a10b8bbf66d2ee0f6
SantiagoChaparro/Analisis-Numerico
/Taller 2/taller2.py
481
3.609375
4
def funcion(vector,ekis): resultado=0 for n in range(0,len(vector)): if(n==0): resultado=resultado+vector[n] else: resultado=vector[n]+ekis*resultado #end if #end for return resultado #end def #def main vector =[10, 20, 30, 5,0] ekis= 8 print ("Para los coeficientes: ") print(vect...
ef0bfa841bdb62c42f6a489aced4fa818211326a
thetronjohnson/SS-Lab
/file-organization/two-level.py
3,186
3.65625
4
from termcolor import colored class Directory: def __init__(self,name): self.name = name self.files = [] self.folders = {} def createfile(self,file): if(file not in self.files): self.files.append(file) print(f"File {file} has been created inside the directory {self.name}") else: print(f"File {file...
e9787d15bf6d7199c3a4fd9a7d10131dec51abdd
jpennell/harvest
/harvest/utils.py
926
3.6875
4
def escape(text): """ HTML escape a string escape('< > ' " &') -> '&lt; &gt; &apos; &quot; &amp;' """ html_escape_table = { "&": "&amp;", '"': "&quot;", "'": "&apos;", ">": "&gt;", "<": "&lt;", } return "".join(html_escape_table.get(c, c) ...
5cce1caf8666c82ea5f180d45188272a82e290d3
Anupam-dagar/Work-with-Python
/Very Basic/remove_vowel.py
435
4.5625
5
#remove vowel from the string. def anti_vowel(text): result = "" for char in text: if char == "A" or char == "a" or char == "E" or char == "e" or char == "I" or char == "i" or char == "O" or char == "o" or char == "U" or char == "u": result = result else: result = ...
cd7208baaca31499b8d8c488d35787bf7179219d
Anupam-dagar/Work-with-Python
/Scripts/rename_files.py
534
3.953125
4
#rename file to contain only letters and no numbers from 0-9. #replace "alphabet" with the folder name and make sure it is in the same directory as of this script. import os def rename_files(): file_list = os.listdir("alphabet") saved_path = os.getcwd() os.chdir("alphabet") for file in file_list: ...