blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
2f7684e7aa08437358aead7c7c1b4e6029d8402b
AnhTuan2804/LearnPython
/learn.py
729
3.671875
4
import datetime # item = [12, 2,6,4,9] # print(item) # print(sum(item)) # item.sort() # print(item) # def sumItem(list): # total = 0 # for subitem in list: # total +=subitem # return total, total # print(sumItem(item)[0]) class person(): name = 'Dog' age = 20 color = 'blue' ey...
bbce0488f3266680f4aa4368584031c16a2d255b
andjo16/course-help
/DM550 - Introduction to Programming/Python_examples/MandelbrötColour.py
3,786
3.828125
4
"""Messy, but fairly optimized code for drawing the mandelbrot set using turtle graphics""" import turtle """These values can be modyfied to change the rendering""" width = 200 #Size in max distance from 0,0. Medium performance impact #width = 500 fits a maximized window on a 1080p screen height = ...
57bab83657cbb240b216a56e4fc69018277840bb
kemingy/daily-coding-problem
/src/subarray_sum.py
544
3.984375
4
# Given an array of numbers, find the maximum sum of any contiguous subarray of # the array. def max_sum(array): maximum, cur = 0, 0 for a in array: cur = max(0, cur + a) maximum = max(maximum, cur) return maximum if __name__ == '__main__': for array in [ ...
7800bb5de4761f760a3ad91e0436160d2a1dc865
Keshav1506/competitive_programming
/Linked_List/005_leetcode_P_160_IntersectionOfTwoLinkedLists/Solution.py
12,357
3.734375
4
# # Time : O(m+n) # Space: O(1) # @tag : Linked List # @by : Shaikat Majumdar # @date: Aug 27, 2020 # ************************************************************************** # LeetCode - Problem - 160: Intersection of Two Linked Lists # # Write a program to find the node at which the intersection of two singly link...
26430923a360291c8989a841d477ce38d3d1b62c
dbsima/python-playground
/programming-foundation-with-python/rename-file-names/rename-file-names.py
473
3.875
4
import os def rename_files(): current_dir = os.path.dirname(os.path.abspath(__file__)) path_to_dir = current_dir + '/prank' file_list = os.listdir(path_to_dir) os.chdir(path_to_dir) for file_name in file_list: new_name = ''.join([i for i in file_name if not i.isdigit()]) ...
91608f884fad01a9a0f65ca46d06893e665cebfe
Anzanrai/AlgorithmicToolbox
/week2_solution/gcd.py
636
3.71875
4
# Uses python3 import sys def gcd_naive(a, b): current_gcd = 1 for d in range(2, min(a, b) + 1): if a % d == 0 and b % d == 0: if d > current_gcd: current_gcd = d return current_gcd def remainder(a, b): return a % b, b def gcd_euclid(a, b): if a > b: ...
8b5b9fb9435a9f19f3228eadffd664fe780475cb
saurabh-pandey/AlgoAndDS
/leetcode/linkedList/singly_linked_list/tests/test_odd_even.py
698
3.546875
4
import singly_linked_list.odd_even_a1 as a1 import singly_linked_list.operations_a1 as sll_a1 solutions = {"attempt_1": a1} slls = {"attempt_1": sll_a1} class TestOddEvenList: def test_example1(self): for attempt, solve in solutions.items(): sll = slls[attempt] head = sll.create([...
7330bfad0a0a0aba5b0ef00df904013d5c02274e
Hunt66/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/0-square_matrix_simple.py
191
3.65625
4
#!/usr/bin/python3 def square_matrix_simple(matrix=[]): if matrix is None or len(matrix) is 0 or matrix[0] is None: return matrix return [[i ** 2 for i in j] for j in matrix]
a0eb5d44b62d28cf0f049bd8b817de968ac183a1
stanml/image_similarity
/python_scripts/text_similarity.py
2,138
3.53125
4
import itertools as it import editdistance # The segmentation algorithm can potentially extract text in an arbitrary order, # therefore, the Levenshtein measure can classifiy text with exactly the same # sentences as being different because of the order. This class gives a score # based on matched segments by taking t...
d13ff39717f581af0159df12819fd548411d2aee
Vworri/Computational-Physics-Review
/madelungConstant.py
1,601
3.59375
4
import scipy.constants as s_const from math import pi #In condensed matter physics, the Madelung constant gives the total electric potential felt by an atom in a solid. #In this program, we will use the sodium chloride wich is arranged in a cubic lattice. The vertexes of the cube alternate #positive to negative with th...
6a1f0e6bcd7c1f3d7ed3d512d76046617608c904
lanngo27/data-structures-algorithms
/recursion/prime_numbers/tests.py
844
4.125
4
import unittest import math from prime_numbers import has_divisors class TestPrimeNumbers(unittest.TestCase): def test_with_10_not_prime_numbers(self): """has_divisors returns True if numbers are not prime numbers. (10p)""" numbers = [4,8,10,15,20,155,270,300,444,985] for number in numbers...
b1c8876b6d7a7f2a795711584e4d2d1c3e568617
aka-luana/AulaEntra21_Luana
/Entra21-Python Maykon/01-Exercicios/Aula008/parte2.py
1,978
3.875
4
import parte1 from parte1 import listaPessoa listaEndereco = [] def cadastroEndereco(): if(len(listaPessoa) == 0): print("Primeiro cadastre uma pessoa.") else: numeroId = input("Digite o seu ID: ") if(numeroId.isspace()): while(numeroId.isspace()): numeroId ...
401ce4682507daad5f48d776f832f466fbbd910f
dkavaler/cracking_the_coding_interview
/chapter1/1.2.py
850
3.515625
4
from collections import defaultdict TEST_STRINGS = [('kjjkll', 'kkjjll'), ('dkaj', 'jkad',), ('abcde', 'edcba'), ('eeaee', 'aaeaa'), ('defg', 'gfde'), ('akjd', 'buif')] CORRECT_RESULTS = [True, True, True, False, True, False] # O(len(string1) + len(string2)) using hash table def is_permutation(st...
72e82eae3b2441f68c5e681a232577c49dcaa44a
leandro-matos/python-scripts
/aula02/ex14.py
193
3.578125
4
sal = float(input('Qual é o salário do Funcionário? R$ ')) aumentoSal = sal + (sal * 15/100) print(f'Um funcionário que ganhava {sal}, com 15% de aumento, passa a receber {aumentoSal:.2f}')
ca3ac506e199133d845f8234277bfc6b4a13134a
vivek-144/1BM17CS144-PYTHON
/8_DataBase.py
1,882
4.0625
4
import sqlite3 from sqlite3 import Error conn = sqlite3.connect('student.db') print("Connection Established") cur = conn.cursor() def create_table(): cur.execute("CREATE TABLE STUDENT (SID int primary key, name text, age int, marks int)") conn.commit() print("STUDENT table created.") def insertor(): ...
ff75ffede3bfa18c62dae3c55f68cb30139d17f9
parrisma/Reinforcement-Learning
/examples/PolicyGradient/TestRigs/RewardFunctions/LocalMaximaRewardFunction1D.py
4,262
3.5625
4
import math from typing import Tuple import numpy as np from examples.PolicyGradient.TestRigs.Interface.RewardFunction1D import RewardFunction1D """ This Reward Function has two local maxima and one global maxima. This is modelled as 2.5 cycles of a sinusoidal curve with the 2nd (central) peek weighed as give it a l...
d478f8b6d5c7811e432ffb23d2d892dec4a72893
starbucksdolcelatte/AI_Practice_2019
/Programming_Mathematics/[01]Number_Theory-Prime_Number/mersenne.py
408
3.84375
4
def isPrime2(n): # To-do if(n<=1): return False if(n%2 == 0): return False else: for i in range(1, int(n**0.5)): if(n % (i*2+1) == 0): return False return True pass def mersenne(n): return isPrime2(2**n-1) # 결과 출력을 위한 코드입니다. 자유롭게 값을 ...
b536c689d8bef8ec9de689d80eba9c03f74444e4
kevin-goetz/Python-Specialization
/01_Programming for Everybody (Getting Started with Python)/PY4E_Exercise 4.1.py
252
3.609375
4
# %% """ Exercise 4.1: Run the program on your system and see what numbers you get. Run the program more than once and see what numbers you get. """ import random # noqa for i in range(10): x = round(random.random()*100) print(x)
cae63bb302d25fd70c99763ee56c3b919675548c
norrismei/coding-fun
/linked_list_remove_duplicates_from_sorted_ll.py
2,255
4.28125
4
# You are given the pointer to the head node of a sorted linked list, where the data in the nodes is in ascending order. # Delete nodes and return a sorted list with each distinct value in the original list. # The given head pointer may be null indicating that the list is empty. # # For your reference: # # SinglyLink...
938e83c42b759eafb41db21adb090f77007cf92e
aumaro-nyc/leetcode
/trees/114.py
864
4.03125
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def flatten(self, root: TreeNode) -> None: """ Do not return anything, modify root in-place instead. """ ...
cc69510c34e62d218652b963e82cc5a068660661
HelloMyFriend-o/Weathergetabot
/database/db.py
663
3.546875
4
import psycopg2 as psycopg2 from loader import PG_DB, PG_USER, PG_PASS, PG_HOST, PG_PORT def connect_to_db(): connection = psycopg2.connect( database=PG_DB, user=PG_USER, password=PG_PASS, host=PG_HOST, port=PG_PORT ) return connection def create_a_tb(): conn...
c0f4440364657b75b98af371d05ad5a8f647022a
Debjit337/Python
/7.1.Tuple work.py
843
4.25
4
mytuple= ('A','B','C','D','E') print(mytuple[3]) print(mytuple[1:3]) print(mytuple[-3:-1]) Coming=('A','B','C') Notcoming=('D','E','F') Changes=list(Coming) Changes.append('D') Changes.append('E') print(Changes) Coming=tuple(Changes) print(Coming) Changes=list(Coming) Changes.remove('C') Changes.rem...
49e9c154a3217c2b26ab7f3c4091fb2d80718c72
dola258/Python
/ex01/var.py
580
4.03125
4
# 1. 파이썬은 인터프리터 언어이다. # 2. 파이썬은 모든 것이 객체이다. # 3. 파이썬은 변수의 타입이 없다. 타입 추론을 지원한다. # 4. boolean 의 true, false 첫글자 대문자로 # 5. ''' ~~~ ''' 사이는 문자열 # 6. "" '' 상관없이 사용가능 a=1 b=1.2 c="문자" d='문자' e=True f=False g=''' 안녕하세요. 반가워요. 하하하핳 ''' print (type(a)) # 1 int print (type(b)) # 1.2 float print (type(c)) # str pr...
fe45d5e2a4ca70c0e8ed2859fc86e336a3797959
zahid1905/PracticeJAVAPrograms
/ejercicios5/src/Hanoi.py
751
3.8125
4
def hanoi(n, torre0, torre2, torre1): if n > 0: # Mover la torre de tamaño n-1 a la torre1 hanoi(n - 1, torre0, torre1, torre2) # Mover el disco de torre0 a torre2 if torre0[0]: # Sacar el ultimo número del arreglo y sustituirlo por un 0 disco = torre0[0]....
fc600fe69a95b3129053f04ce7e3b72551d514c6
jonathanbarrow/python_basics
/dict_accum1.py
1,113
3.625
4
d = {'vowels': 0, 'consonants': 0, 'nonalpha': 0, 'abcd_words': [], 'punct_words': []} def breakout_1(some_str): for char in some_str: if char.lower() in ['a', 'e', 'i', 'o', 'u']: d['vowels'] += 1 elif not char.isalpha(): d['nonalpha'] += 1 else: d['c...
85098267410dc7d297923ad15ca349de5de00327
mhhuang95/LeetCode
/python/leetcode468.py
1,153
3.5
4
class Solution(object): def validIPAddress(self, IP): """ :type IP: str :rtype: str """ if '.' in IP and self.isvalidv4(IP): return "IPv4" if ':' in IP and self.isvalidv6(IP): return "IPv6" return "Neither" def isvalidv4(self, IP):...
ed8e41739f0b8aed39f1b050342f530bdb6efc14
LoveDT/leetcode
/236 Lowest Common Ancestor of a Binary Tree/nonrec.py
1,115
3.65625
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param {TreeNode} root # @param {TreeNode} p # @param {TreeNode} q # @return {TreeNode} def lowestCommonAncestor(self, ...
42bddc090d1afe6123c7282191dd37ecc1fb4462
qinliu1023/practices
/658. Find K Closest Elements.py
2,334
3.9375
4
""" Given a sorted array, two integers k and x, find the k closest elements to x in the array. The result should also be sorted in ascending order. If there is a tie, the smaller elements are always preferred. Example 1: Input: [1,2,3,4,5], k=4, x=3 Output: [1,2,3,4] Example 2: Input: [1,2,3,4,5], k=4, x=-1 Out...
865a787af5bd44e005284b50be5ecc1e8a194619
katebee/Battleships
/battleships.py
2,158
3.890625
4
__author__ = 'Admin' import config import players class Game(object): def __init__(self, ocean_size, fleet_size, max_turns): self.ocean_size = ocean_size self.fleet_size = fleet_size self.max_turns = max_turns def declare_ocean_size(self): print "The ocean is a {0} by {0}...
2685bb61c7438ca2e7ef7d7e827173d87e5e8b4e
Mark-Seaman/UNC-CS350-2017
/Exercises/Results/adam5491/Development_Exercise/file_text.py
706
3.84375
4
# file_text.py # Read the text from a file def read_file(filepath): with open(filepath) as f: return f.read()[:-1] # Write the text string to a file def write_file(filepath, text): with open(filepath, 'w') as f: f.write(text+"\n") # Test that the file reads and writes the same data def tes...
aae9ab50c28faf153738109b5a7093e0c04f3244
anhle730s/python
/le_kieu_anh-12MMC-1813020005/BT2.py
581
3.890625
4
#đề 2: #bài 2: Viết hàm với tham số truyền vào là một tháng và trả về mùa tương ứng trong năm. Sử dụng hàm vừa cài đặt, nhập vào một tháng và in ra màn hình mùa trong năm def mua(n): if ( n == 1 or n <= 3): return("Xuân") elif (n == 4 or n <= 6): return("Hạ") elif ( n == 7 or n <= 9)...
c2eca8500c373aabd1cb1f777947d8c3f5c4ee5c
Marlenqyzy/PP2
/week1/w3school/64.py
422
3.734375
4
'''thisset = {"apple", "banana", "cherry"} print(thisset) thisset = {"apple", "banana", "cherry", "apple"} #duplicate will be ignored print(thisset) thisset = {"apple", "banana", "cherry"} print(len(thisset)) set1 = {"apple", "banana", "cherry"} set2 = {1, 5, 7, 9, 3} set3 = {True, False, False} myset = {"apple", "...
f9207cb3bea0621b4e34853f044f10f44341b2c9
jcafiero/Courses
/CS115/Homework/hw10.py
585
3.75
4
#Stephanie Green #12/5/14 #Homework 10 def isnode(node): if type(node) == type(()) and len(node) == 3: return True return False def sumTree(tree): if type(tree) != type(()): return 0 elif isnode(tree) and type(tree[0]) == type(0): return tree[0] + sumTree(tree[1]) ...
4f4b164de2a437c2543039b07e7aafb16152c40a
Mounicask/Leetcode-problems
/THE MINION CHALLENGE.py
371
3.5
4
name='BANANA' lis=['A','E','I','O','U'] list1=[] length=len(name) vowcount,conscount=0,0 for i in range(0,length): if(name[i] in lis): vowcount=vowcount+(length-i) else: conscount=conscount+(length-i) if(vowcount>conscount): print("kevin",vowcount) elif(vowcount==conscount): ...
a84fddce12998dee4e64c60cb861e13e0605b252
odavidsonteixeira/RPG-python
/rpg_2v.py
35,804
3.703125
4
from random import randint # Mago vida_max_mago = randint(10, 20) mana_max = randint(5, 10) vida_max_guerreiro = randint(15, 25) est_max = randint(5, 15) # Monstro vida_max_monstro = 20 nome = input('Qual é o nome do seu aventureiro?' '\n---> ') print('Wow! Que belo nome') print('=-' * 40)...
0e85111c4deaa6923b8b28d7367d5c4b826f8a88
SKosztolanyi/Python-exercises
/75_Creating set class object and methods.py
2,180
4.125
4
class intSet(object): """An intSet is a set of integers The value is represented by a list of ints, self.vals. Each int in the set occurs in self.vals exactly once.""" def __init__(self): """Create an empty set of integers""" self.vals = [] def insert(self, e): """Assumes e...
164bc45622ecde62979494d8cc49c702dc9fbf34
fariharajput/Python_3
/week4/lab9-Mar4/q2.py
1,649
4.34375
4
# Question 2: Let’s sort the array using Merge Sort # Let’s suppose we have a list # list1= [1,5,67,2,43,6,4,2,2,4,6,2,1,68,5,4 ] # Write a function that # takes list1 an input # Sort all elements in the list in an ascending order # Returns the sorted list # Hint: Check this video to learn more about merge sort: htt...
adf6e27d163e0ccbeb1215da6418a1492a61fa82
SteveLyu07/DA202010
/poc_pandas/try0_excel.py
1,358
3.578125
4
# -*- coding: UTF-8 -*- # ------------------------(max to 80 columns)---------------------------------- # author by : (学员ID) # created: 2020.9 # Description: # pandas 技术验证用 # 各类基本技巧的练习 # 注:需安裝 pip install xlrd # ------------------------(max to 80 columns)---------------------------------- import os import panda...
8a1dfd3742cfdb2dd46665bc208547126ff20b61
dws940819/DataStructures
/DS3_BaseStructures/lesson3_queue.py
6,359
4.3125
4
''' 队列:是一系列有顺序的元素集合,新元素加入在队列的一端,这一端叫做“队尾” 已有元素的移出发生在队列的另一端,叫做“对首(front)”,当一个元素被加入到队列之后,它就从队尾向对首前进,直到它成为下一个即将被移出队列的元素 先进先出(FIFO):最新被加入的元素处于队尾,在队列中停留最长时间的元素处于队首 抽象数据类型(ADT): Queue()创建一个空队列对象,无需参数,返回空的队列 enqueue(item) 将数据项添加到队尾,无返回值 dequeue() 从队首移出数据项,无需参数,返回值为队首数据项 is...
e38fd352597542627a4429dfe445f0af714d988a
mathtkang/Data-Structure
/3-5.트리의 너비.py
2,216
3.625
4
# class Tree: # def __init__(self, i, l, r) : # self.index = i # self.left = l # self.right = r # self.depth = -1 # def setDepth(self, d) : # self.depth = d # def addNode(self, i, l, r) : # if self.index == None or self.index == i : # self.index ...
abd1db19c2fafe343d2e2a17a07bd72b9250a5df
ahmedyoko/python-course-Elzero
/lists13.py
1,676
4.6875
5
#------------------------ #lists : #......... #1- items enclosed in square brackets [] #2- ordered item and accessed by index #3- mutable => Add , delete , Edit #4- list items : are not unique #5-list can have different data type #------------------------ MyAwesomelist = ['one','two','one',1,2.5,True] print(MyAwesome...
2ae1a67c64d41e9fac44778570d8ef9e659eb48a
cybelewang/leetcode-python
/code693BinaryNumberWithAlternatingBits.py
1,085
4.125
4
""" 693 Binary Number with Alternating Bits Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values. Example 1: Input: 5 Output: True Explanation: The binary representation of 5 is: 101 Example 2: Input: 7 Output: False Explanation: ...
8aea11062ed72fde49628d38304510902cce8416
Naydell/Python
/ex009.py
435
3.984375
4
n = int(input('Digite um número: ')) n1 = n * 1 n2 = n * 2 n3 = n * 3 n4 = n * 4 n5 = n * 5 n6 = n * 6 n7 = n * 7 n8 = n * 8 n9 = n * 9 print('8 x 1 = {}'.format(n1)) print('8 x 2 = {}'.format(n2)) print('8 x 3 = {}'.format(n3)) print('8 x 4 = {}'.format(n4)) print('8 x 5 = {}'.format(n5)) print('8 x 6 =...
3d56ae4a1b0a5c2c77c9faae057b867d99245c98
ssthouse/PythonCookBook
/test_generator/test_generator.py
211
3.640625
4
# coding=utf-8 def generate_three_num(): for i in range(5): print("yield %d" % i) yield i def test_use_generator(): for i in generate_three_num(): i += 1 test_use_generator()
2f1c03f29f8931681fb8e9fce3b3c0748143e7fb
TanyaGerenko/T.Gerenko
/Ex26.py
1,045
3.84375
4
#Написать функцию для перевода десятичного числа в другую систему исчисления (2-36). В качестве параметров, функция получает десятичное число и систему счисления. #Возвращает строку - результат перевода десятичного числа. def ConvertNumber(n,base): D=['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E...
ced33841455ddae4f53b6596aa3236b998a2216c
AdamZhouSE/pythonHomework
/Code/CodeRecords/2484/60793/269297.py
229
3.703125
4
for test in range(0, int(input())): input() ls1 = list(map(int, input().split())) ls2 = list(map(int, input().split())) ls3 = set(ls1) | set(ls2) for x in ls3[:-1]: print(x, end=" ") print(ls3[-1])
e74a0921242666d5e66a20bcf6df5cd69e4724d9
justinjhjung/st_algorithm
/greedy/greedy_coinchange.py
485
3.875
4
from sys import stdin def input(): return stdin.readline().strip() def leastcoin(coins, change): res = 0 for coin in coins: if coin > change: continue leastamnt = change//coin res += leastamnt change -= leastamnt * coin return res test_num = int(input()) fo...
10ed1976041126596cbfd48aa9d7736a4507ef86
vitormicael/FATEC-MECATRONICA-1600792021046-vitormicael
/LTP1-2020-2/Pratica05/exercício02-refeito.py
343
3.84375
4
lado1 = int(input('Informe o valor do primeiro lado: ')) lado2 = int(input('Informe o valor do segundo lado: ')) lado3 = int(input('Informe o valor do terceiro lado: ')) if (lado1 > 0) and (lado2 > 0) and (lado3 > 0): if (lado1 + lado2) > lado3 and (lado2 + lado3) > lado1 and (lado1 + lado3) > lado2: print('Pode ...
8110896fa2728263f0726a162dccc64f3efa0227
hirad-p/ascend
/bytebybyte/autocomplete/autocomplete.py
231
3.671875
4
import sys words = ["abc", "acd", "bcd", "def", "a", "aba"] def autocomplete(prefix): return [x for x in words if x.startswith(prefix)] if __name__ == "__main__": suggestions = autocomplete(sys.argv[1]) print(suggestions)
6771f4ea316060a2e5550649e4ad510e6aa6da7f
dgeoffri/adventofcode
/2021/day03b.py
1,669
3.5625
4
#!/usr/bin/env python3 def get_gamma_rate(the_input): return idk(the_input, 0) def get_epsilon_rate(the_input): return idk(the_input, -1) def get_oxygen_generator_rating(the_input): return idk(the_input, 0, True) def get_co2_scrubber_rating(the_input): return idk(the_input, -1, True) def idk(the_in...
cd1cea69fdf616dba14676af4bf98fb397123ac9
gokuleswaran/python-class
/parser.py
5,395
3.609375
4
#!/usr/bin/python # Robert Theis # Sept. 15, 2012 # Introduction to Python Programming # Parses a valid Protein Data Bank (PDB) format text file for a protein. import argparse, os, requests, sys def atom_element(atom): return atom[0] def atom_residue(atom): return atom[1] def atom_x_pos(atom): return a...
f8ca8aa0dce4083ee289b8786e4a5d961536a27b
konishis/exercise_python_koni
/exercise_python_koni/projecteuler/Q1.py
1,158
4.28125
4
''' If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. ''' ''' 3 または 5 の倍数である 10 未満のすべての自然な数値をリストすると、 3、5、6、9 が得られます。これらの倍数の合計は 23 です。 1000 以下の 3 または 5 のすべての倍数の合計を検索します。 ''' ...
b545f9cd79f53d89490562dbf504956316257b19
KaiHoshijo/Chess
/King.py
14,896
3.546875
4
import pygame class king(pygame.sprite.Sprite): def __init__(self, screen, board, image, rect, row, col, colour): pygame.sprite.Sprite.__init__(self) self.screen = screen self.board = board self.image = image self.rect = rect self.row = row self.c...
5d07526a325ed8f77e57255e11d2811d48e97465
Elizabeth6743/My-First-Project
/Project1.py
4,938
4.03125
4
score = 0 First_name = input("What is your First name?") Last_name = input("What is your Last name?") age = input("What is your age?") print("Hello " + First_name + " " + Last_name) print("Welcome to a Nation Wide PANDEMIC") print("Let's see how much you know about Covid-19") # Question 1 answer1 = input("How many c...
7be371b7b74b5aa52ade9070139e0fe9ff06c773
RaulGnzlzAlvrd/clase-python3
/clase09/soluciones/uses_only.py
462
4.03125
4
def uses_only(word, available): ''' Comprueba que word use solamente letras en chars word: String chars: String return: boolean ''' for letter in word: if not letter in available: return False return True caracteres = input("Ingresa los caracteres deseados:\n") file...
21c620da5b65dda157f2bb0e118d92ffeec207c4
burakbayramli/books
/Introduction_to_numerical_programming_using_Python_and_CPP_Beu/modules/sort.py
6,998
3.625
4
#---------------------------------- sort.py --------------------------------- # Contains routines for sorting, indexing and ranking numeric sequences. # Part of the numxlib numerics library. Author: Titus Beu, 2013 #---------------------------------------------------------------------------- #==================...
efc5778c00196d8133503756de5699a6a45d55c7
github653224/GitProjects_SeleniumLearing
/SeleniumLearningFiles/SeleniumLearning01/Test2/26StringIO.py
929
3.625
4
#往内存中读写内容 from io import StringIO f=StringIO() f.write("hello ") f.write("panxueyan") f.write("!") print(f.getvalue()) # 要读取StringIO,可以用一个str初始化StringIO,然后,像读文件一样读取: >>> from io import StringIO f = StringIO('Hello!\nHi!\nGoodbye!') while True: s = f.readline() if s == '': break print(s.strip()...
9ca1da04db7918d733d01687ff70a25eff11504d
dfworldwang/Python-Elementary-Practice
/Data Structure and Algorithms/python_join.py
565
3.671875
4
li = ['my', 'name', 'is', 'bob'] # Concatenate the elements of list with blank print(' '.join(li)) print('..'.join(li)) class Foo(): def __init__(self): self.name = [{"Susan": ("Boyle", 50, "alive")}, {"Albert": ("Speer", 106, "dead")}] def __str__(self): ret_str = "" ...
0f4a5a3988386b2b5610035dea167c8a8cbf3261
harinderbhasin/DataScience
/BhasinMiniProject-XML-Q1.py
1,173
3.71875
4
# Mini Project 4 # Name: Harry Bhasin in collaboration with Peter B. # Question 1 import pandas as pd import xml.etree.ElementTree as ET # import statistics # from statistics import mean import numpy as np # read the player data text file into a python dataframe using panda playerdata=pd.read_csv('baseball_s...
853f36d2b70faaf0757768ca1467d70ab38d6c91
pranavmswamy/leetcode
/mathworks/numberOfOperationsToMakeConnectedNetwork.py
1,255
3.78125
4
class Solution: def makeConnected(self, n: int, connections: List[List[int]]) -> int: # find number of connected components in the network # number of connections reqd = number of connected components - 1 # this is a simple graph connected components question # if the number...
b883570f1fceebf8d5c89ae53b7aacfbe2531871
yuryanliang/Python-Leetcoode
/100 medium/8/383 ransom-note.py
1,080
3.90625
4
""" Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false. Each letter in the magazine string can only be used once in your ransom note. Note:...
722c9fef00cc8c68bda1a32eb5964413311f1a2d
smtorres/python-washu-2014
/Assignment01/school.py
1,042
4.21875
4
from collections import OrderedDict class School(): def __init__(self, school_name): self.school_name = school_name self.db = {} # Function that adds values and keys to a dictionary. Keys are school grades and each can take as value the name of a kid belonging to that grade. # It returns a dictionary with th...
f0db90784e791d0e90c3d5f10d987f90c3563910
bhawan0407/Python
/Pandas/starter.py
868
3.578125
4
import pandas as pd pd.show_versions() # show pandas as well as dependencies versions pd.show_versions(as_json=True) print (pd.__version__) # dataframes is a 2D array # series is a 1D array of indexed data # pandas support both index and label based indexing # accessing a single series # df['column_name'] or ...
65e3cdfebedc3bd4a70114131f2f7ccb9d704857
Gourav-Sedhai/Basic-Practice
/together2.py
410
3.8125
4
def func(phrases): vars = ("how", "where", "what", "why") capitalized = phrases.capitalize() if phrases.startswith(vars): return "{}?".format(capitalized) else: return "{}.".format(capitalized) result = [] while True: user = input("Say Something: ") if user == "\end":...
c0455a8b735f02255a4ebcb43b0b250729211443
SamJamaloff/hackerrankdailychallenges
/day_11/main.py
617
3.515625
4
if __name__ == '__main__': def get_sum(matrix, row, col): sum = 0 sum += matrix[row][col] sum += matrix[row-1][col-1] sum += matrix[row-1][col] sum += matrix[row-1][col+1] sum += matrix[row+1][col-1] sum += matrix[row+1][col] sum += matrix[row+1][col+...
8a233332e946f6f53a55473046cd37e6c7dbcac8
wjtxlliubin/good-good-study-day-day-up
/leetcode/code/algorithm_code/烧饼.py
583
3.578125
4
def sorter(l, count): if len(l) == 1: return count else: MAX = -1 MAX_ID = -1 for index, value in enumerate(l): if value > MAX: MAX = value MAX_ID = index temp_left = l[:MAX_ID + 1] temp_left.reverse() count += 1...
20d0e10a9ff1da68e8a0a696cd2a1868cec433a2
HelpJamess/Name-Cipher
/cipher.py
1,039
3.65625
4
asciiLower = ['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'] asciiUpper = ['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'] newName = [] def listToStr(lst)...
332b81f8879a3c4a3cac747f284dd478e45da6e2
dapazjunior/ifpi-ads-algoritmos2020
/Iteracoes/Fabio_03/f3_q16_fibonacci.py
271
3.8125
4
def main(): n = int(input('Digite um número: ')) lista = [0, 1] cont = 2 if n == 2: lista = lista else: while cont < n: lista.append(lista[cont-1] + lista[cont-2]) cont += 1 print (lista) main()
da647f7d0e3ed05a0f558bbeff04f6fe02356ef5
humid1/python_learn
/python_study/高级变量类型/demo_字典.py
919
3.90625
4
people_dict = {"name": "小明"} # ==== 取值 ==== print(people_dict["name"]) # ==== 增加、修改 ==== people_dict["age"] = 20 # 增加 people_dict["height"] = 172.5 people_dict["age"] = 21 # key存在,就修改 # ==== 删除 ==== people_dict.pop("name") # 清空 key 为 name 的键值对;若key值不存在就会报错 print(people_dict) # ==== 统计键值对数量 ==== print(len(peop...
a3416e157624c5fb4d421896247861513f82c6c8
dobricsongor/PYTHON
/Polygons.py
1,614
3.921875
4
class Polygon(object): def __init__(self, *args): self.sides = args def __str__(self): return f'Polygon has {len(self.sides)} sides' def display(self): for side_index, length in enumerate(self.sides, start=1): print('Side {} with length: {}'.format(side_index, length))...
26f648b2ab802c0f5ec0b74060b2b4b30e61208f
Rollo-Pollo/CeaserCypherProgram
/Cypher/cypher.py
1,720
4.21875
4
# REVERSE CYPHER #put words in a file and put the file name where words is with open('words.txt', 'r') as file: for line in file: for word in line.split(): start_word = word # lines 2-5 search through the file and pick out the word # These 2 lines reverse each character reversed_word = '' i =...
2948619097864159437a6f5d64df4db25a64f575
tiewangw/Python
/MachingLearning/chapter1/1.1 vector.py
761
4.21875
4
# 创建一个向量(vector) import numpy as np # 创建一个行向量 vector_row = np.array([1,2,3,4,5,6]) # 创建一个列向量 vector_rcolumn = np.array([ [1], [2], [3]]) print(vector_row) # [1 2 3] print("----------------------") print(vector_rcolumn) # [[1] # [2] # [3]] print("-----------...
e200573fe5c9ac5266e5f16453d3468fe1e103f0
ZhaoFelix/Python3_Tutorial
/02.py
1,099
4.125
4
# coding=utf-8 # 类 class Student(object): #定义类属性 name = 'Felix' age = 23 #变量名两个下划线开头,定义私有属性,这样在类外部无法直接进行访问,类的私有方法也无法访问 __sex = 0 #定义构造方法 def __init__(self,name,age,sex): self.name = name self.age = age self.__sex = sex #类方法 def get_sex(self): return ...
7f951c3c21502db18123e06933f918683556a2ce
Vigyrious/python_fundamentals
/Lists_Advanced-Exercise/Moving-Target.py
1,466
3.65625
4
target = input().split(" ") targets = [] for num in target: targets.append(int(num)) def shot(index, amount): targets[index] -= amount if targets[index] <= 0: targets.pop(index) def add(index, amount): targets.insert(index, amount) def strike(targets1, start, end): del targets1[start: ...
25ea185517d7e6db75c2314af720fcf578a1904b
udhayprakash/PythonMaterial
/python3/07_Functions/practical/display_number_pattern.py
1,103
4
4
#!/usr/bin/python """ Purpose: For input of two numbers(say (3,2)), to display number as below: 07 09 11 03 05 01 01 03 05 07 09 11 """ def get_count(m): if m == 1: return 1 return m + get_count(m - 1) def series(_count): numbers = [1] while len(numbers) < _count: ...
52129d3b1b427f4c7a06d9c4a47743409259b551
abenetsol/holbertonschool-higher_level_programming
/0x11-python-network_1/7-error_code.py
387
3.546875
4
#!/usr/bin/python3 """ Takes in a URL, sends a requestt to the URL and displays the value of the variable X-Request-Id in the response header """ if __name__ == "__main__": import requests from sys import argv status = requests.get(argv[1]).status_code if status >= 400: print("Error code: {}".f...
34c65468a5d296eec44a830480f5740bc680b3cb
kirigaine/Socket-Squares
/game_functions.py
2,116
3.59375
4
import sys import pygame def check_events(screen, square): """Respond to keypresses and mouse events""" for event in pygame.event.get(): if event.type == pygame.QUIT: print("justquit") sys.exit() elif event.type == pygame.KEYDOWN: check_keydown_events(event,...
9ce77f3839329e00497c6b488cb7c7b837c04650
gedrex/PyLadies
/06/piskvorky/piskvorky.py
2,651
3.515625
4
#!/usr/bin/python3.4 from random import randint, randrange, sample from glib import input_control from ai import tah_pocitace def starter(): """ starter(None) - losuje nahodne ze 3 cisel. Pokud ho uzivatel uhadne, vraci True, pokud ne, vraci False. """ random_number = randrange(1,4) user_choice = i...
d8aceae1dd4f7f895ed7e8d82cca6e09f63ac023
sabastar/Python
/ExamStats.py
1,541
4.375
4
# MINI PROJECT: Create a program to compute stats grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5] # Write a function to print out the list of grades, one element at a time def print_grades(grades_input): #iterate through list and print each item on its own line for i in grades_input: pri...
0b8ce43c489daba2fd691bf798458488fbaf1250
aayushi-droid/Python-Thunder
/Solutions/oddishVsEvenish.py
625
4.03125
4
import sys from functools import reduce """ Probem Task: Create a function that determines whether a number is Oddish or Evenish. A number is Oddish if the sum of all of its digits is odd, and a number is Evenish if the sum of all of its digits is even. If a number is Oddish, return "Oddish". Otherw...
c2ec0d7efe726145fa9efcb8c2315ef4e1e64079
manhtung2111/Homework_write_in_Class_type
/4.py
330
3.796875
4
class triangle: def __init__(self, a, b, c): self.a = a self.b = b self.c = c def area(self): s = (self.a + self.b + self.c) / 2 area_count = (s*(s - self.a)*(s - self.b)*(s - self.c)) ** 0.5 print("dien tich hinh tam giac la:",area_count) num = triangle(3, 4, 5) ...
2f5fdb8b1d2754e8c1a67ee896170cf011efd139
dulceadelina/criba
/main.py
1,407
4.03125
4
# Programa que implementa la criba de Erastótenes # donde define los números primos de 2 hasta n # Dulce Adelina Zuñiga Ramos # 20/09/2020 - 21/09/2020 from math import isqrt # here implements sieve of Eratosthenes and receives n def sieve(): # criba in english n = data() # as...
c904b236955c6ba88cf9d0533acf38f52898a722
koilhyuk/Algorithm
/src/baekjoon/bronze/haknum_1_2754.py
348
3.625
4
score = input() result =0 if score[:1] == "A": result+=4 elif score[:1] == "B": result+=3 elif score[:1] == "C": result+=2 elif score[:1] == "D": result+=1 else: result+=0.0 if score[1:] =="+": result+=0.3 elif score[1:] =="0": result+=0.0 elif score[1:] =="-": result-=0.3 else: ...
65263231684173318bd0f685269efcf3307dd924
arslan21/pythonworld-tasks
/pythonworld_test_square.py
745
3.859375
4
# расчет площади, периметра и диаганали по стороне квадрата import math def square(a): per = a * 4 sq = math.pow(a, 2) dia = math.hypot(a, a) return(per, sq, dia) import unittest class SquareTestCase(unittest.TestCase): def test_square(self): for a in range(10): with self.s...
d0fa4e17039d48cb0800608ba79d3f1ec817531a
KristjanVeensalu/Omis_Python_EN
/Week 1/firstFIle.py
1,505
4.21875
4
#This is a comment '''print("Hello world!") print(5) print(5+5) print("Testing if this works" + "5") print(10*2-15)''' '''MyFirstVariable = 10 print(MyFirstVariable) MySecondVariable = "This is my variable" print(MySecondVariable) MySecondVariable = 20 print(MySecondVariable)''' ''' firstSide = 10 print(firstSide*...
c236a321425fe774f79315332f875ab2ded96f27
darekj28/free-algos
/4_graphs/edge.py
702
3.5625
4
class Edge: # initializes an edge between vertices v and w with a certain edge-weight def __init__(self, v, w, weight): self._v = v self._w = w self._weight = weight # returns the weight of this edge def weight(self): return self._weight # returns either vertex in this edge ...
7086d5af6707d1d130361de588ebe98fd7b2c713
aaronshang/TDDDemo
/pythonNotes/readTextFile.py
303
3.578125
4
#!/usr/bin/python #set filename fname = '/Users/teso/Desktop/make.txt' #attempt to open file for reading try: fobj=open(fname,'r') except IOError,e: print '***file open error:',e else: #display content to the screen for eachline in fobj: print eachline, //finally close file fobj.close()
1a397059ea44c3a0b11c1362e5a029ba0fc94ba0
Tolianych/Main
/Python/EPAM2/WordLetterCounter/WordLetterCounter.py
703
3.703125
4
''' Created on Jan 20, 2015 @author: s.botyan ''' text_file = open("something.txt") text = text_file.read() list_strings = text.splitlines() count_dict = {} for string in list_strings: list_words = string.split(" ") for word in list_words: # filtering all symbols except alphabet letters_coun...
df8815674ea43ed5f815a4084fe372438765328f
akshaypawar4325/Python
/6.Dictionary_Mandar_sir_technique.py
181
3.921875
4
D1={1:['MANDAR',{'HINDI':56,'ENG':70}]} print(D1) d2=D1[1][1] print(d2) marks=[] for key in d2: marks.append(d2[key]) print(marks) highest=max(marks) print(highest)
f0c0eafa0f7da1f6bd8975b3ec91805d8c8bea28
harmanbirdi/python
/1app/tree.py
2,826
4.03125
4
#!/usr/bin/env python # # Description : Print the directory tree of a given directory using any scripting language # (i.e. anything *except* for a Bash script or a plain shell command). # More Info : Asked by Nour for 1app phone screen interview # __author__ : Harman Birdi # Date : Sep 16, 2016 ...
519be51464b3b72af181b386a6f0ec760d315252
M1c17/ICS_and_Programming_Using_Python
/Week2_Simple_Programs/Lecture_2/Ex-isInString-recursive.py
1,388
4.3125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jan 4 12:02:14 2019 @author: MASTER """ # DETERMINE IF A CHAR IS IN A STR # use bisection search # string is sorted in alphabetical order # base case: empty str # base case: len 1 # Base case: test the midcha of aStr against the cha you're look...
f919de5bfb2253436cf3c0d7dcfe6c3556e5838c
Spraynard/Card-Game-Suite
/Modules/Cards/Card.py
1,965
3.703125
4
def cardRankToNum(rank, variant = None): if not variant: if rank == "Ace": return 14 elif rank == "King": return 13 elif rank == "Queen": return 12 elif rank == "Jack": return 11 else: return int(rank) elif variant == "blackjack": if (rank == "Jack" or rank == "Queen" or rank == "King"): ...
8768267d8f35dc3333325a24b5ed0522e1a55609
vacuum136/CppND-Capstone
/unit2_pp/scripts/unit2_exercise.py
2,874
3.859375
4
#! /usr/bin/env python """ Dijkstra's algorithm path planning exercise Author: Roberto Zegers R. Copyright: Copyright (c) 2020, Roberto Zegers R. License: BSD-3-Clause Date: Nov 30, 2020 Usage: roslaunch unit2_pp unit2_exercise.launch """ import rospy def find_neighbors(index, width, height, costmap, orthogonal_step...
f75b5b23f4f3c5210fa5026d993f5c2cc4c4462d
lenniecottrell/Python-Projects
/End_of_course_Challenges/Database_and_Python_Challenge.py
886
3.65625
4
import sqlite3 from sqlite3 import * rosterValues = (('Jean-Baptiste Zorg', 'Human', 122), ('Korben Dallas', 'Meat Popsicle', 100), ('Ak\'not', 'Mangalore', -5)) with sqlite3.connect(':memory:') as connection: conn = connection.cursor() conn.execute("CREATE TABLE IF NOT EXISTS Roster(Name TEXT, Species TEXT, ...
41777bdaf9e9f942d3b50f13fd9c7f47c289c943
ink-water/ink
/git_test/test03.py
1,970
3.53125
4
import pymysql class Database: def __init__(self): self.db = pymysql.connect(password="123456", database="client", user="root", charset="utf8") self.cur = self.db.cursor() def register(self): print("按回车键退出注册界面") while True: name = input("请输入用户名:") if no...
519706178836f17c408507ff1cc16e67e8a9ac5b
kirankumar2/BridgeLabz
/new/week1/Alogrith/primanagra.py
571
3.765625
4
from collections import Counter num = [] def findPrime(n1, n2) : for x in range(n1, n2) : if x > 1 : for n in range(2, x) : if (x % n) == 0 : break else : print(x) num.append(x) start = 0 end = 1000 findPrime(st...
d9b74105e328ebeabc983824d11c70a8ce02280c
sethdeane16/projecteuler
/037.py
968
3.703125
4
import resources.pef as pef import time """ https://projecteuler.net/problem=37 4.08533501625061 """ def main(): total = 0 num_found = 0 primes = pef.prime_sieve(999999) for i in primes[4:]: count = 0 # determine amount to remove from each end for d in range(len(str(i))): ...
e72be975da543ee3a16bb030a7ff0bcd0e65415d
brjoaogabriel/disparador_email
/functions/abrevia_sobrenomes.py
758
3.578125
4
from log_paste.log_funções import PrintarLogFunção; #Para cada nome que estiver dentro de sobrenomes, abrevia. #Exemplo: "João Gabriel Maciel" se torna "João Gabriel M." Caminho = "disparador_email.functions.abrevia_sobrenomes.py"; def AbreviarSobrenomes(NomeCompleto, Sobrenomes): try: Nome: str; ...
a4ff8e9ed2dafbbc8c81b044322378f3a86d0af5
dgpllc/leetcode-python
/learnpythonthehardway/range-module-715.py
4,879
3.875
4
# A Range Module is a module that tracks ranges of numbers. Your task is to design and implement the following # interfaces in an efficient manner. # # addRange(int left, int right) Adds the half-open interval [left, right), tracking every real number in that # interval. Adding an interval that partially overlaps with ...
0dc1664c45ef391b95b1496d64c82a5024f0696e
MiroVatov/Python-SoftUni
/Python Fundamentals 2020 - 2021/Final Exams Practice/01. String Manipulator.py
1,276
3.84375
4
initial_string = input() while True: command = input() if command == 'End': break token = command.split() action = token[0] if action == 'Translate': char = token[1] replacement = token[2] if char in initial_string: initial_string = initial_st...