blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
7234a33a3295c694ce51d2719da4e096c818168f
arononeill/Python
/Sorting/selectionSort.py
440
3.640625
4
def selectionSort(list): for fillslot in range(length-1,0,-1): GreatestPosition = 0 for location in range(1,fillslot+1): if list[location]>list[GreatestPosition]: GreatestPosition = location temp = list[fillslot] list[fillslot] = list[GreatestPosition] li...
e54903690eceffc1bd7b49faa2db0f79d111f974
TheManyHatsClub/EveBot
/src/helpers/fileHelpers.py
711
4.125
4
# Take a file and read it into an array splitting on a given delimiter def parse_file_as_array(file, delimiter=None): # Open the file and get all lines that are not comments or blank with open(file, 'r') as fileHandler: read_data = [(line) for line in fileHandler.readlines() if is_blank_or_comment(line...
e2fe6cea47113c933eb4202561d53411229b1240
MuhamadRamadan/Explore_US_Bikeshare_Data
/bikeshare.py
15,941
4.28125
4
import time import pandas as pd from tabulate import tabulate # Pretty-print tabular data in Python, a library and a command-line utility. #import numpy as np CITY_DATA = { 'chicago': 'chicago.csv', 'new york': 'new_york_city.csv', 'washington': 'washington.csv' } def get_filters(): ""...
c70566c6b0a4e05b9278373b358c14e21e6ac103
Natan10/ProjetoAquario
/Classes/luz.py
941
3.828125
4
#Classe Portao # Nome_Luz : # Ligada: Ligada / Desligada # Ativar: Liga / Desliga a Luz # Potencia: Ajusta a potência da luz, se possível... Como fazer um método opcional? acho melhor não fazer kkk import random import time class Luz: def __init__(self,nome, ligada = 0, tempo_ligada = 0): self.nome = nome ...
07a84d9a07ae1be948cb524f53a03a866f62ade7
hmercado237/hmercado237.github.io
/chatbot2.py
1,232
4.09375
4
# --- Define your functions below! --- def intro(): print("HELLO, I AM CHATBORT") print("LET'S TALK!") print("[INSTRUCTIONS FOR USE]") # RPS # Different bort personalities def choosePersonality(): print("Choose a personality to talk to. You can choose:") choice = input("Mean, Nice, or Nervous") ...
a37e4d06363f8ead6644dff84add4cf30cd8bbd3
taucsrec/recitations
/2018a/Michal/rec1/tester_example.py
284
3.8125
4
print ("hi") def check_parity(n): if n % 2 == 0: return "even" else: return "odd" def test(): if check_parity(0) == "odd": print("error in function check_parity") if check_parity(1) == "even": print("error in function check_parity")
2c60fa8bde0253965de757c32599fc6be923d46e
rajatmann100/rosalind-bioinformatics-stronghold
/p3-revc.py
398
3.59375
4
# read file file = open("./data/rosalind_revc.txt", "r") input_str = file.read() print(input_str) reverse_str = input_str[::-1] def getComplement(bp): switcher = { "A": "T", "T": "A", "C": "G", "G": "C" } return switcher.get(bp, "nothing") COMP_STR = '' for x in reverse_...
6af6841b7adc41f77845bb13eeee3bd855bc388e
pviktoria/Python
/biggest.py
287
3.875
4
def multinumber(): list=[] for i in range(0,5): number=int(input("Szám: ")) list.append(number) multiplenum=multiple(list) print("A szorzat: {:^10}".format(multiplenum)) def multiple(list ): sum= 1 for i in list: sum*=i return sum multinumber()
18e427e8cf326d2e04699da0a321443d1a5b9ba1
pviktoria/Python
/harmadik2_nehez.py
805
3.53125
4
Név= 'Pap Viktória, ' Osztály= 'Szoftverfejlesztő-esti, ' Dátum= '2020-12-16, 15m' Feladat='Állatok nevét és súlyát adja meg' print(Név, Dátum) print(Feladat) import allat állatfajok = [] for _ in range(3): fajnév = input('Add meg egy állatfaj nevét! ') tömeg = input('Hány kilogramm a tömege egy példánynak?...
0c861151d4f8fb374ae5a766dab0a25567722099
yauheni-sarokin/for_tests
/tests/test006/main3.py
423
3.640625
4
class Property: def __init__(self) -> None: self._my_value = None @property def my_value(self) -> int: return self._my_value*5 @my_value.setter def my_value(self, my_value: int) -> None: self._my_value = my_value*3 if __name__ == '__main__': _property ...
0b62cb1c19d6b1ab85cd314d407acc390dd4812c
yauheni-sarokin/for_tests
/tests/test044/main5.py
360
3.84375
4
# Generators def repeater(value): while True: yield value def repeat_three_times(value): yield value yield value yield value if __name__ == '__main__': # for x in repeater('Hi'): # print(x) obj = repeater('hey') print(obj.__next__()) print(next(obj)) for x in rep...
2a153ef02f9ea6ef69af466991f5e91f4052712e
yauheni-sarokin/for_tests
/tests/test040/main3.py
499
3.890625
4
# Instance, Class, and Static Methods # Demystified1 class MyClass: def method(self): return 'instance method called', self @classmethod def class_method(cls): return 'class method called', cls @staticmethod def staticmethod(): return 'static method called' if __name__...
b196230fec17e6b74df20eb28ba2adb05525b3ab
yauheni-sarokin/for_tests
/tests/test038/main.py
426
3.84375
4
# abstract base classes from abc import ABCMeta, abstractmethod class Base(metaclass=ABCMeta): @abstractmethod def foo(self): pass @abstractmethod def bar(self): pass class Concrete(Base): def bar(self): pass def foo(self): pass if __name__ == '__main__':...
53ee9c32a16ed0788b8bc85fd7c656f7f78e0620
cvpe/Pythonista-scripts
/Map for RocketBlaster05.py
20,119
3.578125
4
''' NOTE: This requires the latest beta of Pythonista 1.6 (build 160022) Demo of a custom ui.View subclass that embeds a native map view using MapKit (via objc_util). Tap and hold the map to drop a pin. The MapView class is designed to be reusable, but it doesn't implement *everything* you might need. I hope that the ...
10ee46c1b8740ec9456a4e84a74669f0dc7b91c3
cacquani/mastermind_py
/mastermind.py
1,339
3.796875
4
import random print('Create secret code!') colours = [ 'R', 'Y', 'G', 'B', 'K', 'W' ] def create_code(): return random.choices(colours, k=4) def calculate_score(code, guess): correct = 0 included = 0 indexes = [] for index, element in enumerate(guess): if code[index] == element: ...
9861031db8acdcc1aad8164d7ff8c3464ede2745
Jaminy/Email-Mining
/Snippets/PN.py
784
3.546875
4
>>> y=re.findall(r'\d+', 'hello +94716772265') >>> y ['94716772265'] >>> print y ['94716772265'] >>> z=phonenumbers.parse("+" + y[0]) >>> print z Country Code: 94 National Number: 716772265 >>> z=phonenumbers.parse("+", "US") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "build/bdist.l...
52b7f866a0a7e7169857af6d225cefcd3b059214
Kamali29/OpenCV
/2.Basic Functions/Erosion and Dilation.py
786
3.640625
4
# Dilation adds pixels to the boundaries of objects in an image, # while erosion removes pixels on object boundaries. # It is normally performed on binary images. import cv2 import numpy as np # Reading the input image img = cv2.imread(r'C:\Users\Lovely\Desktop\Open_CV\Resources\lena.png', 0) # Taking a m...
4bd955a7d74e3c3c6979549222551c99eeab73e1
oscar510/built-by-titan
/oscar01.py
897
3.640625
4
import turtle def draw_square(): square_size = 100 turtle.forward(square_size) turtle.right(90) turtle.forward(square_size) turtle.right(90) turtle.forward(square_size) turtle.right(90) turtle.forward(square_size) def draw_circles(): turtle.back(60) turtle.left(90) turtl...
1db81f19b60305fcc9da2fb4244037e095647b1b
HeizerSpider/Reinforcement_Learning
/mountaincar.py
1,134
3.578125
4
import gym import numpy as np env = gym.make("MountainCar-v0") env.reset() print(env.observation_space.high) # sometimes we engage in some environments in which we dont know these values and hence we have to learn for awhile before we actually get to know these values print(env.observation_space.low) print(env.action...
63d84a0ec7ecdcff9c8bed3ad6f50888e9cfb664
ameya-ganchha/python-challenge
/PyBank/main.py
1,991
3.640625
4
import csv budget_csv = 'budget_data.csv' def print_file(statement, file_pointer) : print (statement) file_pointer.write(str(statement) + "\n") with open('myfile.txt',"w") as f : with open(budget_csv, 'r') as csvfile: # Split the data on commas csvreader = csv.reader(csvfile, delimite...
66b628fb453b1704150bd027fe966a9835f15b2f
davidjanghoonlee/python-exercise-files
/ex43.py
11,398
3.9375
4
# from python import exit and radom integer generator modules from sys import exit from random import randint # class that has-a function "enter" that takes self parameter class Scene(object): def enter(self): print "Unconfigured scene. Subclass it and implement enter()." exit(1) # class with: ...
97c80a0bc24deb72d908c283df28b314454bcfc5
KHilse/Python-Stacks-Queues
/Queue.py
2,139
4.15625
4
class Node: def __init__(self, data): self.data = data self.next = None class Queue: def __init__(self): self.head = None def isEmpty(self): """Returns True if Queue is empty, False otherwise""" if self.head: return False return True def enq...
efb28bd3bedf010ba4cc3fc2692df19968d6f24c
rohit-nair/neuralist
/scripts/mapping.py
1,080
3.53125
4
#!/usr/bin/env python import json import sqlite3 DUPE_FILE = "lastfm_duplicates.txt" DB_FILE = "data/lastfm_similars.db" conn = sqlite3.connect(DB_FILE) cursor = conn.cursor() cursor.execute("""Select * from top100_similars;""") all_data = cursor.fetchall() print "all_data", len(all_data) cursor.execute("""CREATE T...
8e889b7bcf53c0d9704df68b21bdbc25e70335ae
alpha-martinez/scripting-with-python
/my-script.py
1,047
3.875
4
# # open a file # alpha_file = open('alpha-text', 'r') # numbers = [1, 2, 3] # for i in range(len(numbers)): # num = numbers[i] # alpha_file.write("{}\n".format(num)) # alpha_file.close() # # close a file # print(alpha_file.read()) # alpha_file.close() # open a file rome_file = open('rome.txt', 'a') num...
485458ce7505e832f81aab7520d9fa16db630e89
kalstoykov/Python-Coding
/isPalindrome.py
1,094
4.375
4
import string def isPalindrome(aString): ''' aString: a string Returns True if aString is a Palindrome String strips punctuation Returns False otherwise. ''' alphabetStr = "abcdefghijklmnopqrstuvwxyz" newStr = "" # converting string to lower case and stripped of extra non alphabet c...
40a293a5218de8b7594049e1f06a4c0d18988b14
Freemont7/dat119spr19
/Campbell_Week_8.py
4,115
4.53125
5
# -*- coding: utf-8 -*- """ Chris Campbell 3/27/19 Python 1 - Dat 119 - Spring 2019 Week 8 "We’re going to create an application to track a user’s todo list! Our application will maintain at least two lists: 1) items that need to be done and 2) items that have already been completed." """ #create todo list and comp...
fb471f247f81c03e3cd90bf680e9b2d0646c27e1
minsau/hacker-rank
/algorithms/kangaroo.py
352
3.875
4
def kangaroo(x1, v1, x2, v2): # Write your code here start_diff = x1 - x2 velocity_diff = v2 - v1 if (v2 > v1 or velocity_diff == 0): return 'NO' if((start_diff % velocity_diff) == 0): return 'YES' else: return 'NO' print(kangaroo(0, 2, 5, 3)) print(kangaroo(0, 3, 4, 2)...
06007fc223dccb013f734a94f408a4260e7de7c5
annash2005/python_1
/natural#1-n.py
170
3.765625
4
command = input ("Put in the number") #Let's convert cool to interger com_int = int(command) import time num = 1 while(num <= com_int ): print(num) num = num +1
7f3f92769c490f23ade030172f02e0e0ce102774
annash2005/python_1
/while.py
86
3.703125
4
import time num = 1 while(num <= 10 ): print(num) num = num +1 print("Anna Is AMAZING")
fac8d1383134a37e65843b3b83ac424d1d7e277c
maxgamesNL/lessonup.app_Bot
/main.py
1,260
4.0625
4
import time #This is the main file of the project. #On editing write documentation for easy editing. Running = True #Explains what the program is to the user. def Intro(): print("Welcome to LessonUp Bot!!!") time.sleep(1.5) print("This bot is able to perform") time.sleep(1.5) print("A lot of acti...
875a71a620c74bec5b2772ca0e8be779b4b7a52a
JeffCalvert01P/fullstack-nanodegree-vm
/vagrant/tournament/tournament_ec.py
6,400
3.59375
4
#!/usr/bin/env python # # tournament.py -- implementation of a Swiss-system tournament # import psycopg2 import tournament_dbsql_ec def connect(): """Connect to the PostgreSQL database. Returns a database connection.""" return psycopg2.connect("dbname=tournament") def deleteMatches(): """Remove all th...
cd019d3abb62ba7430aefe5042069ba838d787ec
lfbessegato/Treinamento_Python_Udemy
/Exercicio05.py
274
3.828125
4
print('Exercício05 - Dicionário de Cores') cores={'verde':'Green','amarelo':'Yellow','azul':'Blue','vermelho':'Red','preto':'Black'} cor=input('Digite a Cor para traduzir: ').lower() traducao = cores.get(cor,'Esta informação não consta no dicionário') print(traducao)
7047450bb38b74d3df8f0544b5ca789b0c3a73c6
Takkarpool/Proyecto-Formales
/Habitacion.py
1,055
4.03125
4
class Habitacion: """ Clase que representa una habitación """ def __init__(self, xInicial, yInicial ,ancho, alto, numero): """ Constructor de una habitacion :param xInicial: posición x inicial del Habitación :param yFinal: posición y inicial del Habitación :param ...
df1c2b27258ba4d3c57f79cd45d680527027ed5e
onelieV/neorl
/neorl/evolu/bat.py
15,736
3.5
4
# -*- coding: utf-8 -*- #""" #Created on Fri Jun 18 19:45:06 2021 # #@author: Devin Seyler and Majdi Radaideh #""" import random import numpy as np import math import joblib from neorl.evolu.discrete import mutate_discrete, encode_grid_to_discrete, decode_discrete_to_grid #Main reference of the BAT algorithm: #Xie, J...
e8681b0161825b2dbadf5c906eb1488fc94f5553
onelieV/neorl
/build/lib/neorl/parsers/TuneChecker.py
3,810
3.609375
4
""" This class parses the TUNE block and returns a checked dictionary containing all TUNE user parameters """ import numpy as np import os class TuneChecker(): """ This class checks the input for any errors/typos and then overwrites the default inputs by user ones Inputs: master_p...
e19cdf1f2a6f0c8bcca403c8071f2901117cdc08
Leona-qy/machine-learning-web-applications
/punctuation/punctuation/removePunctuations.py
178
3.90625
4
def Punctuation(string): punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' for x in string.lower(): if x in punctuations: string = string.replace(x, "") return string
55d24682fa25a8836fec14d71db36ff268ec3420
DroidFreak32/7th_semester
/Python/college_notes/tkinter/1-window/1-window.py
277
3.890625
4
Example:1a import tkinter # note that module name has changed from Tkinter in Python 2 to tkinter in Python 3 window = tkinter.Tk() # Code to add widgets will go here... window.mainloop() Example:1b import tkinter window=tkinter.Tk() window.title("First tkinter") window.mainloop()
13776998dc9b97cf329928fa2a5632f4be87d37a
Crowiant/learn-homework-1
/2_if2.py
1,196
4.3125
4
""" Домашнее задание №1 Условный оператор: Сравнение строк * Написать функцию, которая принимает на вход две строки * Проверить, является ли то, что передано функции, строками. Если нет - вернуть 0 * Если строки одинаковые, вернуть 1 * Если строки разные и первая длиннее, вернуть 2 * Если строки разные и вторая с...
3851d7501e886dfc0ea0ce0e7ff601cdc4703e06
alihasan13/python_hackerrank
/find_second_largest_num.py
183
3.5
4
n = int(input()) arr=[] for i in range(n): x = list( map(int, input().split())) arr.append(x) print (arr) larger= max(num for num in arr if num!=max(arr)) print (larger)
f09de8f722be2cd8818e4547e4c083547c3521d0
AleksanderMako/Algorithms
/src/pythonSamples/isPalindrome.py
589
3.59375
4
class Solution(object): def isPalindrome(self, s): """ :type s: str :rtype: bool """ if len(s) < 1: return True alphanumeric = "".join(c.lower() for c in s if c.isalnum()) # print(alphanumeric) return self.isPalindromeHelper(0,len(alphanume...
a735b44f27614aa4681b18f84473c3ba4b6c5558
QiongWangUSCEE/EE511-Simulation-Methods-for-Stochastic-Systems
/project1/Q1a.py
1,237
3.59375
4
import random as rd import matplotlib.pyplot as plt def main(): # get the dataset for different number times of Bernoulli trial (n=50, p=0.5) result20 = experiment(20) result100 = experiment(100) result200 = experiment(200) result1000 = experiment(1000) result2000 = experiment(2000) result...
879b6bbe39b82003cc3a61fade57d33c592d8907
lunar-r/sword-to-offer-python
/剑指offer/40 数组中只出现一次的数字.py
2,067
3.5625
4
# -*- coding: utf-8 -*- """ File Name: 40 数组中只出现一次的数字 Description : Author : simon date: 19-3-3 """ # -*- coding:utf-8 -*- class Solution: # 返回[a,b] 其中ab是出现一次的两个数字 def FindNumsAppearOnce(self, array): if array == None or len(array) <= 0: return [] resu...
a845790ab300d3bfb4705d36be4457de66638692
lunar-r/sword-to-offer-python
/剑指offer/41 和为s的两个数字.py
793
3.609375
4
# -*- coding: utf-8 -*- """ File Name: 41 和为s的两个数字 Description : Author : simon date: 19-3-4 """ # -*- coding:utf-8 -*- class Solution: def FindNumbersWithSum(self, array, tsum): # write code here if not array: return [] left, right = 0, len(array...
6368eaed261b57e7e599ff846e2886491878a052
lunar-r/sword-to-offer-python
/剑指offer/19 二叉树的镜像.py
2,902
3.578125
4
# -*- coding: utf-8 -*- """ File Name: 19 二叉树的镜像 Description : Author : YYJ date: 2019-02-16 """ # -*- coding:utf-8 -*- class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # 返回镜像树的根节点 def Mirror(self, ...
48e6d207932f6c208bcfa879c18d826344b0343f
lunar-r/sword-to-offer-python
/leetcode/200. Number of Islands.py
1,705
3.5625
4
# -*- coding: utf-8 -*- """ File Name: 200. Number of Islands Description : Author : simon date: 19-3-31 """ """ DFS 这道题其实和之前的剑指offer最后补充的回溯问题很相似 机器人的运动范围 每次找到一个运动范围之后 将这个范围全部清成0 """ class Solution(object): def numIslands(self, grid): """ :type grid: List[List[str]...
463aaa4cc99d5a573bec3d34e0fa3e87c6709988
lunar-r/sword-to-offer-python
/leetcode/283. Move Zeroes.py
1,488
3.859375
4
# -*- coding: utf-8 -*- """ File Name: 283. Move Zeroes Description : Author : simon date: 19-3-12 """ """ 直接考虑每个非零数字最终需要移动的次数 使用一个List存放每一个元素需要移动的距离 """ class Solution(object): def moveZeroes(self, nums): """ :type nums: List[int] :rtype: None Do not return a...
2ccd24c820e0218f7f3f5a637d9b4d7fc418efa6
lunar-r/sword-to-offer-python
/剑指offer/17 合并两个排序的链表.py
2,153
3.71875
4
# -*- coding: utf-8 -*- """ File Name: 17 合并两个排序的链表 Description : Author : YYJ date: 2019-02-16 """ # -*- coding:utf-8 -*- class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: #返回合并后列表 def Merge(self, pHead1, pHead2): # ...
cafda8e5ff27c14b82cbcf19b1bbc617759a4b94
lunar-r/sword-to-offer-python
/leetcode/647. Palindromic Substrings.py
786
3.65625
4
# -*- coding: utf-8 -*- """ File Name: 647. Palindromic Substrings Description : Author : simon date: 19-3-12 """ """ 考虑每一个可能的对称轴 共有2N-1个可能的点(包含两个index的中点) """ class Solution(object): def countSubstrings(self, s): """ :type s: str :rtype: int """ ...
13c7be410caaf9a5b9f81baf58c97b9751d72d52
lunar-r/sword-to-offer-python
/剑指offer/41 和为S的连续正数序列.py
858
3.828125
4
# -*- coding: utf-8 -*- """ File Name: 41 和为S的连续正数序列 Description : Author : simon date: 19-3-4 """ # -*- coding:utf-8 -*- class Solution: def FindContinuousSequence(self, tsum): # write code here if tsum <= 0: return small, big = 1, 2 curSum...
20bf6a7fedd28c550879813689ca58832f89f5b8
lunar-r/sword-to-offer-python
/leetcode/10. Regular Expression Matching.py
2,325
3.921875
4
# -*- coding: utf-8 -*- """ File Name: 10. Regular Expression Matching Description : Author : simon date: 19-4-12 """ """ 递归 + memo 爽的一批 自顶向下 为什么是自顶向下 因为当前的解依赖于未来的解 dp(i,j)意味着 s[i:] 和 p[j:] 之间的匹配情况 """ class Solution(object): def isMatch(self, s, p): """ :type s:...
522959faa58ad93ac77d5ef590bd61f197eea45e
lunar-r/sword-to-offer-python
/剑指offer/01 二维数组查找.py
1,208
3.765625
4
# -*- coding: utf-8 -*- """ File Name: 01 二维数组查找 Description : Author : YYJ date: 2019-02-12 """ # test """ 二刷记录 """ # -*- coding:utf-8 -*- class Solution2: # array 二维列表 def Find(self, target, array): # write code here rows = len(array) cols = len(array[0...
8269465b2b495fd82b23c2861c8d1cb9a1e988ae
lunar-r/sword-to-offer-python
/剑指offer/33 把数组排成最小的数.py
1,087
3.90625
4
# -*- coding: utf-8 -*- """ File Name: 33 把数组排成最小的数 Description : Author : simon date: 19-2-24 """ from functools import cmp_to_key # -*- coding:utf-8 -*- class Solution: def PrintMinNumber(self, numbers): # write code here if not numbers: return # ...
508d420c1004b216125d3f50247d29e9a5deba68
lunar-r/sword-to-offer-python
/leetcode/572. Subtree of Another Tree.py
2,326
3.75
4
# -*- coding: utf-8 -*- """ File Name: 572. Subtree of Another Tree Description : Author : simon date: 19-3-24 """ """ Naive approach, O(|s| * |t|) """ # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None ...
9dfa5f7bea5cac3228715bf6b83ad731fddbdee3
lunar-r/sword-to-offer-python
/剑指offer/22 从上往下打印二叉树.py
1,259
3.8125
4
# -*- coding: utf-8 -*- """ File Name: 22 从上往下打印二叉树 Description : Author : YYJ date: 2019-02-17 """ # -*- coding:utf-8 -*- class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # 返回从上到下每个节点值列表,例:[1,2,3] ...
b049e855fb873027a24ac6e3f022b675788d4ad9
lunar-r/sword-to-offer-python
/剑指offer/把字符串转换成整数.py
1,435
3.75
4
# -*- coding: utf-8 -*- """ File Name: 把字符串转换成整数 Description : Author : simon date: 19-3-19 """ # -*- coding:utf-8 -*- class Solution: def StrToInt(self, s): # write code here if not s: return 0 s = list(s) for i in s: if i no...
e733b066911f5ebafa1a8a01c37d9cf69ef3870f
amanlalpuria/go-python-over
/Using Python to Access Web Data/02. Assignment.py
272
3.5625
4
import re def getNumbers(str,sum): array = re.findall(r'[0-9]+', str) for i in array: sum+=int(i) return sum sum = 0 file = "regex_sum_702801.txt" fh = open(file) for line in fh: result = getNumbers(line,sum) sum = result print(sum)
f3d2913606a2b0536ceb12a9b469762cd9d86fc3
giant-xf/python
/untitled/4.0-数据结构/4.02-栈和队列/4.2.2-队列的实现.py
945
4.4375
4
class Queue(object): #创建一个空的队列 def __init__(self): #存储列表的容器 self.__list = [] def enqueue(self,item): #往队列中添加一个item元素 self.__list.append(item) #头插入,头出来,时间复杂度 O(n) #self.__list.insert(0,item) def dequeue(self): #从队列尾部删除一个元素 #r...
5e68926d8fb2ab4328840045fbf9b330f983445b
giant-xf/python
/untitled/1.01-小白成长记/复习篇/函数--匿名函数.py
437
3.6875
4
def fun(a,b): sum =a+b return sum print("result =",fun(1,2)) t=lambda x,y:x+y print("result =",t(1,2)) #应用场景: #函数作为参数传递 #1.自定义函数 def f(a,b,opt): print("result =",opt(a,b)) f(1,2,lambda x,y:x+y) #2.作为内置函数的参数 stus =[{"name":'老王','age':15}, {'name':"老李",'age':...
15d307f0a9d26df337c7fe941d2c4fcf28c9d9d6
giant-xf/python
/untitled/4.0-数据结构/eg.py
1,816
4
4
class Node(object): """单链表的节点""" def __init__(self,elem): self.elem = elem self.next = None class SingleLinkList(object): """单链表的实现""" def __init__(self): self.__head =None def is_empty(self): """判断是否为空""" return self.__head == None def...
1212457649585f24add77cd3ed4c18e543d14a6e
giant-xf/python
/untitled/2.0-小白进阶篇/2.01-核心编程/1.01.3-生成器应用于协程.py
1,605
4.03125
4
#生成器中 send用法 next()用法 __next__()用法 以及 yield 用法 '''1.next(xx)用法: 调用一次生成一个值,最后生成完了会异常 2.__next__用法: 与next用法相同 3.send()的用法: 第一次不能传入非空数据,要么不用seed(),要么传入None, 传入temp参数,传一次更新一次,否则下次不传就默认传入了None 可以用条件判断使其一直保持最初传入的值 def f(): i=0 ...
4fb432f7762c778f8efd0de0e14031b004a27f2b
Resinchen/CG-course-Urfu
/draw_func_ghrafic.py
1,635
3.875
4
from math import * from tkinter import * screen_width = 700 screen_height = 600 is_show_X_axis = True is_show_Y_axis = True # входные данные a = -10 b = 10 func = lambda x: sin(x)+cos(x/2) # доп. переменные x0 = 0 ymin = ymax = y0 = func(a) axis_y_x = axis_x_y = 0 # будем ли рисовать вертикльную ось if a > 0 and ...
0ad4b40d559778b1b9623427de20cb10b5c20f2d
aitsc/interesting-algorithm
/上楼梯问题.py
300
3.609375
4
def 上楼梯(层数,次数=[0]): if 层数>=3: 上楼梯(层数-1, 次数) 上楼梯(层数-2, 次数) 上楼梯(层数-3, 次数) elif 层数==2: 次数[0] = 次数[0] + 2 else: 次数[0] = 次数[0] + 1 return 次数[0] print(上楼梯(4))
4785c91aa4570236396e5628a71b14c7bc3d1c36
arung-agamani/tubes-tbfo-cyk
/grammarConverter.py
1,707
3.59375
4
RULE_DICT = {} def read_grammar(grammar_file): with open(grammar_file) as cfg: lines = cfg.readlines() return [x.replace("->", "").split() for x in lines] def add_rule(rule): global RULE_DICT if rule[0] not in RULE_DICT: RULE_DICT[rule[0]] = [] RULE_DICT[rule[0]].append(rule[1:]) ...
77df69304204d14fbcf444cb65e18c7d9bfb2f3f
arung-agamani/tubes-tbfo-cyk
/inputFile4.py
260
4
4
def greet(name): """ This function greets to the person passed in as parameter """ print("Hello, " + name + ". Good morning!") while(True): name = input("Input your name : ") if (name != ""): greet(name) else: break
1b0dbc67c509a73b2482d2424987e284c5dbd063
kevinliu2019/CP1404practicals
/prac_05/hex_colours.py
758
4.4375
4
CODE_TO_COlOUR = {"AliceBlue": "#f0f8ff", "AntiqueWhite": "#faebd7", "AntiqueWhite1": "#ffefdb", "AntiqueWhite2": "#eedfcc", "DodgerBlue3": "#1874cd", "gray": "#bebebe", "aquamarine1": "#7fffd4", "OldLace": "#fdf5e6", "aquamarine4": "#458b74", "azure1": "#...
c67732237f85176b80ae8a8a6691c7e10c71e41c
marcoacarvalho/marco-carvalho
/Connection.py
1,074
3.5
4
###################################################### # Exemplos de uso do sqlobject ###################################################### import sqlobject from sqlobject.mysql import builder conn = 'mysql://dbuser:dbpassword@localhost/sqlobject_demo?debug=1' """ Database Connections Examples: MySQL conn =...
bd8def2a1686e8c48fc77f68009bc8a292db6cba
DilrajS/TD-Learning-Black-Jack
/wordBased.py
6,297
3.921875
4
import Card import Dealer import Player import random # import time # IMPORTANT VARIABLES AND DICTIONARIES current_player = 0 # Keeps track of who is playing. numOfPlayers = 0 # Number of players user wants. playerDictionary = {} # Keeps players (& dealer) in a dictionary. cardDict = {} # This stores cards that ar...
42d8d3d8105a71924d5a391eef15d9cfc7f66aa2
Danielacvd/Py3
/Funciones/funciones.py
4,613
4.375
4
""" Funciones en python3 Definicion o llamada: Syntax Basica: def nombre_funcion(): codigo.... return codigo #llamo desde el cuerpo del programa nombre_funcion() Dentro de la funcion puedo declarar variables, inicializarlas, etc Pero para que estan variables puedan vivir fuera de la funcion, las tengo q...
faf5e2e6b7a1df320d4dd5124041cbf0ccf19692
Danielacvd/Py3
/Estructura_de_control/ciclo_while.py
460
4.03125
4
""" Ciclo While inicializo variable while condicion: instrucciones actualizar variable else: print("Fin ciclo") Si uso el break en el while, no se ejecutara el else, ya que el ciclo no finaliza su iteracion, si no que se interrumpe Instrucción continue Sirve para "saltarse" la iteración actual sin romper...
69c90196bf5f5b97440c574eef6df4d6c70bf04c
Danielacvd/Py3
/Errores_y_excepciones/excepciones.py
2,764
4.1875
4
""" Errores y Excepciones en Python Excepciones Son bloques de codigo que nos permiten seguir con la ejecucion del codigo a pesar de que tengamos un error. Bloque Try-Except Para prevenir fallos/errores tenemos que poner el bloque propenso a errores en un bloque TRY, y luego encadenar un bloque except para tratar la s...
db1eedd2b2ea011786f6b26d58a1f72e5349fceb
mirarifhasan/PythonLearn
/function.py
440
4.15625
4
#Function # Printing the round value print(round(3.024)) print(round(-3.024)) print(min(1, 2, 3)) #If we call the function without parameter, it uses the default value def my_function(country = "Norway"): print("I am from " + country) my_function("Sweden") my_function("India") my_function() #Array passing in fu...
d8a7bf8f88456c702dc0ad06f88a7aa6cfcac0a9
MadsRasted/pythonExam
/ListLoops.py
1,451
4.0625
4
#List loops animalList = ['Hamster', 'Tiger', 'Gnu', 'Lion'] #For loop #Loop thru for i in animalList: print(i) print('') #Loop thru for i in range(len(animalList)): print(animalList[i]) print('') #Break at position for i in animalList: print(i) if i == 'Tiger': break print('') #___________...
e2667a1f65600f84b0f1892372f22ae131a859bd
ruiwancheng/test
/test_list_and_dictionary.py
2,060
4.09375
4
list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(list[2:-2])# 从第二个开始(包含),到倒数第二个(不包含) length = len(list) # 容量 max_data = max(list) # 最大值 min_data = min(list) # 最小值 # list(tuple) print(list) list.append(11) # 添加元素 print(list) print(list.count(3)) # 计算元素出现次数 list.extend([12, 13, 14, 15]) # 添加列表 print(list) list.ins...
69199e5f988a159992b12ba048712c86f9d14032
kimmoahola/neural
/app.py
5,872
4.03125
4
from numpy import random from numpy.ma import exp, array, dot class NeuralNetwork: def __init__(self): # Seed the random number generator, so it generates the same numbers # every time the program runs. random.seed(1) # We model a single neuron, with 3 input connections and 1 outp...
2ac79f13fc4c1c6616184d5c4c1327bbc593daf3
daivikvennela/python-udemy
/Math.py
434
4.09375
4
print("math") number_1 = eval(input("number1: ")) operation = input("operation - +,-,*,/: ") number_2 = eval(input("number2: ")) if operation == "+": result = number_1 + number_2 elif operation == "-": result = number_1 - number_2 elif operation == "*": result = number_1 * number_2 elif operation == "/...
856f9202d749b87a551fc014dc3a481018fcd564
rishi23root/Password-Strength-Checker
/run.py
13,545
3.765625
4
from tkinter import * class password_strength_checker: def __init__(self,password): self.password =rf'{password}' # saving empty variables self.digits_count = 0 self.small_letters_count = 0 self.big_letters_count = 0 ...
35b74584f9373c2bb54020d55702df1ca61aa47b
Samsabal/public-library-system
/Book.py
2,662
3.53125
4
import json import BookItemCSV import LoanItem import PersonCSV CURRENTUSER = 0 class Book(): """This is a book class""" def __init__(self, author, country, imageLink, language, link, pages, title, year): self.author = author self.country = country self.imageLink = imageLink ...
4235ddfb49c4281b0ecbb62fa93c9098ca025273
davisrao/ds-structures-practice
/06_single_letter_count.py
638
4.28125
4
def single_letter_count(word, letter): """How many times does letter appear in word (case-insensitively)? >>> single_letter_count('Hello World', 'h') 1 >>> single_letter_count('Hello World', 'z') 0 >>> single_letter_count("Hello World", 'l') 3 ...
2d0b03210a1804efc091fd08d2424e39d3485798
Bernardo-MR/EjercicioPrueba
/EjercicioCoche.py
241
3.71875
4
# Autor: Bernardo Mondragon Ramirez # Calcula velocidad promedio, dado el tiempo y la distancia d = int(input("Teclea la distancia en km. enteros: ")) t = int(input("Teclea el tiempo en hrs. enteros: ")) v = d*t print("Velocidad promedio:",v, "km/h")
45861e4c7821d123a4e97685286dabb27b83f6b3
wolf5885/agendaPy
/menu.py
1,585
3.6875
4
from os import system def mainMenu(): system("clear") print("Menú Principal") print("==== =========") print() print(" a) Alta de Personas") print(" b) Búsqueda de Personas") print(" m) Modificación de Personas") print(" e) Eliminación de Personas") print(" s) Salir del sistema") print() print() def hight...
c98dd8cc4843b8458b0838636f624d8129cfc0fe
itspawanbhardwaj/python-examples
/com/bdu/chapter/four/Conditions.py
184
3.8125
4
album_year = 1983 if album_year > 1980: print "Album year is greater than 1980" elif (album_year > 1990): print "greater than 1990" else: print "album is less than 1980"
b3ac0fbaf398833737607940fede0714d6f6d41d
duanyiting2018/learning_python
/bounce_ball_game.py
1,418
3.6875
4
from tkinter import * import time,random tk=Tk() tk.title("Bounce ball game") tk.resizable(0,0) tk.wm_attributes("-topmost",1) c=Canvas(tk,width=500,height=450,bd=0,highlightthickness=0) c.pack() tk.update() class ball: def __init__(self,ca,co): self.ca=ca self.id=ca.create_oval(10,10,30,3...
c2d84cef1ee24526239102c834c5db617c28e1aa
duanyiting2018/learning_python
/selection_sort.py
695
3.734375
4
# -*- coding: utf-8 -*- """ Created on Sat Jun 6 16:08:57 2020 @author: duanyiting """ def showdata(data): for i in range(len(data)): print('%5d'%data[i],end=" ") print() return "" def select(data): for i in range(len(data)-1): for j in range(i+1,len(data)): if data[i]>data...
afddf0f66e7ff4df3edb9ca64c32ade9c095070e
duanyiting2018/learning_python
/learning_python/turtle_eight.py
243
3.90625
4
import turtle t = turtle.Pen() def draw_star(size, points): angle = 360 / points for x in range(0, points): t.forward(size) t.left(180 - angle) t.forward(size) t.right(180-(angle * 2)) #draw_star(50,50)
8dac9d53df8a0d280a5a2b95987e5b5ba6c9ffbb
duanyiting2018/learning_python
/money.py
334
3.96875
4
# -*- coding: utf-8 -*- def money(fiveNumber,twoNumber,oneNumber): total=5*fiveNumber+2*twoNumber+oneNumber return total fiveNumber=int(input("Enter a number of five:")) twoNumber=int(input("Enter a number of two:")) oneNumber=int(input("Enter a number of one:")) print("total money is:",money(fiveNumber,twoNumb...
644d944cab96f8cbae9d53d2939433ece24bf839
duanyiting2018/learning_python
/beachball.py
590
3.53125
4
# -*- coding: utf-8 -*- import pygame pygame.init() screen=pygame.display.set_mode([700,500]) screen.fill([255,255,255]) my_ball=pygame.image.load("beach_ball.png") screen.blit(my_ball,[60,60]) pygame.display.flip() x=60 y=60 for i in range(1,100): pygame.time.delay(1000) pygame.draw.rect(screen,[255,255,255],[...
08823f540327149c6d4de3749d5d2317cdbd0e34
duanyiting2018/learning_python
/student_list1.py
694
3.5625
4
# -*- coding: utf-8 -*- """ Created on Fri Oct 2 18:56:32 2020 @author: duanyiting """ class student: def __init__(self): self.name="" self.score=0 self.next=None head=student() head.next=None ptr=head select=0 while select !=2: print("输入1添加数据,输入2离开:") select=int(input()) if se...
bd9fb8875f07565de13167b981c1baf97c9c4ec4
duanyiting2018/learning_python
/class_account.py
494
3.953125
4
# -*- coding: utf-8 -*- """ Created on Wed Apr 15 20:12:07 2020 @author: duanyiting """ class account: #def __init__(self): #self.account_name=input() #self.account_money=int(input()) def see_account(self): print(self.account_name,",",self.account_money) def change_account(self): ...
e56884fd026ee0541d964544fe138b855269e1b8
duanyiting2018/learning_python
/class_employee2.py
1,316
3.90625
4
# -*- coding: utf-8 -*- """ Created on Sat Jul 4 19:37:40 2020 @author: duanyiting """ class employee: #__init__==setting def __init__(self,name,age,sex): self.name=name self.age=age self.sex=sex #__str__==getting def __str__(self): return "name:"+self.name+"\t age:"+st...
f4f1319bebc4e5edfcdc8edd8cff987158994391
duanyiting2018/learning_python
/class_person_student.py
1,452
3.921875
4
# -*- coding: utf-8 -*- """ Created on Fri Jul 3 20:age3:33 2020 @author: duanyiting """ class Person: def __init__(self,name,addr,sex,age): self.name=name self.addr=addr self.sex=sex self.age=age def output1(self,name,addr,sex,age): print("name:",name,"addr:",addr,"sex...
ba547c8e6d073237cb6330c2a2b38b0829913e31
kniewohner1/mystuff
/hello.py
116
3.671875
4
#!/usr/bin/python if __name__ == '__main__': n = 5 for i in range(n): if i >= 3: print(i)
2cbc5e2ac30e8625e7b9ebbe6f900c5742ca8716
jlm200065/SoftWareImprovement
/test/test.py
1,202
3.65625
4
#!/usr/bin/env python # -*- coding:utf-8 -*- """code_info @Time : 2021 2021/4/2 13:48 @Author : jiangliming @File : test.py """ from selenium import webdriver # (1) browser = webdriver.Chrome() # (2) # Edith has heard about a cool new online to-do app. She goes # to check out its homepage browser.get('http://...
26a80b1e87230fd2d097ed1d3d04a63f21711b66
DanielSCrouch/basic-algorithms
/binary_tree/test_traversal.py
2,136
3.734375
4
import unittest from binary_tree.binary_tree import BinaryTree class TestBinaryTree(unittest.TestCase): def test_breadth_first_traversal(self): bt = BinaryTree() bt.insert(9) bt.insert(4) bt.insert(6) bt.insert(20) bt.insert(170) bt.insert(15) bt.insert(1) ordered = [9, 4, 20,...
163539325a65d9dca176df7cb23fda6c6d8869b4
Lyzw57/Dice-roller
/dice_roll.py
774
3.84375
4
# def roll_the_dice(dice: str): # """ # non bonus version. # """ # from random import randint # amount, size = dice.split("d") # result = 0 # for i in range(1, int(amount) + 1): # result += randint(1, int(size)) # return result def roll_the_dice(dice: str): """ bonus v...
b2234ad8314af231120f2fca6ea427ef2fee5362
jonmaxgreenberg/AnagramsSolver
/anagramssolver.py
2,635
4.03125
4
def main(base_word, added_letters): __author__ = "Jonathan Greenberg" import pandas as pd import collections import pprint import pickle alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']...
0ad445d7ae58a5b1a89ee2681003379f429e220a
MaxToyberman/Enigma
/Rotor.py
1,880
3.5
4
from Translator import Translator ''' Author:Maxim Toyberman Date:18.11.2015 ''' class Rotor(Translator): def __init__(self, ringOffset, ringSetting, permutation, notch): super(self.__class__, self).__init__(permutation) self.ringOffset = ringOffset self.ringSetting = ringSetting s...
16a9dbae2999b30e78c1b5bf460c0b8614a44fb1
mattcpfannenstiel/feudalismSim
/LandUnit.py
2,808
3.859375
4
from Climate import Climate from Location import Location class LandUnit: """ The basic unit that produces grain and houses serfs """ SERF_MAX = 10 PRODUCTION_VALUE = 50 SERF_UPKEEP_COST = 5 def __init__(self, x, y, fief): """ Makes a new land unit :param x: the x ...
99db5d93dd6673b1afa97701b1fb8d09294223c0
timseymore/py-scripts
/Scripts/set.py
485
4.125
4
# -*- coding: utf-8 -*- """ Sets numerical sets and operations on them Created on Tue May 19 20:08:17 2020 @author: Tim """ test_set = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} # returns a set of numbers in given range (inclusive) # that are divisible by either 2 or 3 def set_mod_2_3(size): temp = {} index = 0 f...
fea0c7cd509f4f9e059fcefb37218a380cd25b2d
timseymore/py-scripts
/Scripts/hanoi.py
307
3.75
4
# -*- coding: utf-8 -*- """ Hanoi Towers how many turns to solve a Hanoi towers puzzle with n discs Created on Wed Apr 8 16:54:52 2020 @author: Tim """ def turns_to_solve(n): if n == 1: return 1 elif n == 2: return 3 else: return (turns_to_solve(n-1) * 2) + 1
4bdf487e4600dfd927e4419f0c25391cfbfb721c
timseymore/py-scripts
/Scripts/counting.py
2,285
4.5
4
# -*- coding: utf-8 -*- """ Counting examples of counting and recursive counting used in cominatorics We will be implementing a graph consisting of nodes and then use recursive counting to find the number of possible paths from the start node to any given node in the graph. The number of possible paths to any give...