blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
1b725d6f580e3e9889b39fe904ffbbf037ae73c4 | pyao7-code/ops435-Python | /lab1/lab1d.py | 111 | 3.609375 | 4 | #!/usr/bin/env python3
x = 10
y = 2
z = 5
print(str(x) + ' + ' + str(y) +' * '+ str(z) + ' = '+ str(x + y * z)) |
7fe7df3b4a6a3bfcbae1923d86fd237cd0e109f7 | AnanyaMaruthi/CollegeCourseWork | /5th semester/ADALab/mergeSort.py | 941 | 4.0625 | 4 | def merge(arr, low, high, mid):
temp = [0 for i in range(low, high + 1)]
i = low
j = mid + 1
k = 0
while(i <= mid and j <= high):
if arr[i] <= arr[j]:
temp[k] = arr[i]
k += 1
i += 1
else:
temp[k] = arr[j]
k += 1
... |
bab322322b5f445a7bc08a5a554b230801e72fca | basdijkstra/python-for-testers | /exercises/exercises_06.py | 626 | 4.46875 | 4 | # Exercise 6.1
# Create a method write_and_read_file() that does the following:
# Create a new file file.txt (Python will create a file that you
# try to open a file that doesn't exist) with "write" privileges.
# Write three random lines to the file and close it.
# Reopen the file and print its contents.
# Exercise 6.... |
ddc778262c364945927a59d3b0129e3aad4c55d9 | AlexanderBollbach/leetcode | /leetCode101.py | 1,178 | 3.828125 | 4 |
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
t = TreeNode(1)
tl = TreeNode(2)
tr = TreeNode(2)
tll = None
tlr = TreeNode(3)
trl = None
trr = TreeNode(3)
t.left = tl
t.right = tr
t.left.left = tll
t.left.right = tlr
t.right.left = trl
t.right.right... |
897d913a36702eb234189de7f630f949dcb230eb | hbbaly/python-learn | /demo3/demo2.py | 2,475 | 4.21875 | 4 | # -*- coding: utf-8 -*
# 函数定义
# 定义一个函数要使用def语句,依次写出函数名、括号、括号中的参数和冒号:,然后,在缩进块中编写函数体,函数的返回值用return语句返回
# 我们可以自定义一个类似abs()函数功能:
def my_abs(a):
if a > 0:
return a
else:
return -a
print(my_abs(10)) # 10
print(my_abs(-10)) # 10
# 函数可以同时返回多个值,但其实就是一个tuple,返回一个tuple可以省略括号,而多个变量可以同时接收一个tuple,按位置赋给对应的值
def man... |
bc400c084f9554f58737c0bcde68422347a86f19 | mwflickner/cmsi282 | /hw1/PriorityQueue1.py | 1,602 | 4.09375 | 4 | class PriorityQueue1:
def __init__(self):
self.heap = []
self.size = 0
def add(self, x):
self.heap.append(x)
self.size += 1
self.sift_up(self.size-1)
def remove(self):
if self.size == 0:
raise IndexError('Queue is empty')
if self.size ==... |
a88599b1abb8c8040d31beee3841a532244550ed | salaschen/ACM | /Leetcode/128_LongestConsecutiveSequence/sol.py | 3,936 | 3.546875 | 4 | '''
Prob: Leetcode 128 - Longest Consecutive Sequence
Level: Hard
Author: Ruowei Chen
Note:
1) Need to be O(n) complexity.
2) AC on the second time, first time missed the empty case.
3) Coded the official solution and compare the performance. My implementation does run on O(N) complexity,
as shown by t... |
35149ff513ba3ca47a8b2933f19277edac0dfb58 | Gafanhoto742/Python-3 | /Python (3)/Ex_finalizados/ex093.py | 1,193 | 4.25 | 4 | '''Crie um programa que gerencie o aproveitamento de um jogador de futebol.
O programa vai ler o nome do jogador e quantas partidas ele jogou. Depois vai ler a
quantidade de gols feitos em cada partida. No final, tudo isso será guardado em um dicionário,
incluindo o total de gols feitos durante o campeonato.'''
jo... |
14a371893ffe56b80475ed573b46b68dbd2a568c | rgostic/Project-2 | /affine.py | 957 | 3.703125 | 4 | import string
from ciphers import Cipher
class Affine(Cipher):
FORWARD = string.ascii_uppercase * 3
MAP = {}
forcedMAP = {}
def __init__(self, offset=3):
self.offset = offset
self.FORWARD = string.ascii_uppercase + string.ascii_uppercase[:self.offset+1]
self.BACKWARD = st... |
9c4d6584901bee4b62b7c48d02d91f867204bde8 | ptsiampas/Exercises_Learning_Python3 | /07_Iteration/Exercise_7.26.02.py | 342 | 4.09375 | 4 | # Sum up all the even numbers in a list.
__author__ = 'petert'
def is_even(n):
if (n%2) == 0:
return True
return False
def sum_even(xs):
final=0
for num in xs:
if is_even(num):
final+=num
return final
numbers=[1,2,3,4]
print("Sum of all the even numbers is {0}".format... |
f36a15a0a66045f6e045e1ecaf75df4b6aae09a8 | jamuna1BM18CS408/python | /additional.py | 159 | 3.6875 | 4 | def rev1(str1):
lis=[]
for a in str1:
if a.isdigit():
lis.append(a)
print(lis)
str1=input("enter the string")
rev1(str1)
|
1f53e6a6f50fff5bdf9df834d349a7d5bb3c6ae7 | abstractlyZach/CardGames | /cards/five_card_hand.py | 2,536 | 3.796875 | 4 | from collections import defaultdict
from cards import exceptions, ranks
class FiveCardHand(object):
"""General class for hands with five cards."""
def __init__(self, cards):
self._cards = list(cards)
self._check_hand_size()
self._count_suits_and_ranks()
def _check_hand_size(self)... |
4a604ed964c1453a1db572d2535efaa131b1a06b | hash-table/algorithm | /2020/12/02/leet_75_sort-colors.py | 4,266 | 3.5625 | 4 |
# leet_75_sort-colors.py
# _leet
# _two-pointer
# sort-colors/
# 202012062104 202012062130
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
'''
problem
... |
df9521bcc9e60256ebb5181dd1e9254de4b830c7 | ChrisLiu95/Leetcode | /google/Palindrome_Permutation.py | 984 | 3.90625 | 4 | """
Given a string, determine if a permutation of the string could form a palindrome.
For example,
"code" -> False, "aab" -> True, "carerac" -> True.
collections.Counter()
http://www.pythoner.com/205.html
get(key[, default])
Return the value for key if key is in the dictionary, else default.
If default is not given... |
4d253738150432d06f88350c1bd4f77e0e7c69a7 | LukasKodym/py-tests | /strings.py | 369 | 3.75 | 4 | # %%
##
s = 'Witaj nasze 0'
print('b' not in s)
# to jest komentarz
# %%
##
x = input('Wprowadź swoej imię: ')
print('Twoje imię to: ' + x)
# %%
##
a = float(input('Wprowadź liczbę: '))
a += 1
print(a)
# %%
##
pcs = 12
# s = 'W magazynie jest ' + str(pcs) + ' sztuk.'
s = 'W magazynie jest {} sztuk.'.format(pcs)
prin... |
3bfcfe40cbcf8546ff22091fc9cf2d37f9e7bd81 | justcoddev/Python100days | /day005/Ejercicio_011.py | 656 | 3.96875 | 4 | # 3)Hacer un programa para ingresar por teclado cuatro números, sumar los dos primeros y los dos segundos; si la
# suma de los dos primeros es mayor a la suma de los dos segundos emitir un cartel aclaratorio, caso contrario no
# emitir nada.
print('#####')
num_1 = int(input('Ingrese primer número: '))
num_2 = int(input... |
5c09637ac26508caee6916868e528d9c98aecfbd | Cica013/Exercicios-Python-CursoEmVideo | /Pacote_Python/Ex_python_CEV/exe093.py | 1,002 | 4.125 | 4 | # Crie um programa que gerencie o aproveitamento de um jogador de futebol. O programa vai ler o nome do jogador e
# quantas partidas ele jogou. Depois vai ler a quantidade de gols feitos em cada partida. No final, tudo isso será
# guardado em um dicionário inclindo o total de gols feitos durante o campeonato.
jogador =... |
255330b16de4863073b77c7f6a76f0e20820240c | py27/python | /addressbook.py | 4,706 | 3.71875 | 4 | # RKunt
from Tkinter import *
import tkMessageBox as msgBox
from contacts import *
import csv
import pandas as pd
def cselect():
""" This the function which sets the location when the cursor selects an contact from the list"""
return int(select.curselection()[0])
def addF():
""" This function will add all the ... |
890ac30e7c8bf5fdcf742fec2d31b8b1d12aaf7a | maguas01/hackerRank | /pStuff/Service_Lane.py | 1,100 | 3.65625 | 4 | '''
Calvin is driving his favorite vehicle on the 101 freeway. He notices that the check engine light of his vehicle is on, and he wants to service it immediately to avoid any risks. Luckily, a service lane runs parallel to the highway. The length of the service lane is N units. The service lane consists of N segments ... |
0be7449407984a5c38ead9cb9b9d9aa702a29bed | Wizmann/ACM-ICPC | /HackerRank/Tutorials/10 Days of Statistics/Day 1: Quartiles.py | 324 | 3.625 | 4 | def median(ns):
n = len(ns)
if n % 2 == 0:
return (ns[n / 2 - 1] + ns[n / 2]) / 2
else:
return ns[n / 2]
n = int(raw_input())
ns = sorted(map(int, raw_input().split()))
m = median(ns)
l, r = filter(lambda x: x < m, ns), filter(lambda x: x > m, ns)
print median(l)
print m
print median... |
ad6cf81011c3c674ecd0373dcaff8d7574be211a | bhushangawde/Daily-Coding-Problems | /extra/countingSort.py | 481 | 3.5 | 4 |
"""
Linear time sorting
"""
def countingSort(A: list) -> list:
min_A, max_A = A[0], A[0]
for a in A:
if a>max_A:
max_A = a
if a<min_A:
min_A = a
H = {k: 0 for k in range(min_A, max_A+1)}
for a in A:
H[a]+=1
for k in range(min_A+1, max_A+1):
H... |
19a4114e01c5575cd59ce49abe1d91ceb5b28e23 | ParkJiwoo98/AI-Programming | /HW6_1_201824481.py | 918 | 3.625 | 4 | import numpy as np
# (a)
a = np.full((6, 4), 2)
print(a)
# (b)
b = np.full((6, 4), 1)
b[0:6, 0:1] = 3
print(b)
# (c)
print(a * b)
# print(np.dot(a, b))
"""
a * b의 경우 단순히 각 위치에 있는 배열의 원소끼리
a[0][0] * b[0][0], a[0][1] * b[0][1], ... 과 같이
곱셈을 하게 되어 a와 b의 크기가 같다면 * 연산이 가능하다.
하지만 dot 연산의 경우 matrix multip... |
a351de6aeb01a62f7e940f10020b05f0b0046015 | ccbrantley/Python_3.30 | /Lists and Tuples/rainfall_statistics/rainfall_statistics.py | 800 | 4.0625 | 4 | #rainfall statistics
def main():
months = get_input()
avg_rain(months)
min_max(months)
def get_input():
months = []
for index in range(12):
user_input = float(input('Enter the amount of rainfall for month {}:'.format(index + 1)))
months.append(user_input)
return m... |
4d4d8f25183f321f2cc195cc47e2a543c3a713ff | danhNQ7/CompressAndDecompress | /JPEG_ENCODER/LZW.py | 5,536 | 4.25 | 4 | import io
def compress(text):
"""
compress() takes a string and compresses it using the LZW algorithm.
Returns the compressed string in the form of a list of integers.
@params: string to be compressed.
@return: compressed string (list of ints).
"""
if text == '':
return []
elif t... |
3f81c77c4d5832eab7e9c2526b7322a1ece6738e | faridaatei/python | /python/saumu.py | 283 | 4 | 4 | def area_triangle(base,height):
return 0.5*base*height
def area_circle (radius):
return 3.14 * radius *radius
height, base, radius =50 ,70, 14
print ("area of triangle {}". format(area_triangle(base ,height)))
print ("area of a circle {}".format(area_circle(radius)))
|
c21643f5c58676f77da8ffbc14d3dc488c5b0d8e | saadkang/PyCharmLearning | /basicsyntax/indexvstring.py | 2,088 | 4.40625 | 4 | """
We will see how the index works in python
"""
nameOfAString = "This is for educational purposes only"
# The : in the [] is has no starting and ending index so it will print the whole String
print("There is nothing before or after the : so it will print complete String: "+nameOfAString[:])
# In the example below ... |
8950ac176813b900f3f4e7a4d3358e977987552e | andrewn488/5061-entire-class | /Week 05/pec1_decimal_to_binary.py | 741 | 4.21875 | 4 | """PEC1: Decimal to Binary
Author: Andrew Nalundasan
For: OMSBA 5061, Seattle University
"""
print('When you enter a non negative integer a string in binary representation will be shown')
n = int(input('Enter a non- negative integer: '))
if n < 0:
print('You must enter a non- negative integer: ')
p... |
3b702da81deba10c58305d40f48ba2e162be7ce2 | rkeb/rgn | /model/geom_ops.py | 14,645 | 3.59375 | 4 | """ Geometric TensorFlow operations for protein structure prediction.
There are some common conventions used throughout.
BATCH_SIZE is the size of the batch, and may vary from iteration to iteration.
NUM_STEPS is the length of the longest sequence in the data set (not batch). It is fixed as part of the tf... |
8fd3ac1a99361503fc6de9fa6e396d596f68e98d | NaikShweta/Movie-Trailer-Website | /media.py | 395 | 3.59375 | 4 | class Movie():
"""class to create a movie-trailer website"""
def __init__(self, movie_title, movie_storyline,
movie_poster_url, movie_youtube_url):
"""Current instance of class Movie"""
self.title = movie_title
self.storyline = movie_storyline
self.poster_image_u... |
4fd64d2f9a9e50558c30622decda441bed0b465f | twangcode/MLforTradingUdacity | /01_03_Arithmetic_operations.py | 514 | 3.984375 | 4 | """Arithmetic operations."""
import numpy as np
def test_run():
a = np.array([(1,2,3,4,5),(10,20,30,40,50)])
print "Original array a:\n", a
# Multiply a by 2
print "\nMultiply a by 2:\n", 2 * a
#Divide a by 2
print "\nDivide a by 2:\n", a / 2.0
# Add the two arrays
b = np.array([(100,200,300,400,500),(1,2... |
fbdfdb9eb7b62625ac968eed2ea712f50e940b3f | caryt/kiosk | /model/salaries.py | 375 | 3.6875 | 4 | """Salary Class definition.
"""
from db import db
class Salaries(db.Model):
emp_no = db.Column(db.Integer, db.ForeignKey('employees.emp_no'))
salary = db.Column(db.Integer)
from_date = db.Column(db.DateTime, primary_key=True)
to_date = db.Column(db.DateTime)
def __str__(self):
return "{fro... |
02f5184624b2f6e76957d82834bcd5c1bf2f8861 | NamNaam/python-for-coding-test | /16.py | 1,869 | 3.515625 | 4 | # 떡볶이 떡 만들기
# 내 풀이 (오답)
import sys
def binsearch(data, target, start, end):
sum = 0
if start > end:
return not_find_data(data, target, data[end - 1], data[end])
mid = (start + end) // 2
for i in range(mid):
sum += data[i] - data[mid]
if sum < target :
return binsearch(data, target, mid + 1, end)
elif sum ... |
692abe45640f21b30b22f91277c7cdb283fede36 | changhao2882/changhao0001 | /untitled/tkinter_/9.listbox列表框控件.py | 1,318 | 3.75 | 4 | import tkinter
def update():
pass
#创建主窗口
win = tkinter.Tk()
#设置标题
win.title("QQ")
#设置大小和位置
win.geometry("494x470+200+0")
#进入消息循环
#创建列表框
listbox = tkinter.Listbox(win,selectmode=tkinter.BROWSE)
listbox.pack()
for item in ["money1","money2","money3","money4"]:
listbox.insert(tkinter.END,item)#按顺... |
92a25d208d756e7b15bf4fcc61f1417f3976b588 | toby20-meet/meet2018y1lab2 | /debugging1.py | 446 | 3.546875 | 4 | import turtle
my_turtle = turtle.Turtle()
t = 200
b = -200
#draw A
#my_turtle.hidemy_turtle() #this line is broken!
my_turtle.hideturtle()
my_turtle.penup()
my_turtle.goto(-100,0)
my_turtle.pendown()
my_turtle.penup()
x,y = my_turtle.pos()
my_turtle.goto(x,y)
my_turtle.pendown()
my_turtle.goto(x+100, y+300)
m... |
70075cba6b5f02aef296f1dc38838d758f36883f | beepboop271/average-calculator | /classes/mark.py | 962 | 3.546875 | 4 | class Mark(object):
def __init__(self, numerator, denominator, weight, strand_str):
self.numerator = numerator
self.denominator = denominator
self.weight = weight
self.strand_str = strand_str
self.decimal = float(numerator)/denominator
def __eq__(self, other):
if... |
dafda449e3e34708994498bfc6ef94eabafed060 | wnwoghd22/NTHU_HW_All | /Python/SC10_1.py | 337 | 3.84375 | 4 | class Polynomial:
def __init__(self, *coeff):
self.coefflist = coeff
def evaluate(self, xvalue):
idx = 0
x = 0
for i in self.coefflist:
x += i*(xvalue**idx)
idx += 1
return x
__call__ = evaluate
f = Polynomial(3,5,4,7,1)
print(f.evaluate(3))
p... |
71e47aa9d6adf6fb721d1a5835c4a05c625e6cd9 | fudigit/Basic_Algorithm | /5.Binary_Tree&Tree-based_DFS/86.Binary_Search_Tree_Iterator.py | 1,617 | 3.984375 | 4 | '''
Use stack, stack[-1] is the next node for in-order traversal
1. use stack to store the trail to left most node
2. hasNext() is the same as check if stack is not empty
3. Next(): return the top of stack, then change to stack to the next state
- if current node has right subtree (no left tree guaranteed), get its... |
ffa679f6da0eed5547bc28a0fabbc27f2163334f | GoblinDynamiteer/pyt_io | /str_i.py | 1,372 | 3.84375 | 4 | #!/usr/bin/env python3.6
'''String input'''
import sys
import os
import str_o
PRINT = str_o.PrintClass(os.path.basename(__file__))
def yes_no(question, default="yes", script_name=None):
valid = {"yes": True, "y": True, "no": False, "n": False}
if default is None:
prompt = " [y/n] "
elif default... |
c42b5e119a026217c305ba37d23b2a3271237dd1 | felipevitalrc/CursoEmVideoPythonExercicios | /aula10h.py | 564 | 4.15625 | 4 | print('---PROGRAMA PARA CALCULAR SE É POSSÍVEL FORMAR UM TRIÂNGULO---')
ladoA = float(input('Digite a primeira reta: '))
ladoB = float(input('Digite a segunda reta: '))
ladoC = float(input('Digite a terceira reta: '))
if (ladoA - ladoB) < ladoA and ladoA < (ladoB + ladoC):
if (ladoA - ladoC) < ladoB and ladoB < (l... |
ea6e249599e6d0f5871f9207e77b84a4bfc88e3b | mwilliamson13/pgss2020-corecs-jupyter-d2 | /sym-ascii-cipher.py | 1,922 | 4.34375 | 4 | # Hiding this really important number in an obscure piece of code is brilliant!
# AND it's encrypted!
# We want our biggest client to know his information is safe with us.
bezos_cc_secret = "_aeg\\e`aa\\bg`g\\`beg"
# Reference alphabet
# This alphabet is the same order as ASCII, but omits non-printable characters
alph... |
ab709f9b32284dfe12d0470025a6bdb72a768290 | NWILLROCKU/Euler | /23.py | 687 | 3.53125 | 4 | import time
def getDiv(n):
# Gets all divisors of n, excluding n
divList = [1]
for i in range(2, int(n/2)+1):
if n % i==0:
divList.append(i)
return divList
start_time = time.time()
# Get list of abundant nums
ab = [12]
maxab = 28121
for i in range(14, maxab):
if i % 2 > 0 and ... |
0835a4c8ed5de4377a8c99e1eccdab5c2a5c1c5a | lixintong1992/Algorithms | /Sorting/QuickSort.py | 791 | 3.96875 | 4 | def quickSort(arr, left, right):
if(left < right):
print(arr)
i, j = left, right
if len(arr) <= 1:
return
flag = arr[left]
while(left < right):
while(left < right and arr[right] >= flag):
right -= 1
if(left < right):
... |
5bb8fc186cce98403831fd014f6b70900de6d222 | sssschenyi/tools | /字符串分割.py | 548 | 3.9375 | 4 | # author: chenyi
# ide: notepad++
# date: 19:45 2022年10月11日
# 把字符串分割成列表
def strplit():
s = "this is string example he"
restr = " " #指定分隔符对字符串进行切片
# 调用函数只需要更改上面 2 个变量
### 下面不用改
s2 = ''
new = []
for i in s:
# print(i)
if i != restr:
s2 += i
elif i == ... |
4e433bc1f4f7723c750e2751f1f3a1b6332d14fb | fingerecho/proms-3.0.1 | /rules_proms/rules_templates/rule.py | 2,914 | 3.53125 | 4 | import datetime
import json
class Rule:
"""
Template for a Rule.
This template class needs to be initialised with the standard Rule required parameters as well as any other
instance parameters needed for the specific rule operation.
It returns a standard rule return object which is a Python dict... |
57b2b8ae9ba8f2b82637f30009df756034ce8e80 | rathoresrikant/HacktoberFestContribute | /Algorithms/Geometry Algorithms/Graph Theory/breadth_first_search.py | 752 | 4.03125 | 4 | """
Python implementation for Breadth First Search algorithm
"""
from queue import Queue
dummy_graph = {
'A': ['C', 'E'],
'B': ['C', 'E', 'G'],
'C': ['D', 'F', 'G'],
'D': ['H'],
'E': ['A', 'B', 'C'],
'F': ['D', 'I'],
'G': ['A'],
'H': [],
'I': ['B', 'C']
}
def bfs(graph):
q = Queue()
visited_nodes = []
... |
b3cc3ba3ceb161604dad112f14e4914af2ffb0fa | JinZSu/ML_Study | /Linear Regression/LinearRegression+Multi.py | 4,253 | 4.34375 | 4 | # ML_Homework1
import numpy as np
import pandas as pd
import matplotlib
from matplotlib import pyplot as plt
# %matplotlib inline
def fit_linear(x,y):
"""
Given vectors of data points (x,y), performs a fit for the linear model:
yhat = w0 + w1*x,
The function returns w0, w1 and rsq, where rsq is the... |
586acc03a7d3f4d7500ae52336106b9c661eb4b1 | csrunner/leetcode | /912_sort_an_array.py | 357 | 4.09375 | 4 | '''
Given an array of integers nums, sort the array in ascending order.
Example 1:
Input: [5,2,3,1]
Output: [1,2,3,5]
Example 2:
Input: [5,1,1,2,0,0]
Output: [0,0,1,1,2,5]
'''
class Solution(object):
def sortArray(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
... |
a34f24be274cda6c893b8f3067c269e0430fa92d | AbelLim/cp1404Practicals | /prac_07/guitars.py | 1,028 | 4.03125 | 4 | """
Allow user to add guitar to list of guitars. Allow the user to view the list of guitars.
"""
from prac_07.guitar import Guitar
def main():
print("My Guitars!")
guitars = []
is_blank = False
while is_blank is False:
guitar_name = input("Name: ")
if guitar_name is "":
i... |
10b150416afe4d70011fa93a80b20fa39faf79be | t12343/Quoridor | /quoridor/pawn.py | 973 | 3.5625 | 4 | import pygame
from quoridor.data import SQUARE_DISTANCE, SQUARE_SIZE, WALLS_AT_THE_START
class Pawn:
def __init__(self, row, col, color, been_there=[]):
# Pawn constractor
self.row = row
self.col = col
self.color = color
self.RADIUS = SQUARE_SIZE // 4
sel... |
172ca2ac60c63ee15afab3193a8442af01b1478d | Sabryfattah/Python | /GUI/exch_rates.py | 1,578 | 3.71875 | 4 | import requests
import tkinter as tk
# Where USD is the base currency you want to use
url = 'https://api.exchangerate-api.com/v4/latest/USD'
# Making our request
response = requests.get(url)
data = response.json()
# Your JSON object
eg = data['rates']['EGP']
uk = data['rates']['GBP']
root = tk.Tk()
root.... |
e16776f47f8b3dc0f0794dc9fcb8a3e2e93216a8 | Odarlie/Binarysearch_programming_logic | /binarysearch_andelab.py | 509 | 4.125 | 4 | def BinarySearch(the_list, item_to_search):
'''
binary search function
'''
start_position=0
last_position=len(the_list)-1
found=False
while start_position<=last_position and notfound:
midpoint=(start_position+last)//2
if the_list[midpoint]==item_to_search:
found=Tru... |
03df6565aeab2a6ec662428606968ea26dd33376 | ksaylor11/python-functions | /multiples_of_3_and_5.py | 361 | 3.9375 | 4 | def solution(number):
numbers = []
for x in range(number -1, 0, -1):
if (x % 3 == 0):
numbers.append(x)
continue
elif (x % 5 == 0):
numbers.append(x)
continue
else:
continue
return sum(numbers)
if __name__ == "__main__":
... |
30d3da1ba30eadb48126f60fef1af8c400b4f582 | michael-mck-doyle/Python | /unit_tests/test_calc_function.py | 1,172 | 4.28125 | 4 | '''
1. import the function that you need e.g. import unittest
2. create a test case Class in the test file
3. define the test case (which is a method) - the test case is written in the method
4. the test case name (method) must begin with "test_"
'''
import unittest
from unit_tests import calc_Function
class test_c... |
b68f4cc082558d70aff5d705195c1acbdf3bbf69 | ZhihaoJun/project-euler | /7.py | 351 | 3.78125 | 4 | #10001st prime
#By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
#What is the 10 001st prime number?
#The answer is 104743
fin = open("prime", "rb")
primeList = fin.read()
primeNum = 0
for i in range(2, len(primeList)):
if primeList[i] and primeNum<10001:
prim... |
908fd28d889333f829bb8c6c3ef9694fbdad8803 | jakechenzhenbin/hello-world | /class_test/test_01.py | 10,380 | 3.8125 | 4 | #-*- coding:utf-8 -*-
#contact: 787872498@qq.com
#file: test_01.py
#time: 2020/5/25 17:36
# print("趁自己肯定就付款即可")
#
# class MyClass:
# i = 123456
# def a(self):
# return "hello wolrd"
# x = MyClass()
# print(x.i)
# print(x.a())
# import random
# print(random.random())
# n = 0
# while n < 5:
# a = ran... |
b4649a6a55f01da19880efabed1b06e6aeb2a9d7 | petewurster/csci111 | /class_labs/better_versions/gymnastic.py | 1,320 | 3.90625 | 4 | #gymnastic.py;
#depencancies: none;
#last edit: 2020-06-01, by pWurster;
#get scores from 6 gymnastics judges & average them using a program that is
#modularized into functions and is well documented
#init vars
NUMBER_OF_JUDGES: int = 6 #constant based on program requirement for 6 judges
#gets score from each judge ... |
bd12d94134bb3b4370c5edf134f07932b69c8a40 | Castro99/2018-19-PNE-practices | /Session-5/Seq-1.py | 569 | 3.875 | 4 | #Exercise II lesson 5
class Seq:
"""A class for representing sequences"""
def __init__(self, strbases):
print("New sequence created!")
self.strbases = strbases
def len(self):
return len(self.strbases)
class Gene(Seq):
s1 = Seq("ATTCGATCC")
s2 = Seq("AAAGG")
str1 = s... |
2cca7487a5fd3335173b7e6f5c083e480db7dcf5 | wql7654/bigdata_exam | /01.jump to python/codingdojang/sainap.py | 525 | 3.6875 | 4 | name="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
name_etc=name.split(',')
name_cnt=0
lee_cnt=0
for name_find in name_etc:
if name_find[:1] in '김' or name_find[:1] in '이':
name_cnt+=1
if name_find in "이재영":
lee_cnt+=1
name_set=set(name_etc)
name_list=list(name_... |
a9a281e5fdbfca0208a9a7e343f276ebac813451 | B-joon/java-school | /Workspace_Python/Python00/opr.py | 795 | 3.984375 | 4 | # 산술연산자
a = 21
b = 2
print(a + b)
print(a - b)
print(a * b)
print(a ** b) # a의 b승
print(a / b)
print(a // b) # 몫 (floor division)
print(a % b)
# 비교연산자
a, b = 5, 3
print(a == b)
print(a != b)
print(a > b)
print(a >= b)
print(a is b)
print(a is not b)
# 범위연산자
list01 = list(range(100)) # 0 ~ 99
print(list01)
# [s... |
ccd9e84ec78b0248329265c87485bda4a6159937 | DamoM73/Learn-to-program-in-Python | /Chapt 12/Ex2.py | 471 | 3.875 | 4 | from tkinter import *
window = Tk()
def greeting():
label.config (text = "Hello")
def farewell():
label.config (text = "Goodbye")
label = Label(window, text = "Press a button")
label.grid(row = 0, column = 0, columnspan = 2)
button1 = Button(window, text="Greeting", width=7, command = greeting)
button1.gri... |
0644b2523fc9361b89f2a2f0713e1cf0c67f6ab4 | toulondu/leetcode-repo | /linkList-middle/addTwoNumbers.py | 2,629 | 4.21875 | 4 | '''
给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。
请你将两个数相加,并以相同形式返回一个表示和的链表。
你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例 1:
输入:l1 = [2,4,3], l2 = [5,6,4]
输出:[7,0,8]
解释:342 + 465 = 807.
示例 2:
输入:l1 = [0], l2 = [0]
输出:[0]
示例 3:
输入:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
输出:[8,9,9,9,0,0,0,1]
提示:
每个链表中的节点数在范... |
2dd5e8fd4d23b4fa32ea65ccd4288a6a2496b683 | Mohitgola0076/Day3-Internity | /Generators.py | 1,397 | 4.65625 | 5 | '''
A generator-function is defined like a normal function, but whenever it needs to generate a value,it does so with the yield keyword rather than return.
If the body of a def contains yield, the function automatically becomes a generator function.
'''
# 1.) A Python program to demonstrate use of genera... |
f3e96eb8640067f4f2698e1a02c03f2f6fcfa46c | jiangshen95/UbuntuLeetCode | /SumofLeftLeaves.py | 764 | 3.84375 | 4 | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def sumOfLeftLeaves(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
if root.left and not root.l... |
be23e3bb52a6a191041264d2430fde3a4a1ebdd6 | richardOlson/Intro-Python-I | /src/13_file_io.py | 1,172 | 4.375 | 4 | """
Python makes performing file I/O simple. Take a look
at how to read and write to files here:
https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files
"""
# importing the os to get the path to find the file
import os
fooPath = os.path.join(os.path.dirname(__file__), "foo.txt")
# Open up t... |
39a3b8dfaeba552d2cb9350c88e38528bdd14266 | n0execution/Cracking-the-code-interview | /Stacks_Queues/python/DoublyLinkedList.py | 1,023 | 3.59375 | 4 | class Node(object):
def __init__(self, data=None, next=None, prev=None):
self.data = data
self.next = next
self.prev = prev
def __str__(self):
return str(self.data)
class DoublyLinkedList(object):
def __init__(self):
self.head = None
self.tail = None
... |
6d88859097e3a6ea52fa5e621cdb3e4f4593f073 | venkateshraizaday/ArtificialIntelligence | /a1/puzzle.py | 3,210 | 3.625 | 4 | '''
- In this problem I have used a brute force approach to solve the puzzle.
- I pass the all possible permutations of the names, orders and locations into a vallidator function which checks if the current arrangement passes all the conditions in the question.
- If 'no' the state is discarded and next state is... |
e72900223e22a5bc57d192f19d5da97db48a4272 | pateli21/ICS2019_2020 | /ICS_05_HiLo/Program.py | 2,489 | 4.0625 | 4 | import random
#this function takes a guess, evluates it, and gives back the appropriate response
def hiLo(magicNum, b, count, guessList):
try:
guess = int(input("Guess a number between 1 and " + str(b) + ": "))
count += 1
if guess < 1 or guess > b:
print("Your guess is out of ... |
2408fbbb800bd551af1b0813f623dd57db6c2849 | WallysonGalvao/Python | /CursoEmVideo/Exercicios.py | 10,628 | 4.3125 | 4 | # Challenge 001
# Create a program that write "Hello, World!" on the screen.
print("Challenge 001")
print("Create a program that write \"Hello, World!\" in screen.")
print("Hello, World")
# Challenge 002
# Make a program that reads the name a person and show a welcome message.
print("Challenge 002")
print("Make a prog... |
c0533416a75d678f0c280f1945017cc02e92304c | crazywiden/Leetcode_daily_submit | /Widen/LC3_Longest_Substring_Without_Repeating_Characters.py | 1,518 | 4.125 | 4 | """
3. Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the le... |
e2df5c4298c1dde042c8a777780cab2dcaaafda0 | shankar7791/MI-10-DevOps | /Personel/Rajkumar/Assessment/1_march/list.py | 123 | 3.53125 | 4 | #wrrong h output
n = int(input('Enter a number:'))
l = [n]
if l[0] == l[len(l)-1]:
print(True)
else:
print(False) |
37136561c886b06b9ade50daac562971e98ae6e3 | PedroPadilhaPortella/Curso-Em-Video | /Curso de Python Mundo 3/098-maior.py | 539 | 3.78125 | 4 | from time import sleep
def maior(*valores):
contador = maior = 0
print("Analizando os valores recebidos...", end=" ")
sleep(1)
for valor in valores:
print(valor, end=" ", flush=True)
sleep(0.4)
if contador == 0:
maior = valor
if valor > maior:
m... |
4b9834b851c87af67c6dab82f8a62e341b4afc59 | FredC94/MOOC-Python3 | /UpyLab/UpyLaB 5.23 - Matrices.py | 1,175 | 4.34375 | 4 | """ Auteur: Frédéric Castel
Date : Avril 2020
Projet : MOOC Python 3 - France Université Numérique
Objectif:
Écrire une fonction init_mat(m, n) qui construit et renvoie une matrice d’entiers initialisée
à la matrice nulle et de dimension m x n.
Consignes:
Dans cet exercice, il vous est demandé d’é... |
89ab82774df52137b0be4442182cf422579a6efd | Akanksha-Verma31/Python-Programs | /split with deliminater.py | 155 | 3.953125 | 4 | # split(): break string into list of string with specified point of break
string = "the rain in spain"
a = string.split("ai") # with delimiter
print(a)
|
2b1e4ddaa78f4b596e8913e64833b2c9dd66c3f1 | tiboras/IN104_Mathis_Miroux-Thibaud_Rasse | /Project_TA/projet/simulator/simulator.py | 891 | 3.515625 | 4 | import numpy as np
from simulator.utils.vector import Vector, Vector2
class Simulator:
def __init__(self, world, Engine, Solver):
self.t = 0
self.world = world
self.engine = Engine(self.world)
# Engine uses World to represent the state
# of the world while Solver uses a
... |
392bd531eedda9f6b472915498f8e4e019450cd7 | hhshhd/hhshhd | /IB CS/Hw/first test 0829-0902.py | 2,945 | 3.921875 | 4 | import unittest
import random
import itertools
# Given a string (e.g. "What the hell?"), returns a list of the following pattern
# ['What the hell?', 'What the hell', 'What the hel', 'What the he', 'What the h', 'What the ',
# 'What the', 'What th', 'What t', 'What ', 'What', 'Wha', 'Wh', 'W']
def input_nput_put_ut_t... |
db35061199ee4e7c1918982ec091b8b361b0648b | letivela/AnitaBorg-Python-Certification-Course | /Week 7 Coding Challenges/Functions/output.py | 391 | 3.75 | 4 | # SCRIPT: output.py
# AUTHOR: Sahar Kausar
# CONTACT: saharkausar@gmail.com
#
# Anita Borg - Python Certification Course
#
# DESCRIPTION: What is the output of the following code?
"""
Code Input:
i = 1
while i < 5:
if i == 6:
break
print(i, end = " ")
i = i + 1
else:
print("Else is... |
e63c73e56568c7965ffbb79db02d2ea7b4578d00 | gabrielyap/early-works-python | /32ahw7/board.py | 707 | 3.671875 | 4 | class Board:
EMPTY_SLOT = "_"
def __init__(self, width, height):
if (width < 0 or width < 0):
raise ValueError
self.width = width
self.height = height
self.grid = self.init_grid()
def reset(self):
self.grid = self.init_grid()
# Initialize grid to be... |
ee97c0ecf20c8e69b713458b2ed938ef3734d1e7 | afroisalreadyinu/cython-samples | /sieve_python.py | 396 | 3.71875 | 4 | import math
def sieve(up_to):
if up_to < 2:
return []
primes = [True for _ in range(up_to+1)]
primes[0] = primes[1] = False
upper_limit = int(math.sqrt(up_to))
for i in range(2, upper_limit+1):
if not primes[i]:
continue
for j in range(2*i, up_to+1, i):
... |
92643861541f76a58a6a00af5557b95d9016f2c9 | xMrShadyx/SoftUni | /PB_EXAM/PB_Online_Exam_6_and_7_July_2019/05_PC_Game_Shop.py | 652 | 3.578125 | 4 | sold_games = int(input())
hearthstone = 0
fornite = 0
overwatch = 0
others = 0
for i in range(sold_games):
game_name = input()
if game_name == 'Hearthstone':
hearthstone += 1
elif game_name == 'Fornite':
fornite += 1
elif game_name == 'Overwatch':
overwatch += 1
elif game_... |
6091d2659f7299afb74e697abaf5ce0debbd1225 | LuckyJosh/advent-of-code-2017 | /src/aoc2017/day_5.py | 1,069 | 3.5625 | 4 | #! /usr/bin/env python
# encoding: utf-8
import click
import numpy as np
from .download_input import get_input
def memory_jumps_1(jumps):
# @documentation: All or parts of the documentation is missing!
jumps = [int(jump) for jump in jumps.split("\n")]
njumps = len(jumps)
i = 0
counter = 0
w... |
57719cd75291469b8684076f6b49fe8c4deb6547 | 07734willy/small_programs | /print_diamond/diamond.py | 388 | 3.78125 | 4 |
def tri(num):
return num * (num + 1) // 2
def make_list(size, depth=1):
shape = " " * (size - depth - 1)
shape += " ".join((str(tri(depth) - x) for x in range(depth)))
if depth == size:
return []
return make_list(size, depth + 1) + [shape]
def print_dia(size):
dia = make_list(size)
print("\n".join(dia[::-1]... |
b3e1d7f2400bd4147031ad2622b84369e7575a6a | zcYin/python | /prime_numbers.py | 337 | 3.640625 | 4 | def do_main():
for n in prime():
if n < 1000:
print(n)
else:
break
def _odd_iter():
n = 1
while True:
n = n + 2
yield n
def _not_divisble(n):
return lambda x: x % n > 0
def primes():
yield 2
it = _odd_iter
while True:
n = next(it)
yield n
it = filter(_not_divisble(n),it)
if __name__ == '_... |
3c46453cff8c7c368d44c37f48f2a86c1632594e | thangpro1242002/CTDL-GT | /CTDLGT_Python/BT06_Danhsachlienketdon.py | 1,001 | 4.03125 | 4 | class Node:
# Hàm khởi tạo dối tượng node
def __init__(self, data):
self.data = data # Gán dữ liệu
self.next = None # Khởi tạo tiếp theo là null
# Lớp Danh sách được liên kết chứa một đối tượng Node
class LinkedList:
# Hàm khởi tạo head
def __init__(self):
sel... |
3cb0fab844f10b3d2ea7ff56a7c51f2a8036e716 | ibbur/LPTHW | /3.py | 1,853 | 4.5625 | 5 | #This line will print to screen the quoted statement
print "I will now count my chickens:"
#This line with print to screen the word Hens and the solution to the math problem
print "Hens", 25.0 + 30.0/6.0
#This line will print to screen the word roosters and the solution to the math problem
print "Roosters", 100.0 - 2... |
1e53ae1d7827fdd4acef80df83b5a75964606dd7 | thienlongtran/Beginning-Small-Projects | /Python For Everybody Class - Autograder/Excercise 2.3.py | 148 | 3.796875 | 4 | # This first line is provided for you
hrs = input("Enter Hours:")
pay = input("Enter Pay:")
print("Pay: {0}".format(float(hrs) * float(pay))) |
0ec5d97f0a44659c9e28bd80f3a8d2f4654dd6b9 | atozzini/CursoPythonPentest | /PycharmProjects/ExerciciosGrupo/exercicio121.py | 369 | 4.0625 | 4 | mensagem = "\nDigite 'sair' para fechar o programa"
mensagem += "\nDigita alguma coisa ai: "
textoUsuario = ""
while textoUsuario != 'sair':
textoUsuario = raw_input(mensagem)
print(textoUsuario)
# neste exercicio o usuario digita uma mensagem e o while verifica se o que ele digitou
# e a palavra 'sair' se f... |
d73f584cf93c7ad768e13562ff6da145c3bd4e62 | sandeepbaldawa/Programming-Concepts-Python | /trees/tree_height_parent_array.py | 1,615 | 3.984375 | 4 | '''
Task. You are given a description of a rooted tree. Your task is to compute and output its height. Recall
that the height of a (rooted) tree is the maximum depth of a node, or the maximum distance from a
leaf to the root. You are given an arbitrary tree, not necessarily a binary tree.
Input:
5
4 -1 4 1 1
Output:
3... |
ffc348d94287c45cdbfb715e98ad7802992f993a | chenshanghao/RestartJobHunting | /Cracking The Coding Interview/Chapter_1/3.URLify/mySolution.py | 520 | 3.71875 | 4 | class Solution:
def checkPermutation(self, s1: str, length: int) -> str:
'''function replaces single spaces with %20 and removes trailing spaces'''
new_index = len(s1)
for i in reversed(range(length)):
if s1[i] == ' ':
# Replace spaces
s1[new_inde... |
e24e564f6d777fe3a0128cc8faf22c7de3d85e37 | mitul-s/webcrawler | /general.py | 2,439 | 3.71875 | 4 | # Allows you to create directories
import os
def create_project_dir(directory):
if not os.path.exists(directory):
print('Creating project ' + directory)
os.makedirs(directory)
# create_project_dir('mitul')
# Only one URL given to the crawler
# The queue and files already crawled are needed
#... |
ed4389b718c29d3ca2413a1601f5632562a96555 | feiyanshiren/myAcm | /t000011.py | 223 | 3.609375 | 4 | t = int(input())
for i in range(t):
n = int(input())
d = ""
o = ""
for j in range(1, n + 1, 2):
d = d + str(j) + " "
o = o + str(j + 1) + " "
print(d)
print(o)
print()
|
d6d18960ea39b72f72487b9ce209638397bb2a06 | Vanditg/Leetcode | /Leetcode-June-Challenge/Problem - 9/AcceptedSolution.py | 1,107 | 3.78125 | 4 | ##==================================
## Leetcode June Challenge
## Username: Vanditg
## Year: 2020
## Problem:9
## Problem Name: Is Subsequence
##===================================
#
#Given a string s and a string t, check if s is subsequence of t.
#
#A subsequence of a string is a new string which is formed from the... |
b64762f11e077012fcef707ec4d320b4e76fcf93 | leonnuxy/Miscellaneous | /longestSubstring.py | 852 | 3.5 | 4 | class Solution(object):
def lengthOfLongestSubstring(self, s):
# Creating a set to store the last positions of occurrence
seen = {}
max_len = 0
# starting the inital point of window to index 0
start = 0
for end in range(len(s)):
... |
29c4dc202f838227cc6a073c4c5a6006b6dc471e | SajinKowserSK/algorithms-practice | /Grokking Coding Interview/P6 - In Place Reversal of LL /reverse alternating k sub list.py | 1,794 | 4.03125 | 4 | from __future__ import print_function
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def print_list(self):
temp = self
while temp is not None:
print(temp.value, end=" ")
temp = temp.next
print()
def reverse_alternate_k_elements(head, k):
... |
359dbe864699f98da54d2f1476bfdfeb0644c10b | HuangZengPei/LeetCode | /Middle/Que95不同的二叉搜索树.py | 969 | 3.796875 | 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 generateTrees(self, n):
"""
:type n: int
:rtype: List[TreeNode]
"""
def gener... |
a9a1bc3a76264b2815f96840334825d7b10eccdc | dennysmiranda/weightConverter | /venv/weightConverter.py | 261 | 4.03125 | 4 | weight = int(input("How much do you weight? "))
unit = input("L(bs) or K(bs): ")
if unit.upper() == "L":
converter = weight * 0.45
print(f'You weigh {converter} kilos.')
else:
converter = weight / 0.45
print(f'You weight {converter} pounds.')
|
fe07ca7de12e690fcfd0a060b54ab19768dab14a | megannguyen6898/dataminingcourse | /practice1-monty hall.py | 2,650 | 4.03125 | 4 | import random
#Write a function that is a door not having a prize (the host knows) and is not the player choice so it will be opened
def open_non_prize_door(host, player_choice, num_doors):
i = 0
while i == host or i == player_choice:
i = (i+1)%num_doors
return i
#Write a function what happens if ... |
365c6ab46d762e868906a5eef5f6fa8985d278ad | sivatoms/Python_DataStructures | /Queue_Using_Stack.py | 1,453 | 4.375 | 4 | # Queue is an Abract Data structure
# It follows a particular particular order in which operations are performed
# The order is First In First Out (FIFO)
# the difference between a Stack and Queue is in removing. In stack we remove the item the most recently added, in Queue, we remove the item at first
class Queue:
... |
e295078c819a6089b144d4603b124b2e409e80ee | drozdzu88/Python_examples | /Zadanie_7.3.py | 211 | 3.625 | 4 | number = input("Podaj proszę dowolną liczbę: ")
number = int(number)
if number % 10 == 0:
print(f"Liczba {number} jest podzielna przez 10")
else:
print(f"Liczba {number} nie jest podzielna przez 10") |
3e52d652a556d00e82ec241a48873d7823abebd9 | holken/forward-filtering-based-robot-localization | /mainprogram.py | 8,726 | 4.125 | 4 | """
This exercise is concerned with filtering in an environment with no landmarks. Consider a vacuum robot in an empty room, represented by an n×m rectangular grid. The robot’s
location is hidden; the only evidence available to the observer is a noisy location sensor that
gives an approximation to the robot’s location.... |
32022ae2ae12ef2c51adc401db04994c8b3e22c9 | karanmalh0tra/python-coding | /MergeTwoSortedArrays/mergetwosortedarrays.py | 714 | 3.875 | 4 | def mergeSortedArrays(arr1,arr2):
len1 = len(arr1)
len2 = len(arr2)
i = 0
j = 0
arr = []
while((i<len1) and (j<len2)):
if arr1[i] < arr2[j]:
arr.append(arr1[i])
i = i + 1
else:
arr.append(arr2[j])
j = j + 1
while i<len1:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.