blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
922638b27f743c13fbed9bf09b4b498a2b72f487 | dataOtter/CodeFights-Python3 | /challenge3_secret_lock.py | 6,336 | 3.984375 | 4 | """
SUBMITTED IN JAVASCRIPT. THIS PYTHON SOLUTION NOT FINISHED.
CFBot stores all of her important information in the Secret Archives.
CodeMaster is trying to pick the lock! The lock, a metal rectangle composed of movable cells,
is unique and hard to pick. Some of the lock’s cells are occupied, and some are empty.
The ... |
49d0219eee28806167bced5b573d97aab67d17ba | Skumbatee/andela-labs | /stringlength.py | 373 | 4.1875 | 4 |
# declare a function that takes a list argument
def check_string(items):
# declare an empty list where you will append the length for strings
empty = []
# loop through the list argument
for item in items:
# append the length of strings in the list in empty list
empty.append(len(item))
return empty
print chec... |
10c48cf87f9d8686b42213a5af4ae9dd6198cd02 | Jassii/HackerRank-Solution-Python-language- | /Compress_the_String.py | 235 | 3.859375 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import itertools
s = input() #input of the string..
for k,a in itertools.groupby(s): #passing the string
print("({}, {})".format(len(list(a)),k),end=" ")
|
b1c3e027e30e36a99afb65ccba9d7e21e4394974 | ampasancho/GithubTraining | /src/ejer.py | 230 | 3.71875 | 4 |
def showNumbers:
number = input("Introduce numero: ")
for i in range(0, number+1)
print(i + "\n")
def par_impar(numero):
resto = numero % 2
if resto == 1:
return 1
else:
return 0
|
66110c655443f265965a3caa2ab4972d676f08df | RAmruthaVignesh/PythonHacks | /DataStructures/linkedlist.py | 4,771 | 4.1875 | 4 | class node(object):
data = None
ptr = None
class LL(object):
head = None
def __init__(self):
pass
def insert(self , position,value):
# Insertion when the linked list is empty
if self.head == None:
mynode = node()
mynode.data = value
... |
3eb1ee4b2c391cc3da0ed50a0e6c4d7465bf7d1d | AZ-OO/Python_Tutorial_3rd_Edition | /4章 制御構造ツール/4.7.4.py | 611 | 3.671875 | 4 | """
4.7.4 引数リストのアンパック
"""
# 引数にしたいものがすでにリストやタプルになっていて、
# 位置してい型行き数を要求する関数のためにアンパックしなければならないという時
print(list(range(3,6)))
args = [6,10]
print(list(range(*args)))
def parrot(voltage, state = 'a stiff', action = 'voom'):
print("This parrot wouldn't", action, end= ' ')
print("if you put", voltage, 'volts through ... |
92a14f8b5c43a427db7540d9c056016d36a9b635 | DeanHe/Practice | /LeetCodePython/MaximumTwinSumOfaLinkedList.py | 2,151 | 4.15625 | 4 | """
In a linked list of size n, where n is even, the ith node (0-indexed) of the linked list is known as the twin of the (n-1-i)th node, if 0 <= i <= (n / 2) - 1.
For example, if n = 4, then node 0 is the twin of node 3, and node 1 is the twin of node 2. These are the only nodes with twins for n = 4.
The twin sum is d... |
a41a81204ca32860b4f37dff534be53488e7e108 | mdk7554/Python-Exercises | /MaxKenworthy_A2P1.py | 2,024 | 4 | 4 | """
Exercise: Given a flat text file containing names of boys and girls, create a function that records the number of times each name
ends in a certain letter of the alphabet. Executing the function produces a 26x2 dataframe where each letter of the alphabet has a
row and a column for each boy and girl names.
"""
impo... |
d17c130017712e620cdb75caf7f3d8624c956ed8 | lalaboom/algorithm-practice | /剑指offer/从上往下打印二叉树.py | 747 | 3.90625 | 4 | #从上往下打印二叉树
# 题目:
#从上往下打印出二叉树的每个节点,同层节点从左至右打印。
# 思路:
#遍历二叉树的两种方式:
# 1.递归
# 2.非递归,入栈:根节点入栈,如果节点不为空,处理这个节点,同时左右子节点入栈
class Solution:
# 返回从上到下每个节点值列表,例:[1,2,3]
def PrintFromTopToBottom(self, root):
if not root:
return []
temp = [root]
result = []
while len(temp):
... |
b295d06ce695d5d627ff0cd380046f5848149ac9 | rkujawa/py-exercises-osec | /ex09/order_csv.py | 265 | 3.59375 | 4 | #!/usr/bin/env python3
from order import *
import csv
class OrderCSV(Order):
def save(self, filename):
with open(filename, 'w') as csvfh:
writer = csv.writer(csvfh)
for i in self:
writer.writerow(i.to_list())
|
2f3d7936617707d05ad8bec61c08fd1451f2e1b7 | VivekVRaga/Coding-Projects | /Fantasy Game.py | 614 | 3.515625 | 4 | stuff = {'rope': 1, 'torch': 6, 'gold': 42, 'dagger': 1, 'arrow': 12}
loot = ['gold', 'dagger', 'gold', 'gold', 'ruby']
def dispinventory(inven):
print('inventory:\n')
for k, v in inven.items():
print(k+'\t', v)
def addinventory(inven, ainven):
for i in range(0, 5, 1):
print(... |
dd0358dd5cf112ebb7efaf1acb944d967a41d2a7 | Drag0nus/Challenges | /Easy_Challenges/list_low10.py | 719 | 4.40625 | 4 | a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
for item in a:
if item < 5:
print(item)
num = int(input("Enter number: "))
result = [item for item in a if item < num]
print(result)
# Take a list, say for example this one:
# a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
# and write a program that prints out all... |
7eae9cd800f809d5967710afceecb8b7b1f140f5 | zjlyyq/algorithm009-class01 | /LeetCode/9. 回文数(翻转数字).py | 499 | 3.578125 | 4 | class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0: return False
x_reversed = 0
x_length = 0
x_copy = x
while x_copy > 0:
x_copy = int(x_copy / 10)
x_length = x_length + 1
l = int(x_length / 2)
while l > 0:
x_r... |
5a5590671f8c21cb76c07d08aba345f3d1bc72d9 | grebwerd/python | /practice/practice_problems/flipAndInvertImage.py | 393 | 3.5 | 4 | class Solution:
def flipAndInvertImage(self, A):
"""
:type A: List[List[int]]
:rtype: List[List[int]]
"""
for l in A:
l.reverse()
for index, value in enumerate(l):
if value is 0:
l[index] = 1
... |
c1f8b26952c31e48b18fb1815e2cc8540727bd85 | sidrashareef99/exactDollar | /main.py | 668 | 3.96875 | 4 | pennies = int(input('Enter the number of pennies:'))
quarters = int(input('Enter the number of quarters:'))
nickels = int(input('Enter the number of nickels:'))
dimes = int(input('Enter the number of dimes:'))
pennies_total = pennies * 0.01
nickels_total = nickels * 0.05
quarters_total = quarters *.25
dimes_total = di... |
fdfd63c1817570142894f7ce1a77cfe62a553c5b | sgarcialaguna/Project_Euler | /problem2.py | 675 | 3.953125 | 4 | """Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2,
the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum
of the even-valued terms."""
... |
80362116992cdbfadd72cf4f7c24c1938d64470a | xjh1230/py_algorithm | /test/l617merge_tree.py | 5,003 | 3.59375 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Author : 1230
# @Email : xjh_0125@sina.com
# @Time : 2019/11/22 13:09
# @Software: PyCharm
# @File : l617merge_tree.py
from data_structure.leecode_tree_node import TreeNode
from data_structure.leecode_tree_node import gen_tree
from data_structure.leecode_tree_no... |
65e579b0d9fb523b7e44bdf4efffa5cff325c996 | AbidMerchant-1106/CompetitiveProgramming | /binlevelordertraversal.py | 2,203 | 3.765625 | 4 | class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Solution2:
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
def dfs(node, depth):
if node is Non... |
e9b4a865844c6da50ad1da9ba9424eadfd6714be | jasminro/2021python | /Week4/h5.py | 625 | 4.1875 | 4 | '''
Harjoitus 5
Palindromi
Kirjoita funktio, joka tarkistaa, onko sana palindromi. Palindromi on sana, joka on sama
kirjoitettuna oikein ja väärin päin. Sanan kirjainten koolla ei ole merkitystä.
Oletus: Sana ei sisällä white space -merkkejä (rivinvaihto, välilyönti, tabulaattori).
Bonus: Sana saa sisältää white space ... |
a654bc0124c1097504d2d8c46af60d21ace10bf9 | AmuroPeng/CodingForInterview | /2020April-30-day-leetcoding-challenge/16-Valid Parenthesis String/16-Valid Parenthesis String.py | 1,217 | 3.734375 | 4 | import collections
class Solution:
def checkValidString(self, s: str) -> bool:
# chars = collections.deque(s)
# left = 0
# right = 0
chars = []
count = 0
for i in s:
if i == "(" or i == "*":
chars.append(i)
else: # ")"
... |
65b795173f96011785806c20edfc067ecd553e96 | runbrain/fluffy-doodle | /AByteOfPython/if.py | 212 | 3.875 | 4 | import antigravity
number = 32
guess = int(input('input integer : '))
if guess == number:
print('congradulations you right')
elif guess < number:
print('value is biger')
else:
print('value is smaler') |
922a17d63c01c8bc1a4706a733c6bcd2941f6de2 | Abel-Fan/USTF1908 | /python02/01回顾.py | 2,923 | 4.03125 | 4 | # python
# 语法特点:面向对象的、动态类型、强类型语言。严格的缩进模式
# 注释:
# 单行注释 #
# 多行注释 """ """ ''' '''
# 输入输出
# input(info) info:用户提示信息
# print([arg1,arg2,....]) 参数不限 参数可以是 变量、值、表达式
# end 输出内容末位的字符,默认\n
# name = "小白"
# print(name,19,20+56)
# print("123",end="")
# print("456",end="")
# 变量
# 变量定义:可变的数据
# 变量的定义语法:
# 简单定义 name="小白"
#... |
6b14803f68ed877e172854c6c768c14aebd61994 | DeathStroXX/Coding | /Codes/Array/Q5aUsingTwoPointer.py | 1,015 | 3.765625 | 4 | def NumberOfTriangles(array):
n = len(array)
array.sort()
print(array)
count = 0
for i in range(n-1,0,-1):
l = 0 # This is the beginning pointer.
r = i - 1 # this is the pointer just before the end pointer.
while l < r:
if array[l] + array[r] > array[i]:
... |
ad3061242c6fad992cc271d57a0185d8b616e3d1 | jrpresta/AdventOfCode2020 | /Day2/puzzle.py | 1,599 | 3.65625 | 4 |
class PasswordRules:
def __init__(self, min, max, letter, pw):
self.min = int(min)
self.max = int(max)
self.letter = letter
self.pw = pw
def validate(self):
count = self.pw.count(self.letter)
return self.min <= count <= self.max
class PasswordRulesNew:
def... |
694e8f7bc11806c24d3907c7af74805fb62d735e | LucMatheus/py3.GuanaPy | /World 3 - Mundo 3 - Intermediario/73 - Brasileirão.py | 1,239 | 3.953125 | 4 | '''
Exercicios de tuplas agora trabalhando com a tabela do brasileirão
@author Lucas Matheus Costa <teclucas.costa@hotmail.com>
@since 18/07/2021
'''
#Colocando a tabela do Brasileirão
tabelaDoBrasileirao = ('Palmeiras','Atlético-MG','Fortaleza','Bragantino','Athletico-PR','Ceará SC','Bahia','Fluminense','Flamengo','... |
5e914eb40b7c003f543d7c78aab7460691b7bd6d | mrgyange/python-project | /Matamorosa_e1.py | 701 | 3.828125 | 4 | # filename : Matamorosa_e1.py
# author : Marge Angela P. Matamorosa
# description : This is a python program that prints
# the contents of a dictionary in a specific format
message = "I am {}.\n" + "My spirit animal is {},\n" + \
"because {}.\n" + \
"When not in... |
3b7b15ec3edf9790f32da1e19aa6c8320cfb459b | gmotzespina/Algorithms | /numbers/plusOneSplit.py | 335 | 3.515625 | 4 | #!/usr/bin/python3
number = ["9","9","9"]
convertArrayToString = lambda number: "".join(number)
incrementByOne = lambda number: number+1
numToIncrement = int(convertArrayToString(number))
incrementedNumber = incrementByOne(numToIncrement)
incNumString = str(incrementedNumber)
incNumArray = list(incNumString)
prin... |
e31e59c6552e1efc52c96c68d901b78d82bc4f8e | yom-elect/free-up | /gufdd.py | 1,530 | 3.5625 | 4 | from collections import Counter
import statistics
'''d = {'a':2, 'b':4, 'c':10}
def fun(a, b, c):
print(a, b, c)
# A call with unpacking of dictionary
fun(**d)
string1 = input ("insert string1 :")
string2 = input ("insert string2 :")
dict1, dict2 = Counter(string1), Counter(string2)
... |
38f79d163a869392b37353023b55836a303d0842 | davidlowryduda/AoC18 | /python/utils.py | 895 | 3.78125 | 4 | #! /usr/bin/env python3
"""
utils.py --- Common utilities
Opens files, maybe does little math things, whatnot.
"""
def _read_file(filename):
try:
return open(filename, "r")
except FileNotFoundError:
print("The file was not found.")
raise
def read_input(day, test=False):
"""
... |
cd55c46b76add264e9fce1f1beba3d6bb40e35eb | ksu3101/studyPythonRepo | /testString.py | 1,941 | 3.546875 | 4 | montyPython = "Monty python's Flying Circus"
# 문자열의 길이 `len()`
print("monty's count = %d" % len(montyPython))
# 문자열에서 특정 문자나 단어의 갯수 세기 `count()`
print(montyPython.count('o'))
print(montyPython.count('on'))
# 문자열에서 특정 문자의 인덱스 얻기 `find()` : 없을 경우 -1
# 가장 처음을 찾게 되는 문자의 인덱스를 얻는다.
print(montyPython.find('p'))
print(monty... |
bfbe7b557f7a484918b1b86e83a441122d959c38 | ryanvgates/intro-to-pytest-2019-08-12 | /pytests/functions.py | 346 | 3.875 | 4 | def divide_by_two(a):
return a / 2
def divide_by(a, b):
return a / b
def sum_all(list_el):
if type(list_el) != list:
raise ValueError('It suppose to be a list')
if len(list_el) == 0:
raise ValueError('The list have to has at least 1 element')
acc = 0
for el in list_el:
... |
68351451b4348d8fca11963685bf3d1cc7c7b96d | linruili/leetcode-python3.5 | /49. Group Anagrams.py | 407 | 3.703125 | 4 | import collections
def groupAnagrams(strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
if strs[0] == "":
return [[""]]
L = []
d = collections.defaultdict(list)
for x in strs:
d["".join(sorted(x))].append(x)
for x in d.values():
x.sort()
L.ap... |
9028ab6c8800e84778f67a6c3b86611213c96cc9 | RajVjti/CCTech | /testing of buildiing.py | 2,608 | 3.65625 | 4 | buildings= []
temp = []
H=[]
W=[]
''' Code to take input starts here
Enter input as cordinates comma seprated eg. 3,4
To break the input cordinates enter an integrer value
eg.
4,0
4,-5
7,-5
7,0
1 ## to break
1,1 ## Source input
'''
def tempLength(tem... |
4198427ee8c953a4d1f37dfea509bc666861bf60 | chitn/Algorithms-illustrated-by-Python | /example/list.py | 956 | 4.1875 | 4 | # List as an array
# One-dimensional
a1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
a1.append(10) # Add an element to a list
a1.append(3.14)
a1.append('hello')
b = a1[1:4:1] # Slicing a list to crete another list
b = a1[:4]
b = a1[1:]
print(a1[ 0]) # Print the first element
print(a1[-2]) ... |
a35cdea62cd73afe63a5c6a19792f6fbd7e92ad9 | r50206v/Leetcode-Practice | /2022/*Medium-19-RemoveNthNodeFromEndOfList.py | 1,568 | 3.875 | 4 | '''
two pass
time: O(N)
space: O(N)
'''
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
length = head
... |
07d9070b4a79140c341bc6d8fa150d569d346b52 | ze25800000/gaoji_python | /py_file/2-3.py | 446 | 3.578125 | 4 | # 如何统计序列中元素出现频度
from random import randint
# 方法1
data = [randint(0, 20) for _ in range(30)]
c = dict.fromkeys(data, 0)
for x in data:
c[x] += 1
print(c)
# 方法2
from collections import Counter
c2 = Counter(data)
# 出现频度最高的元素
print(c2.most_common(3))
# 方法3
import re
txt = open('2-2.txt').read()
txt = re.spli... |
ef8eceb31544e2f93c390e4dfa03b87b2c5c142d | Kim-Ly-L/LPTHW | /EX09/ex9.py | 755 | 3.546875 | 4 | # Here's some new strange stuff, remember type it exactly.
days = "Mon Tue Wed Thu Fri Sat Sun"
# when it comes to "\n" the kind of the slash does play a role!
# even on Windows
# "\n" separates the terms/characters within a string into different lines
# ...even though there's no spacing - magic!
months = "Jan\nFeb\nM... |
fd671455aae8fae94ce1e0a875e9251e52647d57 | isakss/Forritun1_Python | /midterm_list_exercise5.py | 948 | 4.375 | 4 | """
This program allows the user to input as many values into a list as the user dictates and then finds the lowest element from that list.
The program ignores values that are not of type int.
"""
def populate_list(int_object):
new_list = []
while len(new_list) != int_object:
list_element = input("Ente... |
2dcaef0a9761f3892b7b772a37658e14d9344cb2 | summertian4/Practice | /LeetCode/0141.py | 504 | 3.671875 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self):
self.next = None
class Solution(object):
def hasCycle(self, head):
slowerNode = head
fasterNode = head
while(slowerNode is not None and fasterNode is not None and fasterNode.next is not None):
... |
c15281f3f29a5771d62155fbd3f775b79ee6567f | Neha-kumari200/python-Project2 | /largestarray.py | 275 | 4.46875 | 4 | #Python program to find largest element in an array
def largest(arr, n):
max = arr[0]
for i in range(1,n):
if arr[i]>max:
max = arr[i]
return max
arr = [50, 55, 30, 79, 34]
n = len(arr)
ans = largest(arr, n)
print("Largest element is:",ans)
|
41955dfe1c01e58e7830c997e3311ee9ee9f0714 | shankar7791/MI-10-DevOps | /Personel/Chandrakar/Assessment/09jul/pro03.py | 305 | 3.65625 | 4 | def f(n):
b=1
for c in range(1,n+1):
b = b*c
return b
n = int(input("Enter the number : "))
for i in range(0, n):
for j in range(1,n-i):
print(" ", end="")
for k in range(0, i+1):
a = int(f(i)/(f(k)*f(i-k)))
print(" ", a, end="")
print() |
a74b465fbb6f86c6b271275799a1981d526a2b76 | AHartNtkn/DS-Unit-3-Sprint-1-Software-Engineering | /sprint-challenge/acme_test.py | 1,927 | 3.546875 | 4 | #!/usr/bin/env python
import unittest
from acme import Product
from acme_report import generate_products, ADJECTIVES, NOUNS
class AcmeProductTests(unittest.TestCase):
"""Making sure Acme products are the tops!"""
def test_default_product_price(self):
"""Test default product price being 10."""
... |
ecb8154c84dd8e1692b23a13998d157fa4011143 | pmarcol/Python-excercises | /Python - General/Basic/011-020/excercise016.py | 497 | 3.703125 | 4 | """
Write a Python program to get the difference between a given number and 17,
if the number is greater than 17 return double the absolute difference.
"""
"""
SOLUTION:
"""
import sys
from pathlib import Path
abspath = Path(__file__)
toolspath = abspath.parents[3]
sys.path.append(str(toolspath / 'tools'))
from Get... |
825172e0f36ca657f5f4adb3cc28e52a9575cbe1 | Dumacrevano/CSCI318-Task1 | /Paper 1-Based ART.py | 1,113 | 3.765625 | 4 | from random import *
f = 5
def calculate_min_dist(ci, T):
x2 = 0
s_Dist = 100
for y in T:
x1 = abs(y - ci)
print('Candidate Value:', ci, ', Existing Value:', y, ', Difference:', x1, ', Current Shortest Distance:', s_Dist)
if (x1 < s_Dist):
s_Dist = x1
x2 = x... |
3db5636264f49a68885b815135c28ac54b0c031c | Jayasri001/pandas-python | /pandas python 3.py | 2,136 | 4.46875 | 4 | import pandas as pd
import numpy as np
#"**22.** You have a DataFrame `df` with a column 'A' of integers. For example:\n",
#"How do you filter out rows which contain the same integer as the row immediately above?"
df = pd.DataFrame({'A': [1, 2, 2, 3, 4, 5, 5, 5, 6, 7, 7]})
print(df)
duplicate = df.loc[df.duplicat... |
29cfba7df070db8899931b191d9b187b1b53ee7a | bohdanpuzii/Test_task | /task2/main.py | 605 | 3.734375 | 4 | def get_dictionary_by_value(value):
result = {'$$@@': value % 3 == 0 and value % 5 == 0,
'$$': value % 3 == 0,
'@@': value % 5 == 0}
return result
def get_first_true_key(dictionary):
keys = dictionary.keys()
for key in keys:
if dictionary[key]:
return ke... |
d41d1fa214dd3488b97f1f6ad7f10a45fd39d3a9 | sanjeevseera/Python-Practice | /Basic_Programs/Part1/P022_countInList.py | 253 | 4.03125 | 4 | """
Write a Python program to count the number 4 in a given list
"""
numbers=input("enter the numbers with comma seperated:\n").split(",")
count=0
for i in numbers:
if int(i) == 4:
count+=1
print("number of 4s in list: %i"%count) |
694ac91eec52f84fdac4581f1cd3be42554925d4 | CertifiedErickBaps/Python36 | /Listas/Practica 7/positives.py | 1,028 | 4.125 | 4 | # Authors:
# A013979896 Erick Bautista Perez
#
#Write a program called positives.py. Define in this program a function called
#positives(x) that takes a list of numbers x as its argument, and returns a new
#list that only contains the positive numbers of x.
#
# October 28, 2016.
def positives(x):
a = ... |
7c1eb2b2c0a60ccdd82c9112705dfb9d3eb784e5 | dxrogel/ANN-1 | /venv/punto.py | 1,202 | 3.515625 | 4 | import numpy as np
softmax_output = [0.7, 0.1, 0.2]
softmax_output = np.array(softmax_output).reshape(-1, 1)
print(softmax_output)
print(np.diagflat(softmax_output))
print(np.dot(softmax_output, softmax_output.T))
# Validate the model
# Create test dataset
X_test, y_test = spiral_data(samples=100, classes=3)
# Perf... |
468bab6d59be58a54098da68986f43984c2b25d2 | jessjoschwartz/Exercise09 | /markov.py | 972 | 3.734375 | 4 | #!/usr/bin/env python
from sys import argv
script, filename = argv
def make_chains(corpus):
"""Takes an input text as a string and returns a dictionary of
markov chains."""
input_text = corpus.read()
words = input_text.split()
chain_dict = {}
for i in range(len(words) -2):
tuple_words... |
fb5f236e31ac0efdc9fca7423171a2b52c05ea8c | gvashishtha/cs182_gjk | /example.py | 848 | 3.703125 | 4 | import midi
from note import Note
def compile_notes(notes_list):
"""
Takes in a list of Note objects and returns a playable midi track
example use of midi library defined here:
https://github.com/vishnubob/python-midi
Follow installation instructions from Github readme to use.
"""
pattern... |
fe2c2c3b0cbe134f86c9d23c2bfedd88e2b3babd | AlexKVal/leetcode | /remove_duplicates_sorted_array/rm_dups.py | 3,942 | 3.796875 | 4 | from typing import List
def removeDuplicates(nums: List[int]) -> int:
if len(nums) == 0: return 0
curr_index = 0
for next_index in range(1, len(nums)):
if nums[curr_index] != nums[next_index]:
curr_index += 1
nums[curr_index] = nums[next_index]
return curr_index + 1
# nums = []
# nums = [1]
... |
dfe038db09dd6b641500efa532cac99ff4b5a098 | budytanico/examen-final | /python/repaso4.py | 325 | 4.0625 | 4 | print("COMPARADOR DE NÚMEROS")
numero1 = int(input("Escriba un número: "))
numero2 = int(input("Escriba otro número: "))
if numero1 > numero2:
print('El mayor es el primero: ' + str(numero1))
elif numero1 < numero2:
print('El mayor es el segundo: ' + str(numero2))
else:
print("Los dos números son iguales")... |
0a18aee3eb6f4e6156e675cd71cd081e7b45119b | danwwww/AI-Expendibot | /partB-3/your_team_name_3/player.py | 6,310 | 3.625 | 4 | import sys
import json
from math import inf
from your_team_name_3.search import *
import random
class ExamplePlayer:
def __init__(self, colour):
"""
This method is called once at the beginning of the game to initialise
your player. You should use this opportunity to set up your own interna... |
e71e12c3b688ee73489c3540458cffeffc30c5c9 | jcebo/pp1 | /04-Subroutines/27.py | 381 | 3.609375 | 4 | tekst='Nam strzelać nie kazano. Wstąpiłem na działo. I spojrzałem na pole, dwieście armat grzmiało. Artyleryji ruskiej ciągną się szeregi, Prosto, długo, daleko, jako morza brzegi.'
def ile(a,tekst):
i=0
for n in tekst.lower():
if n==a:
i+=1
return i
a=input('Podaj samogloske: ')
p... |
cd8abdba0ea98a0bd2f9f8244662e25378ebfc96 | ayesha-syed/datasturctures-BloomFilter | /Bloom Filter/Project/document.py | 2,716 | 3.84375 | 4 | from dataclasses import dataclass
import pathlib
@dataclass
class Location:
"""The location of a word in a document."""
doc_id: str
start: int
stop: int
class Document:
"""A document in a corpus. It allows to access the contained words with stop
words and punctuation filterd ou... |
7788c5b7a3aaa79bfb14e0563e7f52a49228cbba | hyperlolo/Blackjack_Python | /main.py | 3,122 | 4.0625 | 4 | ###########Blackjack project by Karanjit Gill###########
###########Requirements for game###########
## Cards are removed from the deck as drawn
## Cards have the same probability of being drawn from deck
## The deck is unlimited in size.
## There are no jokers.
## The Jack/Queen/King all count as 10.
## The the Ace c... |
c6f8dd8c214583f943099efdbae480bb71e4d76a | borisachen/leetcode | /134. Gas Station.py | 1,304 | 3.953125 | 4 | 134. Gas Station
There are N gas stations along a circular route, where the amount of gas at station i is gas[i].
You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1).
You begin the journey with an empty tank at one of the gas stations.
Return the ... |
571b993c2f787223f687b668d9725b72ad94c136 | Mandarpowar13/basics-of-python | /while loop.py | 69 | 3.765625 | 4 | i = 2
while i <= 20:
print(i)
i += 2
print("done with loop")
|
bdb1901f4414123ac96cb8a085e39dc1a9033a76 | manu-j3400/The-Simple-Math-Game-SMG- | /main.py | 1,153 | 3.6875 | 4 | import time, os, mathOperations
import mathIntroAnimation
Red = "\033[0;31m"
Green = "\033[0;32m"
White = "\033[0;37m"
red = "\033[0;91m"
green = "\033[0;92m"
yellow = "\033[0;93m"
blue = "\033[0;94m"
magenta = "\033[0;95m"
cyan = "\033[0;96m"
white = "\033[0;97m"
blue_back = "\033[0;44m"
orange_back = "\033[0;43m"
re... |
75ed893b4fc9d8fbdbb35bab7ecb6bbbc23fe8da | calebballw/old_code | /quizlet.py | 331 | 3.84375 | 4 | def quizlet(question, answer):
question = str(question)
answer = str(answer)
user = input(question)
if user == answer:
print ("Good Job")
else:
print ("Wrong answer")
while 1 == 1:
quizlet(input("Type in a question: "), input("Type the answer to that question: "))
... |
d6fdc22875fd3b2bdad71c5980fe08592d63244c | caryt/utensils | /null/tests.py | 2,005 | 3.796875 | 4 | """Test Null
============
"""
from unittest import TestCase
from null import Null
class TestNull(TestCase):
"""Test the :class:`.Null` object.
"""
def assertNull(self, obj):
return self.assertIs(obj, Null)
def test_Null(self):
"""Test Null object."""
self.assertNull(Null)
... |
13550b0324c7fbfa53694e0b14ec0c615818183f | yangzongwu/leetcode | /archives/leetcode2/0445. Add Two Numbers II.py | 614 | 3.734375 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
a=0
while l1:... |
ea6257664593a399b533965118bda14162a6025f | Valeriy73/Douson | /douson_gl6_3.py | 1,496 | 4.125 | 4 | # Доступ отовсюду
# Демонстрирует работу с глобальными переменными
def read_global():
print("В области видимости функции read_global значение value равно", value)
def shadow_global():
value = -10
print("В области видимости функции shadow_global значение value равно", value)
def change_global():
global value
valu... |
3460deb0c5618d2e6dc9ce992117e25e6375d52c | PanMaster13/Python-Programming | /Week 4/Practice Files/Week 4, Practice 6.py | 1,841 | 4.09375 | 4 | x = int(input("Input birthday:"))
y = input("Input month of birth (e.g. March, July etc):")
if (y == "January" and (x >= 20 and x <= 31)) or (y == "February" and (x >= 1 and x <= 18)):
print("Your Astrological sign is : Aquarius")
elif (y == "February" and (x >= 19 and x <= 29)) or (y == "March" and (x >= 1 and x... |
2191caf07fefebe7287a4ce1493598374fdc8fcb | frankskol/programmingChallenges | /ButtonClicker.py | 678 | 3.53125 | 4 | from tkinter import *
class Application(Frame):
"""A GUI application for Fahrenheit and Celsius Conversion"""
def __init__(self, master):
#Initializes Frame
Frame.__init__(self, master)
self.grid()
self.button_clicks = 0
self.create_widgets()
def create_widgets(self):
#Creates the buttons
self.button ... |
c577291a8c8658def33fbefef826d95262c811cb | avivalipkowitz/OOP_lesson | /game.py | 11,950 | 3.5625 | 4 | import core
import pyglet
from pyglet.window import key
from core import GameElement
import sys
username = raw_input("To choose a player type 'Aviva' or 'Katie': ")
if username == "Aviva":
princess = "Katie"
else:
princess = "Aviva"
in_game = True
users_message = []
#### DO NOT TOUCH ####
GAME_BOARD = None... |
ec2fa6cb6ab3c296efb5faa0cb96d81568b56154 | tzabcd/py-study | /python-new-journey/py_28.py | 576 | 3.765625 | 4 | # 解析/构建 XML文档
# from xml.etree.ElementTree import parse
# f = open('demo.xml')
# et = parse(f)
# root = et.getroot()
# for child in root:
# print(child.get('item'))
# list(root.iter())
# ....
from xml.etree.ElementTree import Element, ElementTree
from xml.etree.ElementTree import tostring
e = Element('Data... |
06caa3ddb87eadd5d6d89b178294ae43c058df57 | betty29/code-1 | /recipes/Python/269709_Some_python_style_switches/recipe-269709.py | 1,901 | 3.6875 | 4 | #==================================================
# 1. Select non-function values:
#==================================================
location = 'myHome'
fileLocation = {'myHome' :path1,
'myOffice' :path2,
'somewhere':path3}[location]
#=========================================... |
fc6dd12ae34fdd8108916955f737cbfc8ba585fc | moderndragon/garnrechner | /wlc.py | 528 | 3.921875 | 4 | #/usr/bin/python
# -*- coding: utf-8 -*-
#This little tool calculates the length of the warp needed for a given length of woven ribbon.
unit = raw_input("Please specify if you want to use inches or centimeters.\nUse 'in' for inches or 'cm' for cm:")
lr = int(raw_input("Please specify the desired length of the finishe... |
f6b6a8902fd6415fd39721dbbec804c4e626cded | Beomsudev/Git | /DAY01/P1/numberTest.py | 977 | 3.859375 | 4 | # numberTest.py
a = 14
b = 5
sum = a + b
sub = a - b
multiply = a * b
divide = a / b
divide2 = int(a // b) # 이 부분 이해 못함 !
remainder = a % b
power = 2 ** 10
print("덧셈 : %d" %(sum))
print("뺄셈 : %d" %(sub))
print("곱셈 : %d" %(multiply))
print("나눗셈 : %f" %(divide))
print("나눗셈2 : %d" %(divide2))
print("나머지 : %f" %(remaind... |
fb060382ca4a499a3b27433ade50f63d74e37300 | ndtands/Algorithm_and_data_structer | /Practice_2/sort.py | 3,627 | 4.09375 | 4 | """
Bubble sort
for i from 0 to n-2
for j from 0 t0 n-2-i:
if a[j]>a[j+1]:
swap(a[j],a[j+1])
O(n^2)
"""
arr=[1,2,3,-12,4,-12,3,-2,0]
def Bubble_Sort(arr):
n = len(arr)
for i in range(n-1):
for j in range(n-1-i):
if arr[j]>arr[j+1]:
arr... |
614a738b50ed1b6af795099b88717b60ee8e6693 | Evilzlegend/Structured-Programming-Logic | /Chapter 01 - An Overview of Computers and Programming/Mindtap Assignments/Executing a Python Program.py | 514 | 4.21875 | 4 | # SUMMARY
# In this lab, you will execute a prewritten Python program.
# INSTRUCTIONS
# 1. Execute the program. There should be no syntax errors. Note the output of this program.
# 2. Modify the program so it displays "I'm learning how to program in Python.". Execute the program.
# 3. Modify the Python program s... |
0f5a7d19b1a9dbb1dc326dffa70506881b272aa4 | reihanehsr/PythonCourse | /Dec3.py | 391 | 3.921875 | 4 | """
This is the multiline comments
"""
# This is singleline comment
print("Hello")
def FirstFunction():
print("Hello Again")
FirstFunction()
def ReturnSomething(parameter):
print(parameter)
return parameter
print(ReturnSomething(3))
def add(a,b):
return a+b
print(add(2,4))
def sub(c,d):
print... |
c70046996a50e3a6433eb8e2ec188eed97da4d48 | harjunpnik/Data-Processing | /Games/Mindreader.py | 798 | 4.15625 | 4 | import sys
import random
def logic(guess,number):
""" This function takes in two numbers and compares the guess to the number and returns a string based on if the guess is
Correct, Lower or Higher
"""
if(guess == number):
return("Correct")
elif(guess > number):
return("Lower")
e... |
648f6ed098d22aabb83f2c8858c763e93b2e4bac | ankushngpl2311/decision-tree | /tree.py | 947 | 3.859375 | 4 | from collections import deque
class node:
def __init__(self):
self.children ={} # {low:pointer to low,high:pointer to high}
def insert(self,name,positive,negative):
self.name= name
self.positive=positive
self.negative=negative
# def insert(self,obj):
# self.children.append(obj)
# def preorderTr... |
bd97d376caa00070e6c60e838bb7d2e0ace9cd7e | viktor1298-dev/WorldOfGames | /Utils.py | 983 | 3.71875 | 4 | SCORES_FILE_NAME = "scores.txt"
BAD_RETURN_CODE = "404"
def screen_cleaner():
import os
os.system('cls||clear')
def number_validation(number_list):
if len(number_list) == 3:
pre_number = 0
while not number_list[1] <= pre_number <= number_list[2]:
try:
pre_numb... |
cf43bbd517df3ed8d1169b58270dbf599f9a7346 | Halfoon/BUAA-OJ-Project | /python/1180 简单密码.py | 136 | 3.5 | 4 | word = int(input())
a = int(input())
b = int(input())
c = int(input())
d = int(input())
print("The cyphertext is %d."%((word*a-b)*c+d))
|
66a18b50bb0fbc664a7ac34e65f1c9fdb18c16ac | sumit88/PythonLearning | /PrimeOrNot.py | 318 | 3.90625 | 4 | num = int(input())
for c in range(num):
curr = int(input())
isPrime = True
i = 2
while i * i <= curr:
if curr % i == 0:
isPrime = False
break
i += 1
if isPrime and curr != 1:
print('Prime')
else:
print('Not prime')
isPrime = True
|
5a96227c28902897521cce3fc4f88232f72ee859 | monas1975/Udemy_Python_podstawy | /Udemy_podstawy/8_116_Modul_Math_LAB.py | 1,774 | 3.546875 | 4 | import math
if __name__ == '__main__':
#1. Zaimportuj moduł math
#2 2. Oto wzory pozwalające na wykonanie konwersji stopni na radiany i radianów na stopnie:
#1° = (π * rad)/180
#1 rad = 180°/π
#3. Zadeklaruj zmienną degree i przypisz jej wartość 360.
# Wylicz i wyświetl ile wynosi wartość radianów dla 360 stopni
... |
30a07b1e4e672119cf0a80c32c1016fe13f192f9 | RianMarlon/Python-Geek-University | /secao6_estrutura_repeticao/exercicios/questao45.py | 1,126 | 4.46875 | 4 | """
45) Faça um algoritmo que converta uma velocidade expressa em km/h
para m/s e vice versa. Você deve criar um menu com as duas opções de
conversão e com uma opção para finalizar o programa. O usuário poderá
fazer quantas conversões desejar, sendo que o programa só será finalizado quando
a opção de finalizar for esco... |
edc3e5d94f23305a50f33bd7ea8d9aaba063fca7 | imdsoho/python | /class_function/mro_test.py | 1,882 | 3.78125 | 4 |
class Base(object):
def __init__(self):
print('<Base>')
#super(Base, self).__init__()
super().__init__()
print('</Base>')
class A(Base):
def __init__(self):
print('<A>')
#super(A, self).__init__() # python 2.7
super().__init__() ... |
d089f7a1d0e734bea0fb0b5da024c2a37b450b05 | italovarzone/Curso_Python_Guanabara | /ex037.py | 784 | 4.28125 | 4 | inteiro = int(input("Digite um número inteiro: "))
print("""Escolha uma das opções:
=======================================
[1] Converter o número para BINÁRIO
[2] Converter o número para OCTAL
[3] Converter o número para HEXADECIMAL
=======================================""")
esc = int(input("Sua escolha: "))
if esc... |
4f0eebd888849629419b7e1e5fa18037b3579209 | MichalBogoryja/Python_bootcamp | /Modul_03/task_3_1_2.py | 229 | 3.703125 | 4 | limit = 100
divisible = []
cube = []
for num in range(limit+1):
if num % 5 == 0:
divisible.append(num)
cube.append(num**3)
result = f"""Podzielne przez 5: {divisible}
Ich 3 potęgi: {cube}
"""
print(result) |
7abf69fd28ac978a6301cba69e6d1a8246bee2e6 | netnavi20x5/PythonCodes | /Tello Drone/keytest.py | 592 | 3.515625 | 4 | import msvcrt
from msvcrt import getch
# ...
while True:
key = ord(getch())
print(key)
print(chr(key))
#char = msvcrt.getche()
#print(msvcrt.getch().decode(ascii))
#char = msvcrt.getch()
# or, to display it on the screen
#from msvcrt import getch
#while True:
# key = ord(getch())
# if key == 27: #ESC
#... |
3bb978b2a6d2112feff99cb462304bee00610fb2 | yinyinyin123/algorithm | /数组/findPeakElement.py | 400 | 3.546875 | 4 |
### one code one day
### 2020/03/05
### leetcode 162 寻找峰值
### 二分法 牛皮 无敌
### 仔细分析为何可以二分,深入理解二分
def findPeakElement(self, nums: List[int]) -> int:
l, r = 0, len(nums)-1
while(l < r):
mid = int((l+r)/2)
if(nums[mid] > nums[mid+1]):
r = mid
else:
l = mid + 1
ret... |
285869a6c0ca362c7cbfb302b42e6bad3e668d79 | thomashigdon/blackjack-trainer | /bj_count.py | 1,756 | 3.578125 | 4 | #!/usr/bin/python
import card_set
import random
import time
import sys
plus_one = [ '2', '3', '4', '5', '6' ]
minus_one = [ '10', 'J', 'Q', 'K', 'A' ]
class Trainer(object):
def __init__(self, secs_to_wait, stop_percentage):
self.deck = card_set.Deck(6)
self.count = 0
self.secs_to_wait ... |
2c62aa2fb2a99f8d8e9d6e191a96c7783b057b27 | chuncaohenli/leetcode | /Python/lc121.py | 472 | 3.53125 | 4 | # scan the array for once, and record the minimum price and maximum profit for each element
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if prices == []:
return 0
min_price = prices[0]
p... |
6d195bb3cea67801be370f621fcb658678340751 | sietzemm/Codecloud | /CalculateDistanceCoordinates/calc_distance.py | 1,808 | 4.25 | 4 | # Date of creation : 13-10-2018
# Author : Sietze Min
# Small exercise : Write a function that takes two points and calculates the distance between them.
c1 = (1,2) # coordinate 1
c2 = (-1,1) # coordinate 2
import math
import sys
print(sys.version)
# arguments need to be of type tuple
def calc_distance(c1,c2):
... |
1d9b96c6e134b05a348e71a8bd1398ded45bdddd | zembrzuski/think-bayes | /chapter01.py | 2,411 | 3.875 | 4 |
"""
bayes's theorem
p(A and B) = p(B and A)
p(A and B) = p(A) * p(B|A)
p(B and A) = p(B) * p(A|B)
p(A) * p(B|A) = p(B) * p(A|B)
p(B|A) = p(B) * p(A|B)
-------------
p(A)
mas gostamos de usar outras letras, entao
posteriori priori likelihood
p(H|D) = p(H) * p(D|H)
--... |
28f596e27af04a2f169c503da854a79b8c2fe731 | jan-2018-py1/douglas | /Python/listscompare.py | 528 | 4.09375 | 4 | list1 =['red','blue','green','yellow'] # set list 1
list2 =['red','blue','green','yellow'] # set list 2
list3 = set(list1) & set(list2) # compare list1 vs list2 creates a set of matches
x=len(list1) #length of each list
y=len(list2)
z=len(list3)
if x!=y:
print "lists don't match" # if list 1 doesn't equa... |
462726970f110be433c3152286bf2d08c0f5791a | ilmoi/ATBS | /12_practice.py | 3,780 | 3.71875 | 4 | # Practice Questions
# 1. Briefly describe the differences between the webbrowser, requests, bs4, and selenium modules.
# webbrowser - opens websites, requests - gets data from websites, bs4 - scrapes websites to find specific data, selenium - lets you simulate a user using a browser (for testing or else!)
# 2. What ty... |
294531126bcf7fe82426370826776db1e53fef0b | Mahleat17/Module-4-Lab-Activity | /M4P5.py | 1,082 | 4.375 | 4 | # Calculating Grades (ok, let me think about this one)
# Write a program that will average 3 numeric exam grades, return an average test score, a corresponding letter grade, and a message stating whether the student is passing.
# Average Grade
# 90+ A
# 80-89 B
# 70-79 C
# 60-69 D
# 0-5... |
30f02fcf403ac6fc3a4723e9da536c2b04eee59c | johnsonlarryl/data_analyst_nano_degree | /project_1_explore_weather_trends/explore_weather_trends.py | 5,225 | 3.671875 | 4 | import argparse
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from typing import Tuple
def get_absolute_values(global_years: pd.Series, local_years: pd.Series) -> Tuple[int, int]:
"""
Returns the absolute minimum and maximum values for years between the two vectors
Parameters:
... |
a584eb378ce69810347e90392649596e66455854 | JingGY/Introduction_to_Software_Fundamentals | /LAB assessment/lab6 Sorting and Searching.py | 5,787 | 3.921875 | 4 |
#2
''' not efficent
def bubble_row(data, index):
i = 0
while i < index:
if data[i] > data[i+1]:
new_larger=data[i]
new_smaller=data[i+1]
data[i+1] = new_larger
data[i] = new_smaller
i += 1
else:
i += 1
re... |
b780fb649c65dec4953dd862634ccc7fd59d51c9 | yeomko22/TIL | /algorithm/programmers/greedy/kruskal.py | 646 | 3.609375 | 4 | def find(cycle_table, x):
if cycle_table[x] == x:
return x
return find(cycle_table, cycle_table[x])
def union(cycle_table, x, y):
x = find(cycle_table, x)
y = find(cycle_table, y)
if x < y:
cycle_table[y] = x
else:
cycle_table[x] = y
def solution(n, costs):
... |
af93e702da8ac6329ab9059d03d056d975142775 | munishstudy73/pythonstudy | /sourcecode/apress_bundle/python3.0/things.py | 1,245 | 4.09375 | 4 | #! /usr/bin/python3.0
class Thing:
def __init__(self, price, strength, speed):
self.price = price
self.strength = strength
self.speed = speed
def __str__(self):
stats = """\tPrice\tStr\tSpeed
{price!s}\t{strength!s}\t{speed!s}\t""".format(**vars(self))
return stats
def __repr__(self):
stats = 'Thin... |
97be7d29dcb7ec5b7aade3a909dce434fd7e6648 | tomjjoy/MTA-extraction | /retrieve-MTA-turnstile-data-files.py | 1,881 | 3.765625 | 4 | '''
This script retrieves the list of all available turnstile data files
from the New York MTA web site, and saves the files to a local folder.
The page where the files are listed is http://web.mta.info/developers/turnstile.html
The file names from the page do not include the first two digits for
the year, the mis... |
4f6c8cd536cf6910dd4f79e7e4acf0dce7b65230 | DawnBee/01-Learning-Python-PY-Basics | /OOP Projects & Exercises/Exercise-3.py | 461 | 4.15625 | 4 | # OOP Exercise 3: Create a child class Bus that will inherit all of the variables and methods of the Vehicle class
class Vehicle:
def __init__(self,name,max_speed,mileage):
self.name = name
self.max_speed = max_speed
self.mileage = mileage
def vehicle_info(self):
return f"Vehicle Name: {self.name} Speed: {s... |
e6a3002c1e67f0a021e0d8dce96b513fb8c48f77 | chenzhiyuan0713/Leetcode | /Easy/Q47.py | 749 | 3.625 | 4 | """
1748. 唯一元素的和
给你一个整数数组 nums 。数组中唯一元素是那些只出现 恰好一次 的元素。
请你返回 nums 中唯一元素的 和 。
示例 1:
输入:nums = [1,2,3,2]
输出:4
解释:唯一元素为 [1,3] ,和为 4 。
示例 2:
输入:nums = [1,1,1,1,1]
输出:0
解释:没有唯一元素,和为 0 。
示例 3 :
输入:nums = [1,2,3,4,5]
输出:15
解释:唯一元素为 [1,2,3,4,5] ,和为 15 。
"""
class Solution:
def sumOfUnique(self, nums: list) -> int... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.