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 |
|---|---|---|---|---|---|---|
61abdd031ce217b7e28d1a411885e14c23a5b99a | ellismckenzielee/codewars-python | /points.py | 335 | 3.90625 | 4 | def points(games):
'''Count the number of points achieved in a season based on individual game scores'''
points = 0
for game in games:
result = int(game[0]) - int(game[2])
if result > 0:
points = points + 3
elif result == 0:
points = points + 1
... |
c7f3fd86436c9e77b6457e4420b727939a48c7b7 | MaximeDouylliez/DUT-Info | /python/bissextuel.py | 893 | 3.796875 | 4 | #!/usr/bin/python3.2
"""
val=input()
if int(val)% 4 == 0 and int(val)% 100 == 0 and int(val)% 400 == 0 :
print("Cette annee est bissextuelle")
elif int(val)% 4 == 0 and int(val)% 100 != 0:
print("Cette annee est bissextuelle")
else:
print("Cette annee n'est pas si bissextuelle que ca")
"""
"""
caca0=[... |
f6c9a5bba7f055c894e3e18a7ac14b6aea26e155 | DroidFreak32/PythonLab | /p32.py | 520 | 3.59375 | 4 | #!/usr/bin/python3
# p31.py
# Write a CGI script to demonstrate the concept of radio button.
import cgi, cgitb
form = cgi.FieldStorage()
if form.getvalue('subject'):
subject = form.getvalue('subject')
else:
subject = "Not set"
print ("Content-type:text/html")
print()
print ("<html>")
print ("<head>")
print ("<title... |
7267014e6eaeb1b106c1c0a67da3bf2dd848d71d | snehalbarge/Globant_test | /exercise_1.py | 3,076 | 3.75 | 4 | import unittest
class Person():
counter = 0
def __init__(self, name, lastname, address, age=None):
Person.counter += 1
self.__name = name
self.__lastname = lastname
self.age = age
self.address = address
def get_name(self):
return self.__name
def get_l... |
d13c006f41ecbe66b5b7ccaee83dbab9d9d193a3 | foolishkylin/high_revolution | /convert.py | 7,539 | 3.59375 | 4 | # -*- coding: UTF-8 -*-
import math
import cv2
from gdalconst import *
from osgeo import gdal
import platform
def getSeparator():
"""
Get the separator for different systems.
:return: String,the separator.e.g. "/" on linux.
"""
sysstr = platform.system()
if (sysstr == "Windows"):
sepa... |
73ed3c5c08e49fe9af4fa0a6a77104f50e9d6ba7 | pjcarr/Winter_2021_Data_Science_Intern_Challenge | /shoe_sales_analysis.py | 1,781 | 4.09375 | 4 | """
shoe_sales_analysis.py
Reads in .xlsx file containing shoe sales data. Calculates the cost per shoe from
the order total divided by the number of items. Extracts sales data within the
95th percentile, then determines the average order value by taking the mean
order amount.
"""
import pandas as pd
import n... |
04b3a9e95e7b23b1e6c8752cbbd05105b7e32c50 | yanshengjia/algorithm | /leetcode/Stack/20. Valid Parentheses.py | 2,160 | 4.15625 | 4 | """
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Exa... |
5e44fcce896a18e1a83aec8e87105f4b2df004c4 | hebertomoreno/PythonScr | /hurdles.py | 310 | 3.515625 | 4 | n,h = input().split(" ")
n = int(n)
h = int(h)
def intifyList(listToInt):
intedList = listToInt.split()
intedList = list(map(int,intedList))
return intedList
hurdles = intifyList(input())
potions = 0
for hurdle in hurdles:
if(hurdle > h):
potions += hurdle - h
h = h + (hurdle-h)
print(potions)
|
f954c45b5698d8de3d9a3d0c233fc33339e5b794 | JyotiRSharma/Master-the-Coding-Interview--Data-Structures---Algorithms | /Algorithms/DynamicProgramming/memoization.py | 625 | 3.6875 | 4 | # learn to cache
from functools import lru_cache
def addTo80(n):
return n + 80
addTo80(5)
cache = {}
def memoizeAddTo80(n):
if n in cache:
return cache[n]
else:
print('long time')
answer = n + 80
cache[n] = answer
return answer
print(memoizeAddTo80(6))
print(... |
e3b49c7337cd0a01c6005aa7ba245e677dd98b49 | Dantide/Filing-Cabinet | /Other/Python/Text_based_adventure.py | 648 | 4.15625 | 4 | """This will be my sandbox for creating a text adventure game.
Not exactly sure how to do it, but we will start with something anyway."""
class Room():
def __init__(self, name):
self.name = name
roomlist = {
1 : Room("LivingRoom"),
2 : Room("Kitchen"),
3 : Room("Bedroom"),
4 : Room("Bathroom")
}
def starting_... |
7f3e01413bb035d853c344070f0f96c2e3eef1fa | louisprimeau/esclabs | /newterm/lab1/test.py | 549 | 3.5625 | 4 | from tree import *
from binary_tree import *
a = tree('A')
b = tree('B')
c = tree('C')
d = tree('D')
e = tree('E')
f = tree('F')
g = tree('G')
h = tree('H')
i = tree('I')
j = tree('J')
k = tree('K')
a.AddSuccessor(b)
a.AddSuccessor(c)
a.AddSuccessor(d)
b.AddSuccessor(e)
b.AddSuccessor(f)
b.AddSuccessor(g)
c.AddSucc... |
99225e22d305b5c9e2eb8152f19220e05bc35348 | ganlanshu/leetcode | /majority-element.py | 3,514 | 3.5625 | 4 | # coding=utf-8
"""
169. Majority Element
"""
import random
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return
hash_map = {}
size = len(nums)
for i in nums:
if... |
5b149add69649e1fea7a459feff546b6eaf8a6fe | mmelton09/tdtest1 | /example.py | 1,570 | 4.4375 | 4 |
# Printing a table Mike...
def printTable( aList ):
firstEntry = aList[ 0 ];
headers = []
line = ''
for key in firstEntry.keys():
line += key + '\t'
headers.append( key )
print line
for entry in aList:
line = ''
for header in headers:
line += entry[ header ] + '\t\t'
print line
# Basic lists
... |
6e4f678603d1aab6446ddd010d1007f6b70d917c | vinothini92/Sampleprogram | /ex1.py | 347 | 4.28125 | 4 | #program to find largest of three numbers
print "this is my very first program in python"
print "enter first number "
x = raw_input()
print "enter second number"
y = raw_input()
print "enter third number"
z = raw_input()
if (x > y and x > z) :
print " x is greater"
elif (y > x and y > z) :
print "y is greater "
else ... |
6dbd5540375c95dfd74f52de7bfcf1ec9278bf33 | barbagroup/petibm-examples | /examples/decoupledibpm/flapping2dRe75/run/scripts/create_body.py | 1,742 | 3.984375 | 4 | """Create an ellipse."""
import numpy
import pathlib
import petibmpy
def ellipse(a, b, center=(0.0, 0.0), num=50):
"""Return the coordinates of an ellipse.
Parameters
----------
a : float
The semi-major axis of the ellipse.
b : float
The semi-minor axis of the ellipse.
cente... |
0074bdeab5d464beceba78a3e354de63a7e4b46d | ulink-college/code-dump | /Riddle_Task/riddle_4.py | 318 | 3.84375 | 4 | # Add repetition to this code....
riddle = "What has 4 eyes but cannot see? "
answer = "Mississippi"
userAnswer = ""
attempt = 0
userAnswer = input(riddle)
attempt = attempt + 1
if userAnswer == answer:
print("Well done!")
else:
print("Sorry, that's not it.")
print("You have had", attempt, "attempts.")
|
53d25a320ee73629836b6ff7855256cecfc45a1c | sejin8642/LearnPython | /keywords/args-kwarg-01.py | 1,122 | 4.40625 | 4 | # this script surveys concept of *args
def mulArgs(arg1, arg2, arg3):
return arg1, arg2, arg3
def varArgs(*args):
return args
def varKwargs(**kwargs):
return kwargs
n1, n2, n3 = mulArgs(1, 2, 3)
nums = mulArgs(1, 2, 3)
print(type(n1))
print(type(nums))
print('')
tupleN = varArgs(1, 2, 3, 4) # this will... |
670ce63a59a5cb63226b09e6de34ca27f39103f6 | jorgesmu/algorithm_exercises | /arrays/median.py | 1,098 | 3.65625 | 4 | # Taken from: https://www.youtube.com/watch?v=HGgdcKbC5ro&list=PLNmW52ef0uwsjnM06LweaYEZr-wjPKBnj&index=53&t=1727s
import math
def median_helper(a1, s1, e1, a2, s2, e2):
if e1 - s1 == 1:
lower = min(a1[s1], a2[s2])
upper = max(a1[e1], a2[e2])
return (lower+upper)/2
import pdb; pdb.set_trace()
middle_element_a... |
82e0034d9e75d973ef34300c64ce26f4a7cb1774 | sunshot/LeetCode | /209. Minimum Size Subarray Sum/solution1.py | 754 | 3.5 | 4 | from typing import List
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
left = right = 0
result = float("inf")
curr = 0
while right < len(nums):
curr += nums[right]
while left <= right and curr >= target:
... |
37340104afbcba267654f150775d13cd0fcf3528 | thBoo39/QuantumTransmissionCoefficientCalculator | /TransmissionCoefficientCalculator.py | 6,930 | 3.625 | 4 | """QuantumTransmissionCoefficientCalculator
:platform: Python 3.9
This python code is to calculate quantum tunneling transmission coefficient
using piece wise constant method.
To use, first specify a barrier structure in myStructure.py
myStructure.py will be imported as below
Then, create an object, call compute met... |
b2f15d01d625a75b7ab970779f14de4f4f7c0563 | robertnowell/161 | /lis.py | 1,044 | 3.71875 | 4 | def increasingSubsequence(A):
D = [ [] for i in range(len(A)) ]
longestOverallSubsequence = []
for i in range(len(A)):
import pdb; pdb.set_trace()
longestEarlierSubsequence = []
for k in range(i):
if len(D[k]) > len(longestEarlierSubsequence) and A[k] < A[i]:
... |
1b25da9b3e06e9ba76a8d9d0a056faf636c21537 | PawarKishori/Alignment1 | /Transliteration/Acronym_Dict.py | 2,083 | 3.640625 | 4 |
# coding: utf-8
# In[49]:
def remove_punct_from_word(word):
#print(word, word.strip(string.punctuation))
return(word.strip(string.punctuation))
def extract_only_words_from_sent(sent_file):
with open(sent_file, 'r') as f:
sent = " ".join(f.read().split()).strip("\n") #If sent contains extra spac... |
d97954b1ab133106d0ce1e029da64966abe2882e | Chandra-mouli-kante/Python-100-Days-Coding | /prime.py | 1,098 | 4.125 | 4 | '''
n=int(input("enter the value of n:"))
count=0
for i in range(1,n+1):
if(n%i==0):
count+=1
if count==2:
print(n,"is prime number")
else:
print(n,"is not a prime number")
'''
'''
n=int(input("enter the value of n:"))
count=0
for i in range(2,n):
if(n%i==0):
count+=1
... |
157ba700a5801437e88016aebd40a6ca9610857f | BW1ll/PythonCrashCourse | /python_work/Chapter_9/importing_classes_9.10-9.12/user2.py | 1,392 | 4.40625 | 4 |
'''
Python module class for making users
'''
class User:
'''
User Class example
example python Class for a general user in a general system
'''
def __init__(self, first_name, last_name, birthday):
'''initialize attributes to describe any user'''
self.first_name = first_name
... |
c0473c614b452392318a5dded8a0f69f7a130e68 | rperkins001/Alarm_Clock | /Alarm clock.py | 2,685 | 3.578125 | 4 | import datetime
import time
import webbrowser
from builtins import input
def get_hour():
global hour_choice
while True:
hour_choice = input("Please select an hour for the alarm: ")
if not hour_choice.isdigit():
print("Error: You must input a numberic value.")
continue
... |
0c60de0f535fa6880c4729cffc9ea6ba395e26e4 | RoyalGamer594/pgzero-flappy-bird | /flappy_bird.py | 1,619 | 3.671875 | 4 | import random
TITLE = "FLAPPY BIRD"
WIDTH = 395
HEIGHT = 650
bird = Actor("bird1", center=(WIDTH/2-100, HEIGHT/2))
top = Actor("top", anchor=("left","bottom"))
bottom = Actor("bottom", anchor=("left","top"))
bird.above_ground = 0
bird.dead = False
FALL = .6
JUMP = -9
SPEED = 3
GAP = 130
... |
276efbf44360c71a071eb65f05c3a917f8b70a2a | jcebo/pp1 | /02-ControlStructures/12.py | 309 | 3.796875 | 4 | x=int(input("Wprowadz liczbe calkowita x: "))
y=int(input("Wprowadz liczbe calkowita y: "))
if (x<0 and y<0):
print('obie liczby sa ujemne')
elif (x<0 and y>=0):
print('tylko x jest ujemne')
elif (x>=0 and y<0):
print('tylko y jest ujemne')
elif (x>0 and y>0):
print('obie liczby sa dodatnie') |
8d58db1d73bf62234d0100b96b99deabed1c6e7e | vinokayal/Python | /Recursion/5_Fibonaci_recursion.py | 135 | 3.609375 | 4 | def fibonaci_series(n):
if n<=1:
return n
return (fibonaci_series(n-1)+fibonaci_series(n-2))
print(fibonaci_series(7)) |
c5ca3f05b18b376ba5aa1b510ea5563fb40745ba | amitkac/PythonAtom | /OOPS/pythonic.py | 648 | 3.984375 | 4 | import math
import time
class Ring(object):
# class variables--available to all class methods
date = time.strftime("%Y-%m-%d", time.gmtime())
center = 001.020
def __init__(self, date=date, metal='copper', radius=5.0, price=5.0,
quantity=5):
"""init is not a constructor, but ... |
b9870c989c80ed1b7dbdca14f7544b8dea04cc70 | pembemiriam/pembepython | /chapter4/prime.py | 315 | 4.09375 | 4 | def prime(number1):
prime = True
for i in range(2,number1):
if (number1%i==0):
prime = False
if prime:
print "%d is a prime" %(number1)
else:
print "%d is not a prime" %(number1)
number=raw_input("enter a number:")
number=int(number)
prime(number)
|
ebdd856822265eaa8307b95933771807c5fb35e7 | Hodaaa/Test | /Coin.py | 301 | 3.515625 | 4 | class Coin():
Color = 'E'
place = [2]
board = [[0 for x in range(8)] for y in range(8)]
for i in range(8):
for j in range(8):
board[i][j] = Coin()
board[i][j].place = [i , j]
board[4][4].Color = 'B'
board[4][3].Color = 'W'
board[3][4].Color = 'B'
board[3][3].Color = 'W' |
081139e0ca2f48c488a6bbfb07f8369b5e1ae8d6 | Keda87/kulik | /learn-python/data-structure/insertion_sort.py | 371 | 4.0625 | 4 |
def insertion_sort(arr):
for j in range(1, len(arr)):
key = arr[j]
i = j - 1
while i >= 0 and arr[i] > key:
arr[i + 1] = arr[i]
i = i - 1
arr[i + 1] = key
if __name__ == '__main__':
data = [6, 2, 4, 6, 87, 23, 11, 25, 31, 1, 1, 32, 55, 43, 35, 76]
... |
2adb51d5e15eba9673f06da36737d6ec70c91b56 | alisterburt/peepingtom | /peepingtom/utils/validators/pandas.py | 353 | 3.78125 | 4 | import pandas as pd
def columns_in_df(columns: list, df: pd.DataFrame):
"""
Checks that a list of columns are all present in a given DataFrame
Parameters
----------
columns : list of column names to check
df : DataFrame to be checked
Returns bool
-------
"""
return pd.Series(... |
bd9bdc6dce7a8080eb9c2ec7459e36b723d2165b | Kunal352000/python_program | /list3.py | 176 | 3.6875 | 4 | x=[10,20,30,20,10,30,40,10,20,10,30,20]
y=[]
for i in range(len(x)):
if x[i] not in y:
y.append(x[i])
print("before removing=",x)
print("After removing=",y)
|
ba8701fc8d5db74aac05bb6feef8730c7fd11f80 | jerte/ProjectEuler | /PE2/PE2.py | 622 | 3.71875 | 4 | ### Problem 2: Sum of even terms in Fibonacci sequence whose values
### do no exceed four million ###
def iterativeFibunder(under):
fibsum = 0
f1 = 1
f2 = 1
while(f2 < under):
temp = f2
f2 = f1 + f2
f1 = temp
if(f2 % 2 == 0):
fibsum = fibsum + f2
return fibsum
### Answer: 4613732
## Hac... |
9aebcfbb831617ef1520bf4758665a7b80720428 | JiHoon-JK/Algorithm | /inflearn/python/python basic test.py | 13,626 | 3.6875 | 4 | ### 파이썬 기초 문법 ###
'''
## 변수 : 데이터들을 저장하는 공간
==================================
영문과 숫자, _로 이루어진다.
대소문자로 시작한다
특수문자를 사용하면 안된다. ($,% 등)
키워드를 사용하면 안된다. (if, for 등)
==================================
a = 1 # 1을 변수a에 대입한다.
A = 2
A1 = 3
#2b = 4 : 변수명은 숫자로 시작하면 안됨
_b = 4
print(a, A, A1, _b)
a, b, c = 3, 2, 1
print(a,b,c)
... |
bd31b5866d0e44288300354d191ab984d68d5b9c | maxwelnl1/arvore-binaria | /arvore_busca.py | 2,157 | 3.734375 | 4 | import os
class No:
def __init__(self, valor):
self.valor = valor
self.esquerda = None
self.direita = None
def obtervalor(self):
return self.valor
def obteresquerda(self):
return self.esquerda
def obterdireita(self):
return self.direita
def setes... |
c55dac655151110cb5acdabaabaa67021e1acfdd | MagicHatJo/AoC2020 | /18/01.py | 831 | 3.625 | 4 | #!/usr/bin/python3
def shunting_yard(s):
stack = []
ops = ['+', '*']
for c in list(s.replace(' ', '')):
if c.isdigit():
yield c
elif c in ops:
while stack and stack[-1] in ops:
yield stack.pop()
stack.append(c)
elif c == '(':
stack.append(c)
elif c == ')':
while stack and s... |
626590b43d49a5c7c4bd5213aef13851d9c425e9 | Shr1ftyy/matrix_encryption | /mod.py | 3,322 | 3.6875 | 4 | #!C:/Users/Syeam/AppData/Local/Programs/Python/Python37/python.exe
import numpy as np
import math
import sys
# Function for finding the modular inverse of a, given mod m
def modInverse(a, m) :
# Checks if ax mod m = 1, if yes then it returns x since it is the modular inverse
for x in range(1, m) :
... |
fa3898d8c31fce323555e4633a987c28d27bea80 | NealLyonsWake/advancing_python | /coordinateTesting.py | 1,130 | 4.09375 | 4 | """
Assertion Exercise:
Assume a cartesian cordinate space R = R(x,y,z).
Each of the co-ordinates, (x,y,z) can have only integer values >= 0 The maximum value each of the co-odinates can assume,
and the sum of all three co-ordinates (the tuple) is capped at integer N.
Using assertion, verify that a given set of coordin... |
fb78c286df0e69a82d240921c5b776cc4511a5a3 | lixiang2017/leetcode | /problems/0491.0_Non-decreasing_Subsequences.py | 4,019 | 3.640625 | 4 | '''
Runtime: 266 ms, faster than 52.97% of Python3 online submissions for Non-decreasing Subsequences.
Memory Usage: 27.1 MB, less than 5.00% of Python3 online submissions for Non-decreasing Subsequences.
'''
class Solution:
def findSubsequences(self, nums: List[int]) -> List[List[int]]:
ans = []
... |
d9ec5761ec8b3ca60cd837b496d4c00b2ae5d8ef | JGonzalvo/Project-Euler | /7.py | 199 | 3.828125 | 4 | prime=[2,3,5,7,11,13]
ctr=17
while 10000>prime[-1]:
isPrime=True
for x in prime:
if ctr%x==0:
isPrime=False
break
if isPrime:
prime.append(ctr)
ctr+=1
print(prime)
|
514777b6e3cc63765dd58c06bce7129976a6194f | KeithYJohnson/aind | /sudoku/reduce_value.py | 1,259 | 3.5 | 4 | from utils import *
from eliminate import eliminate
from only_choice import only_choice
from grid_values import grid_values
def reduce_puzzle(dict_grid):
stalled = False
while not stalled:
# Check how many boxes have a determined value
solved_values_before = len([box for box in dict_gri... |
7e76fcf87c8d183d4e47eb2271cdbc0706bba7fa | biglala89/algorithms | /Tree/isSameTree.py | 1,102 | 3.921875 | 4 | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def isSameTree(self, p, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
... |
3be5895920de1863f1c2ced85d4f8b4659cf4469 | Devil8899/Python_demo | /Day3/Demo4多次判断.py | 156 | 3.609375 | 4 | score=int(input("输入您的成绩"))
if score >90:
print("A")
elif score>80:
print("B")
elif score>60:
print("C")
else:
print("不及格") |
e654ad75c9e11654f73e68350d62b25104300852 | nickbauman/robotracker | /utils/geolocation.py | 947 | 4.09375 | 4 | from math import radians, cos, sin, asin, sqrt
def haversine_distance(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance (in meters) between two points on the earth specified in decimal degrees,
(lon1, lat1) and (lon2, lat2).
:param lon1: The first longitude value, in decimal degrees.
... |
c6eec9e175e608a397830351ebdb17b06a2d49e4 | Daoudii/INFO-S2 | /TP/TP1/exo5.py | 247 | 3.78125 | 4 | #Parité d'un entier
a=int(input('entrer un nombre : '))
if a%2==0:
print(a,' est paire' )
else:
print(a, 'est impaire')
#if..else est l'equivalente de si..sinon
input() #pour que le programme ne se ferme pas apres l'execution
|
37fd4a3792eff4a2be3c6d3943302294c89fdb0f | SimonStarling/kyh-practice | /Övning51.py | 2,681 | 3.984375 | 4 | # 51.1 Skriv om funktionen add_as_def som lambda, och lagra i en variabel
'''
add_as_lambda = lambda a,b:a+b
print(add_as_lambda(2,4))
'''
# 51.2 Skriv om obj som en funktion "upper"
'''
# Med lambda
obj = lambda s: s.upper()
print(obj("sträng"))
#Som funktion
def obj(s):
s = s.upper()
return s
x = "hej dett... |
96d2fc095ec2fefc574a2ef3ada091f14cb3933d | rksam24/MCA | /Sem 1/DM/Q6.Modus ponens and Modus Tollens.py | 707 | 3.5625 | 4 | #program to implement Modus ponens and Modus Tollens
#taking p and q from user
p=[bool(int(i)) for i in input('Enter the p in 1 0 form: ').split()]
q=[bool(int(i)) for i in input('Enter the q in 1 0 form: ').split()]
#for Modus Ponens
print('\n\t\tModus Ponens\n')
print('\t p\t q\t p implies q\t (p implies q) ^ p')
f... |
192d988c0e0b45c5ba1413f9e216d15c9f520a85 | shantanumane/voice-prescription | /voice-prescription/main.py | 4,149 | 3.5 | 4 | from tkinter import *
import smtplib
import speech_recognition as sr
from gtts import gTTS
import os
import pandas as pd
import xlsxwriter
r=sr.Recognizer()
with sr.Microphone() as source:
speech = gTTS("Tell me your name")
speech.save("hello.mp3")
os.system("start hello.mp3")
print("Tell me your name... |
bf3a0395e1e8726a8a9ba16e9d9c53d0e15d77ec | loongqiao/learn | /python1707A/0722/111111.py | 178 | 3.5 | 4 | u1={"a":"1","b":"2"}
u2=[{"c":"2","q":"sad"},{"c":"2","qwq":"dsa"},{"c":"4","sdada":"sdda"},{"c":"2","adsd":"dasda"}]
for u in u2:
if u1.get("b")==u.get("c"):
print(u)
break |
50819ba759f37d6ce622b62a32e0074e6d6071d9 | DubMircea/gb_python_basis_hw | /lesson_03/exercise_3.py | 357 | 3.546875 | 4 | def thesaurus(*args):
result = {}
for arg in args:
result.setdefault(arg[0], [])
result[arg[0]].append(arg)
result = dict(sorted(result.items()))
return result
input_data = ["Петр", "Иван", "Мария", "Илья"]
print(thesaurus("Петр", "Иван", "Мария", "Илья"))
print(thesaurus(*input_data... |
44b45ba6e4f29d24197a901d2d479ff79437a8e2 | lololobo93/coleccion | /Proyecto_Programacion/Estructuras_Dinamicas.py | 1,226 | 4.0625 | 4 | """
Metodos de Pila y Cola para usar en el codigo principal.
"""
"Definicion de Pila con sus respectivas funciones."
class Pila:
def __init__(self):
self.items = []
def estaVacia(self):
return self.items == []
def incluir(self, item):
self.items.append(item)
def e... |
00032982baf5698ce551553e3884006ee342edc5 | SatyamAnand98/interviewQuestions | /soroco/insertionBinaryTree.py | 1,187 | 3.78125 | 4 | class Node:
def __init__(self, val=None):
self.data = val
self.left = None
self.right = None
def inorder(temp):
if (not temp):
return
inorder(temp.left)
print(temp.data,end = " ")
inorder(temp.right)
def postorder(temp):
if(not temp):
return
postorder(temp.left)
postorder(temp... |
3b8d49270fe5cde1b039d0d2572531252a9ff6e2 | mpmarroquing/Metcomputacionales | /mp.marroquing10_taller1/NumberPrimesLessThan.py | 698 | 3.515625 | 4 | #esta funcion recibe un arreglo de enteros + e imprime un arreglo pix.
import numpy as np
import matplotlib.pyplot as plt
import scipy
import scipy.special
import math
from math import log
x= np.arange(1000)
y=[]
k=[]
primos=[]
no_primos=[]
z=0
def NumberPrimesLessThan(x):
for j in range (0,len(x)):
m=x[j]
for... |
8fc45d8f9394d68727939409175961133eccfdb1 | yuvenus/Thesis | /input/move_gui.py | 2,266 | 3.734375 | 4 | #!/usr/bin/env python
#Version: 10/6/2016
from Tkinter import *
from move_robot import move
master = Tk()
lin = 0
ang = 0
move_type = ""
running = True
count = 0
def scan():
global lin, ang, move_type, running, count
if (move_type != "wiggle"):
if (running and not count > 3000):
move(lin,ang,move_type)
coun... |
c295d35aad154997d9acb8526f6fc8bc99ae2f29 | Ezekielt96/Data-Analysis | /calcStdev.py | 2,339 | 4.21875 | 4 | import random
gradeList = []
for i in range(8) :
floatValue = float(random.sample(range(1,3),1)[0])
floatValue *= .3
scoreList = random.sample(range(0,10),10)
newList = []
for i in scoreList :
newList.append(i * floatValue)
gradeList.append(newList)
print(gradeList)
# Write a program to calculate the avg ... |
4cf26502473db3a7e134e6719bd9e0122769c2ba | taochenlei/leetcode_algorithm | /LinkedLists/876. Middle of the Linked List.py | 770 | 3.96875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def middleNode(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
# Loop once to count the number of nodes
# ... |
94967c796c85cf2489b44bdb4b23ea5fff19d498 | bertacsevercan/Hangman | /hangman.py | 1,545 | 3.828125 | 4 |
import random
import string
word_list = ["python", "java", "kotlin", "javascript"]
print("H A N G M A N\n")
lives = 8
comp_choice = list(random.choice(word_list))
hidden = "-" * len(comp_choice)
hidden_list = list(hidden)
empty = ""
guesses = []
menu = input('Type "play" to play the game, "exit" to quit:')
while li... |
ebf9be3eeedd4c901f8464a62bf58785cb6b4ec1 | samshipengs/AlgoTool | /A1/fibonacci_huge/fibonacci_huge.py | 535 | 3.703125 | 4 | # Uses python3
import sys
def get_fibonaccihuge(n, m):
if m == 1:
return 0
else:
N = m*10
F = [0]*(N+1)
F[0] = 0
F[1] = 1
F_mod = [0]*(N+1)
F_mod[0] = 0
F_mod[1] = 1
for i in range(2,N+1):
F[i] = F[i-1] + F[i-2]
F_mod[i] = F[i] % m
rep = int(i/2)+1
if F_mod[:rep] == F_mod[rep:i+1]:
... |
800ce521ba597bc35229a3db933f1c57b8233eba | taeheechoi/data-structures-algorithms | /average_words_length.py | 438 | 3.828125 | 4 | sentence1 = "Hi all, my name is Tom...I am originally from Australia."
sentence2="I need to work very hard to learn more about algorithms in Python!"
def solution(sentence):
clean_sentence = sentence.replace(",", "").replace(".", "").replace("!", "").split()
print(clean_sentence)
return round(sum([len(sen... |
d126de7f8e9d70b0f8a6510b51687929fb3a38ed | billforthewynn/PythonProjects | /46exercises/reverse.py | 396 | 4.5625 | 5 | # Define a function reverse() that computes the reversal of a string.
# For example, reverse("I am testing") should return the string "gnitset ma I".
def reverse(string):
target_string = ''
location = len(string) - 1
while location >= 0:
target_string = target_string + string[location]
location = location - 1
... |
c4b3a038ba2be60a1e407b938ae95cdcfb699b62 | johannah/interview_practice | /sort/quicksort.py | 1,145 | 4.0625 | 4 | # O(n log n) - low memory requirement. prefer for contiguous arrays, but choose mergesort for linked list
# 1) pick XX element as pivot
# 2) partition the array around the picked pivot
# def partition() given an array and an element x of array as pivot - put x at its correct position in sorted array and put all smal... |
41bfd7faa4e4339b8a50a2999b7cb4d1acc4a483 | frankieliu/problems | /leetcode/python/535/sol.py | 1,923 | 4.15625 | 4 |
Python 3 solution beats 94% speed, 78% space
https://leetcode.com/problems/encode-and-decode-tinyurl/discuss/256180
* Lang: python3
* Author: csush
* Votes: 0
Thoughts: This code is not very scalable, but it works well within the scope of this problem ;). It generates a random 6 character string and checks if... |
c9838b492a7d3b8d2428c216bb0577fc072bcc68 | florian-corby/Pylearn | /hangman/word_manipulations.py | 1,027 | 4.0625 | 4 | #!/usr/bin/env python3
def create_hidden_word(word):
hidden_word = ""
for i in range(0, len(str(word)) - 1):
hidden_word = hidden_word + "*"
return hidden_word
def search_letter(user_letter, hidden_word):
pos_list = []
hidden_word_end = len(hidden_word)
i = 0
while i < hidde... |
d4b4a7afb357c28a337d31d0676287735fce2539 | xuegao-tzx/PTA | /python-p/7.24.py | 273 | 3.625 | 4 | ##7-24 约分最简分式
'''
2021.10.12
19.24.24
By Xcl
'''
a,b=map(int, input().split('/'))
i=b
if(a!=b):
while i>2:
i=i-1
if((a%i==0) and (b%i==0)):
a=a/i
b=b/i
else:
a=1
b=1
a=int(a)
b=int(b)
print(f'{a}/{b}',end="") |
abb7c4f20ab71e6905b25f7d3f5498f41abd1978 | bhushangy/5th-Sem-Scripting-Languages-Lab | /Part A/python/cl1.py | 716 | 3.96875 | 4 | class Person: #interpretation starts from line 1 in py programs
gender=''
def __init__(self,name,age,gender): #self used to as object reference to determine which object is calling the..
self.name = name #..constructor
self.age =... |
d85e8907f41dfd93a820eb472b599b7c7ff90310 | aaryan-sarawgi1/blood-transfusion | /blood_transfusion.py | 6,904 | 3.859375 | 4 | from tkinter import *
import sqlite3
db=sqlite3.connect("test.db")
cursor=db.cursor()
print("Successfully Connected to SQLite")
cursor.execute("""CREATE TABLE if not exists donor(
name text,
age integer,
gender text,
address text,
contactno integer,
bloodgroup text,
platelet integer,
rbc integer,
dates varchar... |
fd819055d40ba3a7e7827a6d9b46cac97cdf6e52 | thefresia/boreutils | /util/ccomex.py | 791 | 3.84375 | 4 | #!/usr/bin/env python3
from pathlib import Path
import sys
def extract(filename):
text = ""
lines = Path(filename).read_text().splitlines()
capture = False
for line in lines:
if line.strip() == '/**':
capture = True
continue
if line.strip() == '*/':
... |
256ee5c824d2682e341993a7121ecee2e49655a0 | pydi0415/git_zeroo | /python/assignment/operators.ASGM.py | 1,795 | 3.703125 | 4 | #a="sathya"
#b="tech"
#c=a+b
#print("Full name=",c)
#print(b)
#a=2
#b=5
#c=(a,b)
#print(c)
#x=5
#y=2
#z=(x%y)
#print(z)
#x=2
#s=x*x
#c=x*s
#print(s)
#print(c)
#x=5
#y=3
#z=x*y
#sum=x+y+z
#print(z)
#print("sum",sum)
#p=1000
#r000000=15
#t=5
#s=p*r*t/100
#print(s)
#if(1):
# print("hello")
#print('thank you')
x=3
if(x>... |
edba542160d9b2c8e02e4415e0dd536ae8030550 | Bmcentee148/PythonTheHardWay | /ex21.py | 935 | 4.125 | 4 | def add(val_1, val_2) :
print "Adding %r and %r" % (val_1, val_2)
return val_1 + val_2
def subtract(val_1, val_2) :
print "Subtracting %r from %r" % (val_2, val_1)
return val_1 - val_2
def multiply(val_1, val_2) :
print "Multiplying %r and %r together." % (val_1, val_2)
return val_1 * val_2
def divide(val_1, v... |
3a35a2a7306e4a6754877096a5f08a83a5a38af7 | davidobrien1/Programming-and-Scripting-Exercises | /euler1.py | 452 | 4.0625 | 4 | # David O'Brien, 2018-02-20
# Project Euler Prolem 1
# https://projecteuler.net/problem=1
# 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.
sum = 0
i = 1
while i < 1000:
if ... |
d4056e43c652ced70e23a323c23b795f15f01aee | Slavkata/HackTuesX30 | /BoardGame/board_game/game_state.py | 896 | 3.5 | 4 | from board_game.player import Player
import json
class GameState(object):
def __init__(self, players_count, player_turn, question):
self.players_count = players_count
self.player_turn = player_turn
self.question = question
self.type = 'game_state'
self.colors = ["purple", "b... |
e90b41e0d165721685927b243bfeb763753833b5 | NguyenVanDuc2022/Self-study | /101 Tasks/Task 048.py | 325 | 4.21875 | 4 | """
Question 048 - Level 02
Write a program which can map() to make a list whose elements are square of numbers between 1 and 20 (both included).
Hints:
Use map() to generate a list.
Use lambda to define anonymous functions.
--- Nguyen Van Duc ---
"""
squaredNumbers = list(map(lambda x: x ** 2, range(1, 21)))
print(squ... |
ed361dfc9cad554b1dd9bbbeb3fc8aa736cddb6a | aidansmyth95/AlgoExpertSolutions | /Binary Trees/Branch Sums/Solution1.py | 996 | 3.875 | 4 | # This is the class of the input root. Do not edit it.
class BinaryTree:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def isLeaf(node):
return node.right == None and node.left == None
# O(n) time | O(n) space - we need to visit all the branches
# this t... |
c5d9d36dd4fe4e5ef037718f301f89bb6942ade8 | Bradford-Chen/-python | /01-range.py | 1,029 | 3.71875 | 4 | # range() 函数可创建一个整数列表,一般用在 for 循环中
# 一个参数: 0开始,结束为止,步长为1
# 两个参数: 1起始位置,2结束位置
# 三个参数: 1起始位置,2结束位置,3步长
# 例题1:
# a = range(10)
# print(a)
# b = list(a)
# print(b)
# 例题2:
# for i in range(10):
# print(i)
# for i in range(3, 10):
# print(i)
# for i in range(3, 10, 2):
# print(i)
# for i in range(10, 3, -1... |
8fc49e52e904c6c74ea46aec7c583f06f5725ef9 | SapneshNaik/python_assignment | /problem9/dict_insert_delete.py | 367 | 4.03125 | 4 |
def main():
print("\nEnter 3 students details\n")
students = dict()
#insert
for i in range(3):
students[input("Enter Registration number\t")] = input("Enter Name\t")
print("\n")
print(students)
print("\n")
students.pop(input("enter a Registration Number to delete\t"))
print("\n")
print(students)
pr... |
787d0ba455eb7d0d5fbb54ee6835f7daf8d92186 | shiqi0128/My_scripts | /test/practise/lei/restaurant.py | 505 | 3.65625 | 4 | class Restaurant():
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
def describe_restaurant(self):
print("The most famous cuisine in " + self.restaurant_name.upper() + " is " + self.cuisine_type.title())
... |
b5d019c048b49d7679b8dd9ca171ab06fec6d2bb | zacateras/simulated-anneling-in-weighted-directed-graph-assignment-problem | /simulated_annealing.py | 7,862 | 3.921875 | 4 | import math
import random
import time
import matplotlib.pyplot as plt
import networkx as nx
import solution
class CoolingScheme:
"""
Abstract class of a Cooling Scheme.
Provides the next temperature value based on the initial T_0 and iteration number i.
"""
def step(self, t_0, i):
pass
... |
45a71a8194d5a228f759a6c6e02e2615203501fd | fr334aks/100-days-of-Hacking | /Malw0re/013_Day_List_comprehension/list_comp_if.py | 608 | 4.625 | 5 | #!/usr/bin/python3
#Generating even numbers.
even_numbers = [ i for i in range(21) if i % 2 == 0]
print (even_numbers)
#Generating odd numbers.
odd_numbers = [ i for i in range(21) if i % 3 == 0]
print (odd_numbers)
#Filter numbers: Fitlering out positive numbers.
numbers = [-8, -7, -3, 1, 0, 1, 3, 5, 7, 8, 9, 10]... |
642872cfaa692cee4a574b99bf1467f727583ed9 | cha63506/googleCode-22 | /solution1.py | 747 | 3.625 | 4 | def answer(numbers):
numbersSeen=[]
#numbersSeen.append(0)
loopStartIndex = 0
numberCount = 0
index = 0
print numbers
while True:
numbersSeen.append(numbers[index])
index2 = 0
while index2 != len(numbersSeen):
if numbers[index] == numbersSeen[index2]:
numberCount = numberCount + 1
index2 = index... |
13d83751a0baad5487e29f0fcf174ba9cfe1a84d | muhammadumerjaved44/PythonCourses | /Visualization/example_8.py | 260 | 3.59375 | 4 | # -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0.0,100,50)
y = np.random.uniform(low=0,high=10,size=50)
plt.plot(x,y)
# HERE
plt.xlabel('time (s)',color='red',fontsize=30)
plt.ylabel('temperature (C)', fontsize=15)
|
dfecd4a99c180bf24190913cc4df1ef3c22f0152 | data-pirate/recursive_codes | /towers_of_hanoi.py | 462 | 3.75 | 4 | def tower_of_Hanoi(num_disks):
"""
:param: num_disks - number of disks
"""
return solver(num_disks, 'S', 'A', 'D')
def solver(num_disks, source, auxiliary, destination):
if num_disks == 1:
print("{} {}".format(source, destination))
return
solver(num_disks - 1, source, destina... |
c84a7a07e3843632bea2c270df118cf06e43e533 | danielrhunt/python | /loops_while.py | 2,258 | 4.375 | 4 | #practice with loops
#the WHILE statement
#using "while" asks the statement to evaluate whether somethign is TRUE or FALSE, and execute while true
#the order of evaluation for while is:
#evaluate whether the condition is true or false
#if the condition is false, exit the while statement and continue executino ... |
0ab5f0d21c94435330fdbd98257696356574011c | yashAgarwal41/Awesome-Projects-Collection | /ML Projects/Movie Recommendation System/MovieRecommender.py | 1,537 | 3.5625 | 4 | import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import cosine_similarity
moviesPath = './Database.csv'
df2 = pd.read_csv(moviesPath)
# Import CountVectorizer and create the count matrix
cVectorizer = CountVectorizer(stop_words='english')
COUNT_MAT = cVect... |
379b25308413a254eacafd4b17e592548f3466c3 | Raghavi94/guess-the-number | /list_to_dict_and_dict_to_list.py | 256 | 3.703125 | 4 | #list to dictionary
list_alphabet=[(1,'a'),(2,'b'),(3,'c'),(4,'d')]
dict_alphabet=dict(list_alphabet)
print(dict_alphabet)
#dictionary to list
dict_alphabet={1:'a',2:'b',3:'c',4:'d'}
list_alphabet=list(dict_alphabet.items())
print(list_alphabet)
|
e3291cc205afc96b85882d7d12460ffdf75f5040 | mary-keenan/comprobo_warmup_project | /warmup_project/scripts/drive_square.py | 1,499 | 3.5625 | 4 | #!/usr/bin/env python
""" This script drives a robot in a 1m x 1m square """
import rospy
from geometry_msgs.msg import Twist
class square_driver(object):
def __init__(self):
""" initializes the square_driver object """
rospy.init_node('bumpty_dumpty')
self.publisher = rospy.Publisher('cmd_vel', Twist, queue... |
cddec37883c28a91c69d9f03966e6e0e01c3637f | ArunKarthi-Git/pythonProject | /Program220.py | 561 | 3.734375 | 4 | from Program219 import display
if __name__=='__main__':
def read(L):
L.append(input("Enter the Character"))
i=0
while(L[i]!='$'):
i+=1
L.append(input("Enter the Character"))
def copy(A,B,p,q):
print(len(A),p,q)
i=0
while p <= len(A) and i... |
2b1d1e7362692717052c4944f8ca8b34bcba55b3 | AmandaCasagrande/Entra21 | /Aula 04/exercicio13.py | 234 | 4.09375 | 4 |
# Exercicio 13
# Crie um programa que solicite o valor de x (inteiro)
#
# calcule usando a fórmula x+3
#
# mostre o resultado
valor_x = int(input("Digite o valor de 'x': "))
formula = valor_x + 3
print("O resultado é ", formula) |
9f2e7737699c487538ec9637144004f178bdb991 | baidoosik/ProblemSolving | /BOJ/problem_1260.py | 1,629 | 3.5 | 4 | vertex_num, edge_num, start = map(int, input().split())
edge_list = [tuple(map(int, input().split())) for i in range(edge_num)]
vertext_list = [i for i in range(1, vertex_num + 1)]
def dfs(vertext_list, edge_list, start):
stack = [start]
adjacency_list = [[] for i in vertext_list]
visited_list = []
e... |
3db8cde8a3def9bea7aafb265b8bad8e52a584ec | niteesh2268/coding-prepation | /leetcode/30-day-challenge/July_2020/26-Add-Digits.py | 331 | 3.6875 | 4 | class Solution:
def addDigits(self, num: int) -> int:
answer = 0
for digit in str(num):
answer = answer + int(digit)
if answer and answer % 9:
return answer % 9
elif answer and answer % 9 == 0:
return 9
else:
return 0
... |
8cb2e9b16671c57c27b5a81ca15b3faab7519f2b | SalimRR/- | /10,7.py | 279 | 3.8125 | 4 |
a = "мой дядя самых честных правил, Когда не в шутку занемог, Он уважать себя заставил И лучше выдумать не мог"
print(' '.join([ word for word in a.split() if not word.startswith('м')]))
|
29f85c30b3670baf4dfb546d701f036c4aa90ce3 | sthiago/rrgen | /core.py | 9,394 | 3.765625 | 4 | import random
class Node:
"""Represents a node in 2-D Grid. """
def __init__(self, x, y):
assert type(x) == int
assert type(y) == int
self.x = x
self.y = y
def __str__(self):
return f'({self.x}, {self.y})'
def __add__(self, other):
assert type(other) ... |
c8da53102f47b130ca9a47615231d326f0bc746b | fand/euler | /036.py | 637 | 3.8125 | 4 |
def is_palindrome(num):
if is_palindrome_dec(num) and is_palindrome_bin(num):
return True
return False
def is_palindrome_dec(num):
s = str(num)
lim = len(s)/2 # Note: digit at center doesn't need inspection.
for i in range(lim):
if s[i] != s[-1-i]:
return False
... |
9c6d5c60b5b2aa24847d3524473d57e1e031e00a | pouneh-mohammadi-n/monte_carlo_methods_in_finance | /Integral.py | 480 | 3.71875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import numpy as np
def integral(n,a1,a2,b1,b2):
x=np.random.uniform(a1,a2,n)
y=np.random.uniform(b1,b2,n)
I=(a2-a1)*(b2-b1)
s=I*np.sum(((x**2)+(y**2)))/n
print(s)
# In[2]:
import numpy as np
def integral1(n,a1,a2,b1,b2,c1,c2):
x=np.random.uniform(a1,a2,n... |
834831e5cff67c9ae374384817db99a457cd23e4 | sgouda0412/AlgoExpert_Solutions | /Hard/Hard_famous_algorithms.py | 6,770 | 3.65625 | 4 | # 1 Topological Sort
# mine (1st way of solving)
def topologicalSort(jobs, deps):
graph = getGraph(jobs, deps)
return orderedGraph(graph)
def getGraph(jobs, deps):
graph = GraphClass(jobs)
for prereq, job in deps:
graph.addPrereq(prereq, job)
return graph
def orderedGraph(graph):
result = []
for vertex in... |
f3f11e149057be508c607c419cb648b740521431 | BarteeJohn/portfolio | /Rock paper scissors.py | 409 | 4.0625 | 4 | from random import randint
x = int(input("Type 1 for rock, 2 for paper, and 3 for scissors: "))
correct = randint(1, 3)
print("the computer has chosen", correct)
if correct == x:
print("Tie")
if correct != x and x == 1 and correct == 3:
print("You win!")
if correct > x and x != 1 and correct != 3:
... |
2f529cf4b7f7a04e73aff73c3710da10b9ca13f6 | Aasthaengg/IBMdataset | /Python_codes/p03523/s948621897.py | 246 | 3.625 | 4 | S=list(input())
A="AKIHABARA"
id=0
for i in range(len(A)):
if len(S) > i and A[i]==S[i]:
continue
else:
if A[i]=="A":
S.insert(i,"A")
else:
print("NO")
exit(0)
if "".join(S)==A:
print("YES")
else:
print("NO") |
e06017eb94d32dd6dacce0434b5cd8124eac4525 | JannaKim/JavaPythonAlgoStudy | /2020/12_December_2020/201216/StarcraftProject/StarcraftProject2_201214_YejinJang.py | 6,643 | 3.671875 | 4 | from random import *
#일반 유닛
#init: 생성자 -> 객체가 만들어질 때 자동으로 호출됨
#멤버변수: 클래스 안에서 정의된 변수(name, hp)
class Unit:
def __init__(self, name, hp, speed):
self.name = name
self.hp = hp
self.speed = speed
print("{0} 유닛이 생성되었습니다.".format(name))
def move(self, location):
print("[지상 유닛... |
c75a791876d6eac6ba61767f63d784e637c04b3e | thippeswamydm/python | /4 - Classes-inheritance-oops/5-classes-overriding-overwriting-overloading.py | 791 | 4.09375 | 4 | # Describes overiding, overwriting, and overloading concepts
# OVERWRITING
# def funct():
# pass
# def funct():
# print('val')
# OVERLOADING - Theoritically not possible in python classes
# Using different forms of function execution implementation
# https://overiq.com/python-101/operator-overloading-in-pyth... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.