blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
0540da63be24bacc364eb65870cb7248f4d20b94 | dan-sf/leetcode | /climb_stairs.py | 1,345 | 3.96875 | 4 | """ Problem statement: https://leetcode.com/problems/climbing-stairs/ """
class Solution(object):
def climbStairs(self, n):
""" Iterative solution using the fibonacci sequence """
fib = [0,1,2]
if n <= len(fib)-1:
return fib[n]
for i in range(3, n):
current ... |
733e5ccb5bf37077c33127a0c95a8cef87e6eb6f | wahid999/Pythonforbegainer | /ifelse.py | 321 | 4.09375 | 4 | import os
os.system('clear')
#**************Assignment operator*************
#*************** CONDITIONAL STATEMENT **********************
#*************** IF / ELSE / ELIF **********************
num = 5
if (num > 10):
print ("Your Number is greater then 10")
else:
print ("Number is not greater then 10")
... |
46755f2929afcf4127eca858990bc7ab3261c53a | paulorleal1991/prl1991 | /ex007_prl1991.py | 434 | 3.96875 | 4 | '___Curso_de_Python___'
'___Aluno_Paulo_R_Leal___'
'___Exercicio_007____'
print('')
print('_' *40)
print('Calculo de Nota Média')
print('Media para duas Notas')
print('_' *40)
print('')
n1 = float(input('Digite Nota 1: '))
n2 = float(input('Digite Nota 2: '))
m = (n1 + n2) / 2
print('#' *40)
print('A Media será {:.2f} ... |
917ccb14f7cf4ac0797ab55e28c8806c68552c69 | dablackwood/my_scripts_project_euler | /specific_solutions/project_euler_012a.py | 1,823 | 3.96875 | 4 | """The sequence of triangle numbers is generated by adding the natural numbers. So the 7^(th) triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
Let us list the factors of the first seven triangle numbers:
1: 1
3: 1,3
6: 1,2,... |
9e49ca7cfa853a1e27fce07f9a285c6aa8e1f12a | AdithyaYelloju/Data-Structures-in-Python | /py-datastructures/Stack.py | 1,133 | 3.671875 | 4 |
class Stack():
def __init__(self):
self.stack_list = []
def push(self, element):
self.stack_list.append(element)
def pop(self):
try:
return self.stack_list.pop(-1)
except IndexError as e:
raise EmptyStackException("Stack is empty, can't pop")
def clear(self):
del self.stack_list[:]
def displ... |
9a97324535b8c98c9559162b68b1c9a7012a0af0 | guidiamond/password_manager | /zip/zip_manager.py | 1,305 | 3.578125 | 4 | import os
from os import path
from zipfile import ZipFile
import ruamel.std.zipfile as ruamzip
class ZipManager:
def __init__(self):
self.directory = 'password/'
self.zip_location = os.path.join(self.directory, 'password.zip')
def check_for_zip(self):
if path.exists(self.zip_location):... |
889bc6c844f4d6d09176df5de4554ddbd9440d0f | GM3D/CheckIO | /Home/MostWantedLetter/most_wanted_letter.py | 524 | 3.6875 | 4 | def checkio(s):
s = s.lower()
hist = [s.count(chr(c)) for c in xrange(ord('a'), ord('z'))]
max_count = 0
max_char = 'a'
for i in xrange(len(hist)):
if hist[i] > max_count:
max_count = hist[i]
max_char = chr(ord('a') + i)
return max_char
if __name__ == '__main__':... |
02d2a374db6a4dce8da7681b16197f627716e5dd | jakehz/Algorithmic-Questions | /reverseLinkedList3.py | 869 | 4 | 4 | # Definition for singly-linked list.
from typing import List
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def makeList(linked: List[int]) -> ListNode:
head = None
prev = None
curr = None
for v in linked:
if prev == None:
head = Li... |
43749a267ffb987a4b3e2359da61ce4181597e3b | Shimada666/LeetCode | /python/1207. 独一无二的出现次数.py | 511 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
:author: Shimada666
:url: https://github.com/shimada666
:copyright: © 2019 Shimada666 <Shimada666@foxmail.com>
:license: MIT, see LICENSE for more details.
"""
from typing import List
from collections import Counter
class Solution:
def uniqueOccurrences(self, arr: List[... |
c0721b7ad8b1b8b85e2bd2f681c6b67a5290a60a | edu-athensoft/stem1401python_student | /py200325_python1/py200529/stem1401_python_homework_15_ken.py | 1,439 | 4.21875 | 4 | """
For May 29th, 2020.
stem1401_python_homework_15_ken
Quiz 10.
"""
# Question 2.
product = 1
for number in range(2,21,2):
product *=number
print(number)
print(product)
# Question 3
average_score = 0
total = 0
nb_A_students = 0
student_score_list = (
("Marie", 85),
("Phoebe", 78),
("Sabrina", ... |
56c2507e3711fc5b00a178d6a110de730bbf3f8c | GaneshKulkarni1999/python | /gradient.py | 657 | 4 | 4 | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
def gradient_descent(x,y):
m_curr = b_curr = 0
rate = 0.01
n = len(x)
plt.scatter(x,y,color='red',marker='+',linewidth='5')
plt.xlabel('area')
plt.ylabel('prices')
for i in range(10):
y_predicted = m_curr * x + b_... |
3f290c4fadcd674a0982f4ad3c1783bb84d4396b | nesteves/introcs | /scripts/introcs/test_palindrome.py | 901 | 4.125 | 4 | __author__ = 'nunoe'
def is_palindrome(s):
""" Tests a string to find out if it is or not a palindrome
:param s: str, given String to be tested
:return: True if s is a palindrome, false if it is not
"""
def to_char(s):
""" Converts a given string into a list of lower case characters
... |
74220cbe6235b57dc1479f97eb486f636c5b54bb | zepetto7065/study_codingTest | /5주차/풀이/지혜수_15828번.py | 360 | 3.609375 | 4 | # small(50점)과 large(50점)로 나뉘어 있는데 점수 산정 기준을 모르겠습니다.
from collections import deque
deque = deque()
buffer = int(input())
while(True):
k=int(input())
if k == -1:
break
elif k == 0:
deque.popleft()
else:
deque.append(k)
if (deque):
for n in deque:
print(n, end=" ")
else:
print('empty') |
e9f922893a265a9ac294ba075ee09872c9ccb7b4 | neptunun/GlobalAlHubPythonCourse | /Fınal_Project.py | 1,112 | 3.96875 | 4 |
class Employees():
def __init__(self,name,age):
self.name=name
self.age=age
self.lang=set()
def add_language(self):
language=input("Please enter language that you can speak")
self.lang.add(language)
return self.lang
def who_am_I(self):
... |
15e66669690fbc6b16888bd821e2db72bd7e9cdd | Viniciusmgm/aula_processamento_info | /Listas_de_Exercício/lista4.py | 1,618 | 4 | 4 | #Exercício 1
"""
def matriz_zeros(nlin, ncol):
M_zeros = list()
for i in range(nlin):
linha = list()
for j in range(ncol):
linha.append(0)
M_zeros.append(linha)
return M_zeros
def transposta(M):
nlin = len(M)
ncol = len(M[0])
Mt = matriz_zeros(nlin, ncol)
for i in range(ncol):
for j... |
d31ac61eed53a8fe0a5d3da8ed548b0086b6d3e1 | taroooyan/2015_nock100 | /Chapter1/08.py | 645 | 3.765625 | 4 | # coidng: UTF-8
def cipher(string, mode):
if mode == "encode":
clipt_text = []
for s in string:
if s.islower():
clipt_text += chr(219-ord(s))
else:
clipt_text += s
return clipt_text
else:
text = []
for s in string:
... |
637f572c004cfe74b5fa5793dd276bec1c168310 | Panzl/PythonClass2016 | /listExamples/Password.py | 254 | 3.9375 | 4 | passwords = ['aaargh', 'fjfjkdg', 'qwerty']
while True:
print('Please enter the password')
userPassword = input()
if userPassword in passwords:
break
else:
print('Incorrect password!')
print('Access granted!')
|
1e4b637f6f2ba0f502b11b2b877b5e27f4a5da82 | CristianRP/Learning-Python | /B/pascal.py | 812 | 4.0625 | 4 | #!/usr/bin/env python3
# -*- coding:utf8 -*-
def draw_triangulo_pascal(n):
list = [[1], [1, 1]]
for i in range(1, n):
values_linea = [1]
for j in range(0, len(list[i]) - 1):
values_linea.extend([list[i][j] + list[i][j + 1]])
values_linea += [1]
list.append(values_lin... |
cb685a2bd765131bb5c5cf627b06d33a251e2540 | jhglick/comp120-fa21-lab6 | /permutations.py | 1,826 | 3.953125 | 4 | # File: permutations.py
# Author: COMP 120 class
# Date: October 12, 2021
# Description: Contains a function to return a list containing
# all permutations of a parameter list.
def permutations(lst):
"""
Return list containing all permutations of the list lst.
"""
pass # Replace this with your impl... |
2b2e89b23fbed3a18d49bafe010a6e5400a3128c | Sch1257/EGE | /261.py | 833 | 3.859375 | 4 | def f(n):
"""
Функция, которая получает на входе число и возращает уже приобразованное число по правилам
:param n:
:return преобразованное число :
"""
bin_n = bin(n)[2:] # превращаем в двоичную форму
index_last_0 = bin_n.rfind("0") # получаем индекс последнего 0
if index_last_0 != -1:
... |
cee642f394b4fd45f47ab49ba7c1699f64d6827a | rconover06/Logic-Design-1309 | /ch3/3-2_turtle2_expanded.py | 444 | 3.875 | 4 | # Raul Conover
import turtle
wn = turtle.Screen()
wn.bgcolor(str(input("Enter a background color:"))) # Set window background color
wn.title("Hello, Tess!") # Set the window title
tess = turtle.Turtle()
tess.color(str(input("Enter a pen color:"))) # Tell tess to change color
tess.pensize(int(input("Ent... |
1d2eba598be743bd742be0cfb4ae39283490f220 | LuisUTEC/Soluciones-Hackerrank-RUN | /Python Basico/Clase 02/PB0112 - Bienvenida.py | 150 | 3.515625 | 4 | nombre=input()
edad=int(input())
print("Hola "+nombre+" y bienvenido a RUN.")
print("Con "+str(edad)+" años deberias tener "+str(edad+22)+" kilos.")
|
c8f922e46f7efd75d823efd7bbac0ba8724838ac | lnogueir/interview-prep | /problems/binaryTreeLevelTraversal.py | 1,756 | 4.03125 | 4 | '''
Prompt:
Given the root of a binary tree, return the level order traversal of its nodes' values (from left to right, level by level).
'''
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = rig... |
23afa51d4d1c9a180adc48dc3bd79d7fcb6e8c82 | zaky9/zaky | /8.4.2019/1.py | 634 | 3.734375 | 4 | # Comment 1 (trial 1)
# Print trial (single line comment)
print(123456)
print('halo')
print("test 1 2 3")
print (3+3)
print("3"+"3")
'''
comment buat multi line cooment
paragraph yang banyak
'''
# # variables: variable yng contain values
# contoh:
# 2 mangga = Rp 15.000
# 2x = 15000
# x= 7500
u = "8" # string
v = 3... |
fd9ae042e7a8c2dd58355fdc9442aebfacfea403 | AndrewSouthpaw/Python | /Python Intro Coursera Class/Week 8 code/Sets structure.py | 3,552 | 4.53125 | 5 | # Sets
# Structure
# Sets are groups of things without order. Sets are defined
# using parenthesis, brackets, and the word 'set'. Sets
# can contain any type of object, but in general all
# objects in a set are of the same type. A set cannot
# however contain data structures (lists, tuples, or
# other sets... |
1eef3d61cf9f8d59e6fee704e1d1660d8487c550 | nekobon/misc | /vectoring.py | 1,360 | 4.21875 | 4 | '''
Simple 3D vector class.
'''
import math
class vec3(object):
'''3D vector class for easy access x,y,z'''
__slots__=['x','y','z']
def __init__(self,x,y,z):
'''x y z can be any type'''
self.x=x
self.y=y
self.z=z
def __add__(self,other):
'''element wise addition'''
x = self.x+other.x
y = self.y+o... |
f7c9c8be7affb365954ec06ba7e71ca5342fbb64 | inverseTrig/leet_code | /200_number_of_islands.py | 863 | 3.515625 | 4 | from typing import List
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
island_count = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == "1":
self.dfs(grid, i, j)
island_count += 1
... |
fec395cc7a492b9e8a65427e76cbf4ad6f4d08d6 | RajAman01/Codes | /venv/FrequencyOfWord.py | 312 | 4.125 | 4 | def CountFreq(str):
str = str.split()
str2 = []
for i in str:
if i not in str2:
str2.append(i)
for i in range(0, len(str2)):
print("The Frequency of Word",str2[i],"", str.count(str2[i]))
str = 'apple mango apple orange orange apple guava mango mango'
CountFreq(str)
|
d002ff326cc0325864e060a5d3c8ea4b76eae8a0 | Dan-Teles/URI_JUDGE | /2712 - Rodízio Veicular.py | 661 | 3.96875 | 4 | import re
n = int(input())
for i in range(n):
s = input()
if len(s) == 8:
if s[3] == '-' and re.match("[A-Z]", s[:3]) and re.match("[0-9]", s[4:]):
if s[-1] == '1' or s[-1] == '2':
print('MONDAY')
elif s[-1] == '3' or s[-1] == '4':
print... |
a5eec3f8561d9d1703a37690569675ad912b9828 | mingo-doer/AlgorithmQIUZHAO | /Week_02/课内实战/104 二叉树的最大深度.py | 1,621 | 3.6875 | 4 | # 给定一个二叉树,找出其最大深度。
#
# 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
#
# 说明: 叶子节点是指没有子节点的节点。
#
# 示例:
# 给定二叉树 [3,9,20,null,null,15,7],
#
# 3
# / \
# 9 20
# / \
# 15 7
#
# 返回它的最大深度 3 。
# Related Topics 树 深度优先搜索
# 👍 615 👎 0
# leetcode submit region begin(Prohibit modification and deletion)
# Definition for a... |
0ca67ee48e610c256d57c6049d80c99069fce851 | jacaceresf/basketball-reference | /basketball-ref.py | 1,920 | 3.796875 | 4 | import streamlit as st
import pandas as pd
import base64
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
st.title('This is my first streamlit app test')
#we use triple quotes when the string has more than a line
st.markdown("""
This is my first streamlit's app
* **Name:** Jorge Caceres
* **I... |
c97f3c54b845aa8aec6004efb8aed35d72f14236 | EarlMatthews/principlescomputing | /week0/test.py | 2,538 | 4.21875 | 4 | #! /usr/bin/python
#-*- coding=utf-8 -*-
def appendsums(lst):
"""
Repeatedly append the sum of the current last three elements of lst to lst.
"""
for i in range(25):
last3 = lst[-3:]
sum3 = reduce(lambda x,y: x+y, last3, 0)
lst.append(sum3)
sum_three = [0, 1, 2]
appendsums(sum_three)
p... |
8d894d737879371ff1c71cfdf65938767e745be1 | MuhammedSafarov/E-Olymp-solutions | /8876-Integer.py | 71 | 3.5625 | 4 | n = float(input())
if n==int(n):
print('Ok')
else:
print('No')
|
565eb3ef4c11339568666e5927f2420fd1b01bca | jefethibes/Aulas | /Python/Python/ExeLista21.py | 2,288 | 3.90625 | 4 | """Crie uma classe chamada Ingresso que possui um valor em reais e um método
imprimeValor().
a. crie uma classe VIP, que herda Ingresso e possui um valor adicional. Crie um
método que retorne o valor do ingresso VIP (com o adicional incluído).
b. crie uma classe Normal, que herda Ingresso e possui um método que imprime... |
ff986e3f4a9b96ef05a2becaa5f84724f36094ba | KlavierCat/CoderDojo-Python | /lesson2/drawFlowers2.py | 859 | 4.15625 | 4 | # import dependencies
from turtle import *
import random
# define a function to draw flowers
def flower (col, length, angle):
pendown()
times = int(360/(180-angle))
for sides in range (0, times):
color (col)
fd (length)
rt (angle)
penup()
penup()
speed("fast")
# call the flower function with some... |
e476258409fcf39f61295faab6984fb1e67352a3 | magedu-pythons/python-14 | /dongyanwen/week6/02-tuple-list.py | 271 | 3.9375 | 4 | #!/usr/bin/env python
#.Author:Dyw
# 现有两元祖 (('a'),('b')),(('c'),('d')) ,请使用Python中的匿名函数生成列表 [ {'a':'c'},{'b':'d'}]
a="{0[0]}:{1[0]},{0[1]}:{1[1]}".format((('a'),('b')),(('c'),('d')))
print((lambda i,j : [{i} ,{j}] )(i=a[:3],j=a[4:])) |
bcd1c261c12469b8ccac4a9165dbedd0d476c129 | puloma-k/GirlsWhoCode2018 | /PythonPractice/hangman.py | 860 | 4.03125 | 4 | #ask for word input
while True:
word = input("Enter a word: ")
if word.isalpha() == True:
break
else:
continue
#convert word to lowercase
word = word.lower()
#print empty word
currentWord = []
for letter in word:
currentWord.append("_")
lettersGuessed = []
triesLeft = 6
while triesLe... |
fdad783f316259750e3063e763a3a2989bec55cc | SufiyanDilawarkhan/ga-learner-dsmp-repo | /Python-Basics---Student-Management-System/code.py | 1,014 | 3.75 | 4 | # --------------
# Code starts here
class_1 = ['Geoffrey Hinton', 'Andrew Ng', 'Sebastian Raschka', 'Yoshua Bengio']
class_2 = ['Hilary Mason', 'Carla Gentry', 'Corinna Cortes']
new_class = class_1 + class_2
print(new_class)
new_class.append('Peter Warden')
print(new_class)
new_class.remove('Carla Gentry')
prin... |
aad567b17bd2c48c175b4f6453d75af7a2b6aae5 | mdhvkothari/Python-Program | /hackerrank/dict.py | 152 | 3.546875 | 4 | a=int(input("Enter number:"))
b=[]
for i in range(2,a+1):
for j in range(2,a+1):
d=i**j
b.append(d)
c=set(b)
print(len(c))
|
f3c81b3a1884c07b8ec74c3b3d27f4686877cdbf | BIGRIG4/herd-immunity | /person.py | 1,897 | 3.5 | 4 | import random
random.seed(42)
from virus import Virus
class Person(object):
def __init__(self, _id, is_vaccinated, infection=None):
self._id = _id # int
self.is_alive = True # boolean
self.is_vaccinated = is_vaccinated # boolean
self.infection = infection # Virus object or Non... |
05da0459f5aa539b443250a9020eeb8d024d39b9 | fsMateus/exerciciosPython | /fase3/exercicio17.py | 240 | 3.875 | 4 | n = int(input('digite o valor: '))
fat = n
for i in range(1, n):
fat *= (n-i)
print('Fatorial de {} é {}'.format(n, fat))
# origin = n
# while n > 1:
# fat *= n-1
# n -= 1
# print('Fatorial de {} é {}'.format(origin, fat)) |
402477df488dce8dbcb5f8cf0d02178c05faaa78 | zhaoly12/dataStructAlgorithmPythonVer | /methodForNetwork.py | 14,973 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Sep 25 15:29:59 2020
@author: 86156
"""
from network import network
from tree import tree
# activity on vertex for a directed acyclic network
def AOV(g):
'''
activity on vertex:
to work out the sequence of doing tasks
firstly, choose the vertexes who... |
eb9604a3fefbb82c00c813a723383b75355a4a7d | joara123/PyCharm | /untitled11.py | 575 | 3.515625 | 4 | import sys
input = sys.stdin.readline
def solve(string):
stack = []
for ch in string:
if len(stack) == 0 and ch == ')' :
return 'No'
if ch == '(':
stack.append(ch)
else:
if stack[-1] == '(':
stack.pop()
... |
6221d128e6cef73a24615873e7666db4b2fac274 | totemw/algorithm | /CTCI/Trees and Graphs/first common ancestor.py | 1,746 | 3.65625 | 4 | """
find the first common ancestor of two nodes in a binary tree
Avoid storing additional nodes in a data structure
"""
# with parent ref
class Node:
def __init__(self, val, left, right):
self.val = val
self.left = left
self.right = right
self.parent = None
if ... |
7ceeb57178089c182e8f9a9b4b48d0b8babbb2c2 | MacBook-Pro-gala/supinfo.python | /homework/homework2017.11.14.py | 246 | 3.78125 | 4 | s=[]
sn = 0
s.extend(input('give me a world'))
vowels=('a','e','i','o','u','A','E','I','O','U')
def vowelsNumber(sn):
for x in vowels:
sn = sn + s .count(x)
return sn
print('you have ',vowelsNumber(sn),'vowels worlds') |
ee4105202a80eb4a086246234dc84f0c8e224b79 | zhangxu0307/leetcode_solutions | /2.py | 1,522 | 3.796875 | 4 | #encoding=utf-8
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
... |
0e9c7832311088de18660c6a09957b2ea1ed9626 | AvinashKumar999/sorting-algorithm-visualizer | /merge.py | 1,653 | 3.734375 | 4 | import time
def merge_sort(data, drawbar, delaytime):
merge_algo(data, 0, len(data)-1, drawbar, delaytime)
def merge_algo(data, left, right, drawbar, delaytime):
if left < right:
mid = (left+right)//2
merge_algo(data, left, mid, drawbar, delaytime)
merge_algo(data, mid+1, ... |
7154df0a7a902fd2deda41aab6caaef872ae77a6 | Aboli0710/python-lab | /student.py | 155 | 3.5625 | 4 |
d={}
x=int(input())
for i in range(x):
n=input('enter the name')
g=int(input('enter the gr no.'))
b=input('enter the branch')
d[g]=(n,b)
print(d)
|
65301fddc9ecda8472312cf7cc33d3658846c341 | nofamily/python-edu | /lotto.py | 457 | 3.703125 | 4 | import random
# 로또번호는 1~46, 총 6개 당첨번호
today=[]
for i in range(0,6):
today=random.sample(range(1,47),6)
# today.append(random.randrange(1,47,1))
# for j in range(0,i):
# if today[j]== today[i]:
# today[i]=random.randrange(1,47,1)
print('오늘의 추천 번호는 ')
print(today)
# print(str(today[0]... |
d414c4521af3f2d4354f4af998e1ee9e86842e60 | bashwork/project-euler | /041/041.py | 553 | 3.625 | 4 | '''
9 and 8 cannot be prime because
>>> any(a for a in [9,8] if (sum(range(a)) % 3) != 0)
False
'''
import math
from itertools import permutations
def compose(n):
result = 0
for k,v in enumerate(n):
result += v*10**k
return result
def is_prime(n):
if n == 2: return True
if n < 2 or n % 2 =... |
9b0d17d9356f42a1372cd60924c2e021e6b44655 | alexandremerched/learning-python | /PythonExercicios/World 2/ex063.py | 201 | 3.84375 | 4 | n = int(input("Digite um número inteiro: "))
F1 = Ft = 0
F2 = 1
print("0 -> 1 ->", end=' ')
while n != 0:
Ft = F1 + F2
F1 = F2
F2 = Ft
n -= 1
print("{} ->".format(Ft), end=' ')
|
c25d007ac619601ee6833baa22440ffb08a6d4f5 | fergatica/python | /fraction2.py | 3,207 | 4.125 | 4 | class Fraction:
""" This class represents one single fraction that consists of
numerator and denominator """
def __init__(self, numerator, denominator):
"""
Constructor. Checks that the numerator and denominator are of
correct type and initializes them.
:param numerator:... |
d72adf6afca33f845ebd179bcff07620dca59b7b | jjennings955/MAPS | /processing/communication.py | 4,018 | 3.703125 | 4 | import struct
import serial
def analog_to_psi(analog):
"""
Convert an analog value to a PSI value, using formula from data sheet
:param analog: The analog value (between 0 and 1023)
:return: The PSI value
"""
voltage = analog/1023.0*5.0
return (voltage + 5.0*0.004)/(5.0*0.004)*0.145037738
... |
e529698e430a08144048a2892501ac617a441b93 | gkeeth/aoc2020 | /day21.py | 3,514 | 3.65625 | 4 | #! /usr/bin/env python
import re
from collections import defaultdict
class Food(object):
def __init__(self, line):
match = re.match("^(.*) \(contains (.*)\)$", line.replace(",", ""))
self.ingredients = set(match.groups()[0].split())
self.allergens = set(match.groups()[1].split()... |
911b0dbd789d7b7a3926fd0569b7183602859d63 | chrisyli/coding_problems | /624. Maximum Distance in Arrays.py | 1,920 | 4.28125 | 4 | '''
Given m arrays, and each array is sorted in ascending order. Now you can pick up two integers from two different arrays (each array picks one) and calculate the distance. We define the distance between two integers a and b to be their absolute difference |a-b|. Your task is to find the maximum distance.
Example... |
f2eeea1075b33fe364ce3a90e22227fefb1d3465 | ramonvaleriano/python- | /Livros/Introdução à Programação - 500 Algoritmos resolvidos/Capitulo 2/Exercicios 2a/Algoritmo75_Lea48.py | 245 | 3.71875 | 4 | # Program: Algoritmo75_Lea48.py
# Author: Ramon R. Valeriano
# Description:
# Developed: 15/03/2020 - 22:20
# Updated:
weight = float(input("Enter with the weight: "))
grams = weight*100
new_grams = grams + ((grams*12)/100)
print(grams)
print(new_grams)
|
d0ae9ed7633c3830e82ccf32b53efaf3f5cdcfb5 | paix26875/DEDprogram | /calibration/time_average/trimming.py | 886 | 3.578125 | 4 | """
画像を特定範囲でトリミングする
"""
import cv2
def img_trimming(img, top, bottom, left, right):
"""
画像をトリミングする
Parameters
----------
img : numpy
トリミングしたい画像のnumpy配列
top : int
トリミング範囲の上端
bottom : int
トリミング範囲の下端
left : int
トリミング範囲の左端
right : int
トリミング範囲の右端
... |
ad287d0f899615c6bc9d13c813b564133633c76a | shen-huang/selfteaching-python-camp | /19100301/Xuzhengfu/d5_exercise_array.py | 917 | 4.21875 | 4 | # 三、数组操作,进制转换
# 1、……
# 2、将数组 [0,1,2,3,4,5,6,7,8,9] 翻转
numbers = [0,1,2,3,4,5,6,7,8,9]
numbers.reverse()
# 3、翻转后的数组拼接成字符串
num_str_list = [str(num_str) for num_str in numbers] # 使用list comprehension生成列表
numbers_str = "".join(num_str_list) # Join all items in the list "num_str_list" into the stri... |
925ebb34da2db6ae0ec09fc37e81ff6dfce80729 | fpeterek/SPR-Solutions | /10152.py | 1,247 | 3.609375 | 4 | # Shell sort - https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1093
def read_list(size):
lst = []
for i in range(size):
lst.append(input())
return lst
def out_of_place(lst, offset, length):
oop = []
# print('Offset: ', offset)
for i in ... |
25157660597127f0f6cb0cb6e410ecad46467c7c | pompeiifreckles/improved-octo-disco | /Lecture_2/conditions.py | 142 | 4.15625 | 4 | n = int(input("Number: "))
if n > 0:
print("n is positive")
elif n < 0:
print("n is negative")
else:
print("n is equal to zero")
|
194a0ac94faa22a90c1fb46cf343b30ffd6922ac | OKirill/algo_and_structures_python | /Lesson_3/7.py | 968 | 3.875 | 4 | """
7. В одномерном массиве целых чисел определить два наименьших элемента.
Они могут быть как равны между собой (оба являться минимальными),
так и различаться.
"""
from random import random
N = int(input("Укажите длину массива: "))
arr = []
for i in range(N):
arr.append(int(random() * 10))
print(f"{arr[i]:4... |
7950c3479f1a9257a7951c9d5c78fed9c9fc49b2 | JuliyaVovk/PythonLessons | /Lesson3/task3.py | 1,036 | 4.09375 | 4 | """
Реализовать функцию my_func(),
которая принимает три позиционных аргумента,
и возвращает сумму наибольших двух аргументов.
"""
def my_func(a, b, c):
if a >= b >= c or b >= a >= c:
return a + b
if a >= c >= b or c >= a >= b:
return a + c
if c >= b >= a or b >= c >= a:
return b +... |
60169bf29bb766cb1a0dadf7ae941d354cd319c7 | anthony-marino/ramapo | /source/courses/cmps130/exercises/pe22/pe22.py | 845 | 4.21875 | 4 | ##############################################################################
# Programming Excercise 22
#
# Write a function that accepts a list of integers and returns
# the first even number in the list.
#
# Raise an exception if the list does not have an even number.
##############################################... |
5630fcf82aca7a6cc3fb9d1252fba887cb317952 | XinyueZ/some-python-codes | /machine_learning/softmax.py | 508 | 3.515625 | 4 | import matplotlib.pyplot as plt
import numpy as np
from numpy import max as maxium
from numpy import sum as summary
from numpy import arange, exp, ones_like, vstack
def softmax(x):
"""Compute softmax values for each sets of scores in x."""
exp_x = exp(x - maxium(x))
return exp_x / summary(exp_x, axis = 0)... |
00c5e50399ab3ea7958bd7838d2c4b75fdc6c1d0 | apoorvgupta21/Python | /Sorting Algo/Bubble_Sort.py | 419 | 3.53125 | 4 | # Bubble Sort Program:
# Algo
# Compare the first two element of an array, if arr[0] < arr[1], ignore otherwise swap them.
a = [4, 9, 2, 3, 38, 22, 83, 19, 76, 5, 1, 45]
l = len(a)
print(l)
i = 0
j = 0
temp = 0
#for j in range(j, l-1):
while(j < l):
i = 0
for i in range(i, l-1):
if(a[i] < a[i+1]):
i = i + 1
... |
46e2cdd0768eeedb1081544eee293854861de43b | navatha1234/DSP-LAB | /lab-2_program for addition of sin and cos.py | 540 | 3.65625 | 4 | import matplotlib.pyplot as plt
import numpy as a
f=input("enter the frequency")
fs=input("enter the sampling frequency")
x=a.arange(0,50,0.5)
y=a.sin(2*a.pi*f*x/fs)
plt.subplot(3,1,1)
plt.plot(x,y)
plt.title('sinwave')
plt.xlabel('time')
plt.ylabel('amplitude')
b=a.cos(2*a.pi*f*x/fs)
plt.subplot(3,1,2)
pl... |
d5cfeb0e35767bf1a1d758f27d793fdfb3d4ec26 | MrHamdulay/csc3-capstone | /examples/data/Assignment_2/mtsmol017/question1.py | 263 | 4.34375 | 4 | #A program to determine whether it is a leap year or not.
x=(input("Enter a year:\n"))
x=int(eval(x))
if (x%400==0) or (x%4==0) and (x%100!=0):
print(x,"is a leap year.")
else:
print(x,"is not a leap year.") |
d5c01a55f805696e1ed514e45bda91afbf04d8b9 | itsrbpandit/fuck-coding-interviews | /data_structures/linked_lists/tests/test_singly_linked_list.py | 4,833 | 3.75 | 4 | # coding: utf-8
import unittest
from data_structures.linked_lists.singly_linked_list import LinkedList
from data_structures.linked_lists.singly_linked_list import ListNode
class TestCase(unittest.TestCase):
def setUp(self):
self.empty_linked_list = LinkedList()
self.node_0 = ListNode('nobody exi... |
a4fcbe85cf0f4a447ad994002cf2022e76863f1a | AdamZhouSE/pythonHomework | /Code/CodeRecords/2856/47937/283706.py | 600 | 3.515625 | 4 | a=input()
b=input()
#print(a)
#print(b)
if(a=="4" and b=="10 4"):
c=input()
d=input()
e=input()
#print(e)
#print(d)
#print(c)
if(c=="15 1" and d=="19 3" and e=="20 1"):
print(4)
#print(4)
elif(a=="35" and b=="1 7"):
print(10)
elif(a=="40" and b=="1 1"):
print(2)
elif(a==... |
b17136fe34f816f61b86951b878b3bb0c4f14ed1 | Yue-Du/Leetcode | /70.py | 548 | 3.796875 | 4 | class Solution:
def climbStairs(self, n: int) -> int:
return self.climb_iter(n,1,2)
def climb_iter(self, stairs, climb1, climb2):
if stairs == 1:
return climb1
if stairs == 2:
return climb2
return self.climb_iter(stairs-1,climb1, climb2)+ self. climb_iter(... |
60bd73a6881b591e031ef11f93aabe48f8e09a8e | sasank89/python-getting-started | /variables.py | 787 | 4.34375 | 4 | first_name = 'Sasank'
last_name = 'Kalipatnapu'
print (first_name+last_name)
print('Hello '+ first_name + ' '+ last_name)
#Functions on strings
sentence = 'This sentence is exciting me'
print(sentence.upper())
print(sentence.lower())
print(sentence.capitalize())
print(sentence.count('e'))
#combining both the top con... |
883761e30f150aab0fc7e96b0d24ca257a331467 | mwingter/Calculo-Numerico | /pythonCurso/ex10_2.py | 907 | 4.15625 | 4 | #10.2 Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages.
#You can pull the hour out from the 'From ' line by finding the time and then splitting the string a second time using a colon.
#From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008... |
a994daa5ebabcdd05a3ae13aa732c55d53107473 | nie-ed/ot-harjoitustyo | /src/sprites/blocks.py | 812 | 3.90625 | 4 | import pygame
class Blocks(pygame.sprite.Sprite):
"""Class to create one Block for a piece.
Args:
pygame (Sprite): Class for game objects.
"""
def __init__(self, X=0, Y=0, l=29, h=29, color=None): # pylint: disable=invalid-name
"""Constructor for class. Creates a Block object, with ... |
419872a7f3fd3f97f6377410a621e2b8ccd242fc | saubbie23/Bootcamp-Work | /python_stack/python/fundamentals/underscore.py | 1,299 | 3.734375 | 4 | class Underscore:
def map(self, iterable, callback):
# your code here
for i in range(len(iterable)):
iterable[i] = callback(iterable[i])
return iterable
def find(self, iterable, callback):
# your code here
for i in range(len(iterable)):
if call... |
6a80126e08d240d50c847f297955612cb0be75b8 | AshishOhri/simplenn | /simple neural net (sigmoid).py | 2,012 | 4.34375 | 4 | ''' Building a basic neural network'''
import numpy as np
# We use the sigmoid function as the activation function
def sigmoid_function(L):
return 1/(1+np.exp(-L))
# Derivative (slope)=y/x
def deriv(L):
return L*(1-L)
# START READING FROM HERE
# Take input and output
X=np.array([[0,0,1],[0,1... |
80b6affbfc6c238a46cdd53028de674a26fdb232 | andreagrandi/pyngfm | /pyngfm/util.py | 600 | 3.671875 | 4 | def convert_boolean(value):
if isinstance(value, bool):
return value
try:
value = int(value)
if value == 0:
return False
return True
except ValueError:
# couldn't cast string value as an integer
pass
if isinstance(value, unicode):
value... |
1c1f9f5421324e66b8aec20c918da5ee28aa8c99 | rcanolorente/PythonLearning | /Python learning/Theory/ErrorHandling.py | 839 | 4.28125 | 4 | #When code in a try clause causes an error, the program execution immediately moves to the code in the except clause.
# After running that code, the execution continues as normal. The output of the previous program is as follows:
def spam(divideBy):
try:
return 42 / divideBy
except ZeroDivisionError:
... |
727900f3e6e7e2f32d7fd871dd09ce0f6058274e | rodrigoferrazazevedo/dojo-python | /filter.regular.lambda.py | 247 | 3.59375 | 4 | #regular
def is_multiple_of_five(n):
return not n % 5
def get_multiples_of_five(n):
return list(filter(is_multiple_of_five, range(n)))
print(get_multiples_of_five(10))
#lambda
n = 10
print(list(filter(lambda k: not k % 5, range(n))))
|
250ea647860f493fdd0f930cde5ec743a4f472d7 | Vicky1756/Identify-the-type-of-triangle-with-python | /python assignment.py | 2,437 | 3.6875 | 4 | import math
import random
iso = 0
sca = 0
equ = 0
ri = 0
ob = 0
ac = 0
def isValidTriangle(a, b, c):
if (a + b <= c) or (b + c <= a) or (c + a <= b):
return False
else:
return True
def getPerimeter(a, b, c):
perim = a + b + c
return (str(perim))
def getArea(a, b, c):
... |
fd980e5d50af5adf76db0fcd1fbf25dbe5ab230a | abdibogor/The-Bad-Tutorial | /05_Python/14_The ELSE Statement/else.py | 282 | 3.796875 | 4 | """
myvar=50
if myvar<100:
print("You are short of being 100 percent")
else:
print("you are at your best")
print("Good Bye!")
"""
myvar=150
if myvar<100:
print("You are short of being 100 percent")
else:
print("you are at your best")
print("Good Bye!")
|
31d6cc617bfdc6a3ce2cf2f7a692154701f7f9bc | kittu401/Db_operations | /database.py | 3,340 | 3.921875 | 4 | # importing required libraries
import pymysql
import time
# Creating a Database connection
storage = input("Enter your database name :")
table = input("Enter your table name")
db = pymysql.connect(host='localhost', database=storage, user='', passwd='')
cursor = db.cursor()
print("Connected to " + storage)
# ... |
536c402ea5c5ddd09e96e95c115fd35d361372f6 | JohannesBuchner/pystrict3 | /tests/data23/recipe-66465.py | 1,110 | 4.28125 | 4 | #!/usr/bin/env python
__version__ = "1.1"
"""combination.py-- Efficient recursive functions for printing the
combination of the selected number of characters from the specified string.
Can generate unique or all possible combinations.
"""
import sys
def printList(alist):
print(''.join(alist))
def printUniqueComb... |
569c49f3f35600c322fa746a3b7f049d42433b11 | HaiseX7/Data-Visualization | /sitka_highs_lows.py | 794 | 3.578125 | 4 | import csv
from matplotlib import pyplot as plt
from datetime import datetime
filename = 'data/sitka_weather_2018_simple.csv'
with open(filename) as f:
reader = csv.reader(f)
header = next(reader)
print(header)
highs, lows, dates = [], [], []
for row in reader:
date = datetime.strptime(row[2], '%Y-%m-%d')
... |
0331f14827f588fbd89bded14b46e5e323c1f51b | LorenzoVaralo/ExerciciosCursoEmVideo | /Mundo 2/Ex071.py | 762 | 4.09375 | 4 | #Crie um programa que sinule o funcionamento de um caixa eletronico. No inicio, pergunte ao usuario
# qual será o valor a ser sacado(numero inteiro) e o programa vai informar quantas cedulas de cada
# valor serão entregues. Obs. Considere que o caixa possui cedulas de R$50, R$20,R$10 e R$1
print('=' * 30 + '\nBANCO... |
a967ccc903bc469bbddee4ff887bcb23ba783f48 | sajibhaskaran/Algorithms | /ChunkList/chunk_list.py | 603 | 3.984375 | 4 | # Purpuse : Write a function that splits an array (first argument) into groups the length
# : of size (second argument) and returns them as a two-dimensional array.
#
# Authour : Saji Bhaskaran
def chunk_list(lst, size):
result = []
num = 0
slice_len = size
length = int(len(lst)/size)
for i... |
90c0df3b71a8224d9e8107a8d41be1cdd5df8c22 | SachinPitale/Python3 | /Python-2021/17.Functions/5.fun-with-arg-return-values.py | 685 | 3.9375 | 4 | """
def get_add(a,b):
result=a+b
#print(result)
#return None # when use reture None it pass none value to other function.
return result # if you want to pass variable value to other function must use return and variable name (ex: return variable)
def main():
a=eval(input("Enter your first number :... |
d6a3dc44d814b0d18e7d94b318305ad2499a9775 | madasuvamsi/AlgorithmsInPython | /MoveElementToEnd.py | 204 | 3.59375 | 4 | array=[1, 2, 2, 5, 4]
tomove=2
i=0
j=len(array)-1
while i<j:
while i<j and array[j]==tomove:
j-=1
if array[i]==tomove:
array[i], array[j]=array[j],array[i]
i+=1
print(array) |
9c9de33651c2f72b1fc9384fc19be68de8b07234 | drewtuley/UniTeasers | /Jan_26_2021_v2.py | 2,166 | 3.5625 | 4 | import copy
import re
class Vertex(object):
def __init__(self, node1, node2):
self.node1 = node1
self.node2 = node2
def __hash__(self):
return hash(self.node1.letter) ^ hash(self.node2.letter)
def __repr__(self):
return f'{self.node1},{self.node2}'
class Node(object):
... |
f31f20d0e859b06fffd7d23d1e8c9b9cc754bc80 | CezaryKlimczuk/SplidditAD | /project/project_voter.py | 4,227 | 3.90625 | 4 | from project.project import MAX_AVAILABLE_VOTES
class ProjectVoter:
"""
The ProjectVoter is responsible for querying the user for each members votes on a project.
If the user provides invalid input, it keeps querying the user for valid input until a Project has been voted on fully.
"""
def __init... |
e286f09a164ba9b7ed552b57d8a2f07dc24d5f0d | GuruSaju/NineManMorrisSCRUM | /morris/morris_game/Game_board.py | 9,693 | 3.5 | 4 | '''
Created on Oct 3, 2015
@author: speng
'''
from Position import Position
from Game_state import Game_state
class Game_board(object):
'''
classdocs
'''
__coord_list = [(0,0), (0,3), (0,6),
(1,1), (1,3), (1,5),
(2,2), (2,3), (2,4),
(3,0), (3... |
4606bbed2250b0b52b09a961d02ee6e9c3391746 | GabrielAbdul/holbertonschool-higher_level_programming | /0x06-python-classes/3-square.py | 771 | 4.46875 | 4 | #!/usr/bin/python3
"""
This module defines a class Square
Attribues:
private class attribute size
public instance method area()
"""
class Square:
""" Class of square that has no size
Attributes:
__size (int): size of square
"""
def __init__(self, size=0):
"""
... |
275912dbd200ced42fc50e7ac216be7b38ba40e8 | wojtekminda/Python3_Trainings | /SMG_classwork/12_zadanie_operator_modulo.py | 566 | 3.65625 | 4 | words = list()
print("Tworzymy liste slow")
print("(Jezeli wypisales juz wszystkie -> nacisnij Enter)\n")
print("Podaj slowo")
word = input()
while word != "":
words.append(word)
print("Podaj slowo")
word = input()
print("Powiedz po ile slow w linii chcesz wypisywac")
number_of_words = input()
int_number... |
93a7b4e1ca50a08d6afa275507725d5915960167 | AlexPasechnuy/Python_labs_2.1 | /Lab11/Genealogy2.py | 527 | 3.96875 | 4 | def isparent(son, father):
if son == father:
return True
if d[son] not in d:
return False
elif d[son] == father:
return True
else:
return isparent(d[son], father)
n = int(input())
d = dict()
for i in range(n-1):
son, father = input().split()
d[son] = father
d['P... |
a93c0429685a8c17d0b15be3a51bdae0dd0e20a5 | ccjoness/CG_StudentWork | /Garrett/Week3/1.py | 359 | 4.25 | 4 | # If we list all the natural numbers below 10 that are multiples of 3 or 5, we get
# 3, 5, 6 and 9. The sum of these multiples is 23.
#
# Find the sum of all the multiples of 3 or 5 below 1000.
def sum_mults(num):
total = 0
for x in range(num):
if x % 5 == 0 or x % 3 == 0:
total += x
... |
f29c19070c7dd59c21bdbde4b2a781572737cbbe | Mengeroshi/Python-Crash-Course-exercises | /chapter_7/7.8_deli.py | 332 | 3.78125 | 4 | sandwich_orders = ["rosbif", "pastrani", "sailor", "runza"]
finished_sanwiches = []
while sandwich_orders:
made_sandwich = sandwich_orders.pop()
print(f"I made a {made_sandwich} sandwich")
finished_sanwiches.append(made_sandwich)
print("\nFinished Sanwiches:")
for sandwich in finished_sanwiches:
pri... |
4c01270f000a200b12b19688bebfd6d4a0a8ea8e | nickjmartinez/robotics-project | /scripts/Node.py | 2,222 | 3.84375 | 4 | #!/usr/bin/env python
#class to store the values for the a* algorithm
class Node:
def __init__(self,x,y,parent,goal):
self.x = x
self.y = y
self.parent = parent
self.goal = goal
self.f, self.g, self.h = self.calculateValues()
self.parent = None
self.children = []
#calculate the g,h, and then f values ... |
060add36bd05e0409b33f9a9b52d3e781f56e3fe | gtzampanakis/projeuler | /44.py | 501 | 3.546875 | 4 | def pentag():
n = 3
while True:
yield n, 3*n-2, n*(3*n-1)/2
n += 1
pentagonals_encountered = set()
sums_encountered = { }
for n, dn, Pn in pentag():
if Pn in sums_encountered:
print sums_encountered[Pn]
print sums_encountered[Pn][0] - sums_encountered[Pn][1]
break
for pp in pentagonals_encountered:
Pm_... |
13b61a6a78b43fde424c0534a61f0e9969cb3f3e | suraj95/Python-Practice | /test_accountant.py | 617 | 3.828125 | 4 | import unittest
from accountant import Accountant
class TestAccountant(unittest.TestCase):
"""Tests for class Accountant"""
def setUp(self):
self.acc = Accountant(0) # Balance will be 0 at the start of every test case
def test_initial_balance(self):
self.assertEqual(self.acc.balance,0)
self.acc = Accountant... |
20c18cd9161e8979f434c08557066eea7be56a81 | dt-ajayi/pyqt5_youtube_playlist | /hello.py | 972 | 3.703125 | 4 | import PyQt5.QtWidgets as qtw
import PyQt5.QtGui as qtg
class MainWindow(qtw.QWidget):
def __init__(self):
super().__init__()
# Add a title
self.setWindowTitle("Hello World!!")
# Set Vertical layout
self.setLayout(qtw.QVBoxLayout())
# Create A Label
my_label = qtw.QLabel("Hello World! What's Your Name... |
defb5f54bb72450938c071c0f0dc6dbff3ad4824 | jpaulopd/IFB | /202001/lp2/projetoJogo/jogos.py | 511 | 3.640625 | 4 | import adivinhacao
import forca
def escolhe_jogo():
print("*********************************")
print("********Escolha seu jogo !*******")
print("*********************************")
print("***(1) Forca ou (2) Adivinhação**")
jogo = int(input("Qual jogos?"))
if( jogo == 2 ):
print("Joga... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.