blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
797947e164ac884712c7ebe61e0edf154ad98e7b | hanghang177/Tone | /test/voicerectest.py | 1,732 | 3.640625 | 4 | import speech_recognition as sr
import pyowm
from gtts import gTTS
import os
owm = pyowm.OWM('bd5e378503939ddaee76f12ad7a97608')
observation = owm.weather_at_place('Urbana, IL')
w = observation.get_weather()
r = sr.Recognizer()
m = sr.Microphone()
str1 = 'weather'
try:
print("A moment of silence, please...")... |
fa084f887cca4e3b64322fc826149d1fa0718adf | JohnnyQuinn/list-and-loops-tutorial | /list_loops.py | 405 | 3.5625 | 4 | songs = ["ROCKSTAR", "Do It", "For The Night"]
print(songs[0])
print(songs[2])
print(songs[1:3])
songs[2] = "Papa's Got a Brand New Bag"
print(songs)
songs.extend(["Slow Burn", "Stuck in the Middle With You", "Sweet Time"])
del songs[0]
print(songs)
animals =["Gorilla", "Goose", "Giraffe"]
animals.append("Grou... |
7bb65eb465765d8ad4223146b129cd3dd13123e8 | serdardurmus/hjelperfunksjoner_v1.1 | /python/while_loops/Fibonacci.py | 495 | 3.953125 | 4 | # Fibonacci
antall = int(input("Skriv det siste nummeret av Fibonacci-listen du vil se: "))
listeen= []
a = 1
b = 1
while True:
if a > antall: break
listeen.append(a)
if b > antall : break
listeen.append(b)
a = a+b
b = a+b
print(listeen)
if listeen[-1] != antall : print("{} er ikke et fibonacc... |
b0bad1cc54b7b0de873281a81b8765dbd0bff504 | fnava621/euler | /python/p5.py | 306 | 3.625 | 4 | from itertools import count
def smallest_mul(x, y):
lst = range(x, y+1)
for num in count(2520, 2520):
if all(num % x == 0 for x in lst):
smallest = num
break
print smallest
if __name__ == '__main__':
answer = smallest_mul(1,20)
print answer
|
bee3ae57443d32acea5a2d98c6cfec14a30296a2 | jstanbridge/DPWP | /dynamic-site/page.py | 4,216 | 3.65625 | 4 | """
James Stanbridge
26 Feb 2014
Dynamic Site
"""
#create the Page class, which is a generic class to create the basis of our htm layout
class Page(object):
def __init__(self):
#define head attribute to contain all head html info
self._head = '''
<!DOCTYPE HTML>
<html>
<head>
<title>D... |
399268d9b2f412a3d2dff0ae638e5fbb970f5516 | brizjose/JBCodingDojo | /python_stack/Python/dictionaries.py | 1,453 | 4.6875 | 5 | #DICTIONARIES
#Recap: lists are [a,b,c] tuples are (a,b,c)
#dictionaries are { "key":"value", "key":"value" }
#keys must be unique
#creating dictionaries:
#a) literal notation:
weekend = {"Sun": "Sunday", "Sat": "Saturday"}
#b) create an empty dictionary then add values:
capitals = {}
capitals["svk"] = "Brati... |
72c4200a56fce55030c2b72d3b8b723c2bf81951 | rodcoelho/python-practice | /archived_problems/palindrome_alphanumeric.py | 996 | 4.09375 | 4 | #!/usr/bin/env python3
# Jarvis is weak in computing palindromes for Alphanumeric characters.
# While Ironman is busy fighting Thanos, he needs to activate sonic punch but Jarvis is stuck in computing palindromes.
# You are given a string containing the alphanumeric character. Find whether the string is palindrome or ... |
fc21f244892431df9f3fbeb0cb3891d30fbc30c0 | naveen701526/Python-Pojects | /Number_Guessing/number_game.py | 1,043 | 3.765625 | 4 | import os, platform, time
def clear():
if 'linux' in platform.system().lower():
os.system('clear')
elif 'windows' in platform.system().lower():
os.system('cls')
def number_game(value, number):
'''Starts the game of Guessing the right number.'''
clear()
chances = value
i = 0
... |
35a184ee694a9fffa4e0dd5652678c584c60d013 | sonssy/Test | /pythonwork/sqlliteTest/sqlliteTest02.py | 679 | 3.546875 | 4 | import sqlite3
conn=sqlite3.connect('./sqlliteTest/example.db')
c=conn.cursor()
'''
t=("RHAT",)
sql='SELECT * FROM stocks WHERE symbol=?'
c.execute(sql, t)#?에 해당하는거를 sql, 뒤쪽으로 쭉 붙여주면됨
print(c.fetchone())#one은 하나만
purchases=[('2019-03-10','BUY','IBM',1000,45.00),
('2019-03-11','BUY','IBM',1000,75.00),
... |
3a1a949e30c73d462ee1093c7a0ca313e289dce9 | AdamStein593/JazzNetworksPython | /PythonQ3.py | 186 | 3.71875 | 4 | def list_sum(integers):
sum = 0;
for i in range(len(integers)):
integer = integers[i]
if(integer % 2 == 0):
sum += integer * integer
return sum;
|
41c84f64ea87a34ab0ca62b89c4c436b39477414 | IAmAbszol/DailyProgrammingChallenges | /Problem_31/solution.py | 736 | 4.03125 | 4 | import unittest
'''
O(n*m) time complexity
O(1) space complexity
'''
def solve(str1, str2):
longest, shortest = (str1, str2) if len(str1) > len(str2) else (str1, str1)
# Preprocess string
sim_count = 0
for i, l in enumerate(longest):
count = 0
for j, s in enumerate(shortest):
if (i + j) >= len(longest):... |
c4e516c20cb1df8192bd76bee069a11ec92eaa9b | weiguangjiayou/LeetCode | /LeetCode/LeetCode653two-sum-iv-input-is-a-bst.py | 1,572 | 3.8125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/10/17 7:50 PM
# @Author : Slade
# @File : LeetCode653two-sum-iv-input-is-a-bst.py
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None... |
47cbbe338577e8419f73673d0262b9e61d5e6dbf | leeyoonjee/python-study | /level1/ex1.py | 1,126 | 3.5 | 4 | #HelloWorld 파스칼표기법
#helloWorld 낙타표기법
#hello_world 언더스코어(파이썬)
# 타입 추론
# 모든 것이 오브젝트
# 인터프리터
# 1. 숫자
a=1
b=1.2
c=4e5
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
#연산자 +, -, *, /, %
e = 3
f =32
print(e**f) #**제곱
print(e//f) #몫
print(4 % 3) #나머지
#문자열, 쌍따옴표""와 홑따옴표'' 구분 안함
#''' '''
s1= "안녕... |
2475e391716a191f4fd72610f9a7278d8e4839a0 | polyglotm/coding-dojo | /coding-challange/leetcode/easy/~2022-02-28/1370-increasing-decreasing-string/1370-increasing-decreasing-string.py | 1,877 | 3.734375 | 4 | """
1370-increasing-decreasing-string
leetcode/easy/1370. Increasing Decreasing String
Difficulty: easy
URL: https://leetcode.com/problems/increasing-decreasing-string/
"""
class Solution:
def sortString(self, s: str) -> str:
s = sorted(s)
result = []
delete_list = []
while len(s):... |
bbbc34ab3687d59ae5656f0c8c38ce0447756fbd | naveensr89/sound_classification_methods | /src/utils.py | 1,104 | 3.765625 | 4 | import os
def get_path_fname_ext(full_file_path):
"""Return path, filename without extension and extension
ex: get_path_fname_ext('/Users/example/test.txt')
('/Users/example', 'test', '.txt')"""
path, filename = os.path.split(full_file_path)
fname, ext = os.path.splitext(filename)
retu... |
2e0873ceb1a3a78460081198354265e208a432c3 | XavRobo/Pyton_vrac | /adventofcode/day_2.py | 454 | 3.546875 | 4 | import re
with open("inputs/input2.txt", "r", encoding="utf-8") as g:
data = list(map(str, g.readlines()))
count = 0
#PART ONE
# for d in data:
# line = re.split('-|: | ',d[:-1])
# if(int(line[0]) <= line[3].count(line[2]) <= int(line[1])):
# count += 1
#PART TWO
for d in data:
line = re.spl... |
3240ed2a2152fb8a70c99b497cffb2acd0d1f4eb | yjh8806/python-2019-July | /4일/07.포매팅/02.포매팅.py | 871 | 3.859375 | 4 | #2개 이상의 값을 대입할때
#%(값1, 값2) : %뒤에 괄호를 열고 데이터를 넣어준다.
#차례대로 포맷코드에 대입된다.
num = 5
disert = "cakes"
print("I eat %s %s"%(num, disert))
print("\n===포매팅을 이용한 정렬===")
#%s 사이에 양수를 적어주면 우측정렬
#음수를 적으면 좌측정렬
print("%10s%5s"%("name","age"))
print("="*20)
print("%10s%5s"%("jinwoo","30"))
print("%10s%5s"%("dongyul","30"))... |
6a419424f1bea6adde883cb7cb651a05deb9f1fc | Fendo5242/Semana6lab | /Problema 1/problema3.py | 398 | 4.09375 | 4 | angulo = int(input("Ingrese el numero del angulo: "))
if angulo == 0:
print("nulo")
elif 0 < angulo < 90:
print("agudo")
elif angulo == 90:
print("recto")
elif 90 < angulo < 180:
print("obtuso")
elif angulo == 180:
print("llano")
elif 180 < angulo < 360:
print("concavo")
elif ... |
50c0f18cb020a0e29048865fb300971d97f43039 | Mehmet-Erdem-Akin/For-and-While-Loop | /while_döngüsü_1.py | 981 | 3.953125 | 4 | """
x = 0 # 1 yazarsak 1 den balar
while x <= 100:
print(x)
x = x + 1 # veya x += 1 yazabiliriz
"""
# while dngs ile for gibi bir deiken tanmlayarak koyduumuz arta ulaana kadar yazdrma ilemi yapabiliriz.
"""
x = 1
while x <= 100:
if x % 2 == 0: # x in 2 ye blmnden kalan 0 a eit ise x i yazdr. Tek sayla... |
d029745f341bebcaf4f56a4f91a2d46c27f21a97 | anilpolineni/Django-Training-Program_Batch-5 | /Django_workshop/myName.py | 105 | 3.671875 | 4 | class myName:
def fname(name):
return('Hello '+name)
obj = myName
print(obj.fname("Bobby"))
|
3ea38c4d2fdc9760d455e89818cc1ccd848b556d | SilentM/formatJSONFile | /challenge.py | 3,749 | 4.15625 | 4 | import json
import re
# returns true if any number is contained in the given string
def hasNumbers(input_string):
return any(char.isdigit() for char in input_string)
# returns max integer present in a string uses regex
def getLargestInteger(string):
result = re.findall("-?[0-9]+", string)
return max(map(... |
3311b2a1b009316750b83c775e620466652e23f6 | iceeye7gabi/FII | /An3/Sem1/Python/Lab1/Ex4.py | 481 | 3.796875 | 4 | # Ex_4
# Write a function that receives two strings as parameters and returns the number of occurrences of the first character string in the second.
string1 = input("First string: ")
string2 = input("Second string: ")
def ex4 (string1, string2):
string1 = string1.lower()
string2 = string2.lower()
... |
319ac6d5ac4047c15525216fe1c344d93d53572d | MAqilSadik/LatihanChapter6 | /statistik.py | 570 | 3.59375 | 4 | #sum
def sum (*bilangan):
sum = 0
for data in bilangan :
sum += data
return sum
#average
def average (*bilangan):
sum = 0
i = 0
for data in bilangan :
sum += data
i += 1
rata2 = sum/i
return rata2
#maks
def maks (*bilangan):
maksimum = 0
for data in... |
8f1e3edb0aa68b10add9f26b8676b245e45a2ed2 | alexpm94/MITx-6.00.1x-Alejandro-Pe-a | /Final Exam/ex2.py | 427 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 22 12:37:16 2018
@author: alexpm94
"""
L=[3, 9,9, 5, 3, 5,1,9]
def largest_odd_times(L):
newL=[-1]+sorted(L)
count=1
for i in range(len(newL)-1):
if newL[-1-i]==newL[-2-i]:
count+=1
else:
if ... |
22c7f25c97525b9d579d8f4761fe411236ef05e1 | theycallmemac/Project-Euler | /Problems 10-19/problem15.py | 467 | 3.59375 | 4 | def get_ways(num):
way = [1]
ways = 0
while ways < num:
i = 0
new_way = [1, 1]
while len(new_way) - 1 <= ways and i < len(way) - 1:
found_way = way[i] + way[i + 1]
new_way.insert(i + 1, found_way)
i += 1
way = new_way
ways += ... |
f6871f90ba5438d2f42d88d3db028d9c3eb9989f | brettchien/LeetCode | /88_MergeSortedArray.py | 1,526 | 3.625 | 4 | class Solution:
# @param {integer[]} nums1
# @param {integer} m
# @param {integer[]} nums2
# @param {integer} n
# @return {void} Do not return anything, modify nums1 in-place instead.
def merge(self, nums1, m, nums2, n):
print nums1, nums2
if m == 0:
for idx in range... |
25b6ef9f046bdbe3fd60f1ecd9b8b8f16b02bc2e | Pnickolas1/Code-Reps | /leetcode/min_cost_connect_all_points.py | 956 | 3.578125 | 4 |
"""
minimum cost to connect all points
MST - or Minimum Spanning Tree
- 1584 minimum cost to connect all points
prims algorithm
graph
heap (min Heap)
purpose, connect all nodes, DO NOT form a cycle
"""
import heapq
def min_cost_to_connect_all_points(points):
N = len(points)
adj = { i: ... |
6fcd5eeec1e3ef0c0408d5a8fd5b470bb51a7710 | WarrenK-design/Python-GUI-Projects | /useful_code/message.py | 559 | 3.875 | 4 | # THis is for pop up message boxes
# There are differnt ones we can create
# showinfo, showwarning, showerror, askquestion, askokcancel, askyesno
from tkinter import *
from PIL import ImageTk,Image
from tkinter import messagebox
root = Tk()
root.title('Radio Buttons')
def popup():
response = messagebox.askyesno("... |
8c97bb357de896788cacaec7fd66b37fc49f5e43 | avichai321/hackeru-lessons-part1-python | /שיעור 6/demo.py | 313 | 3.6875 | 4 | x = 10
y = x
x = 50
print(x)
print(y)
def lista():
list1 = ['avicii', 'avichai', 'bamba', 'avig']
list2 = list1
list2.append('mha')
print(list1)
print(list2)
def plus():
num1 = int(input('Enter num1'))
num2 = int(input('Enter num2'))
print( num1 + num2 )
return num1 + num2 |
70465059ff665c0c5a154992b56af3d00ac8f7f5 | jtoledouag/cspp10 | /unit1/jtoledo_calcFtoC.py | 145 | 4.0625 | 4 | Fahrenheit = input("enter a number in fahrenheit:")
celsius=(Fahrenheit-32)/1.8
print(str(Fahrenheit) + " F is equal to " + str(celsius) + " C ") |
b4ce64d43cbe0f28d85a6e0a93c7d596bcbde210 | ralba1997/The-final-countdown | /plot_time_sorting.py | 3,150 | 3.546875 | 4 | import timeit
import random
import matplotlib.pyplot as plt
def rand(N):
l=[random.randint(0,1000000) for i in range(N)]
return l
size_10=rand(10)
size_100=rand(100)
size_1000=rand(1000)
size_10000=rand(10000)
size_100000=rand(100000)
print(size_10)
print(size_100)
print(size_1000)
print(size_10000)
print(... |
9ad9be8e210130f2d3c21212557d41defa46af24 | shiki7/Atcoder | /yahoo-procon2018-qual/A.py | 114 | 3.671875 | 4 | S = input()
if S[:3] != "yah":
print('NO')
exit()
if S[3] == S[4]:
print('YES')
else:
print('NO')
|
bd07c6940765ad798eb15bc7ce4c05d4d14b1405 | KartikJha/code-quiver | /python/comp-coding/quicksort.py | 419 | 3.828125 | 4 | def quicksort(arr, low, high):
if (low < high):
p = partition(arr, low, high)
quicksort(arr, low, p - 1)
quicksort(arr, p + 1, high)
def partition(arr, low, high):
i = low - 1
for j in range(low, high + 1):
if arr[j] < arr[high]:
i = i + 1
arr[i], arr[j] = arr[j], arr[i]
arr[i + 1], arr[high] = arr[h... |
924dc731d677e05cf3c0a42e1b571e92c93a780c | hjk1995/crackingthecodinginterview | /python/py1_isunique.py | 298 | 3.875 | 4 | inputstr="abca"
# Is Unique: Implement an algorithm to determine if a string has all unique characters. What if you
# cannot use additional data structures?
def isUnique(str):
if(len(str)!=len(set(str))):
return False
else:
return True
bool=isUnique(inputstr)
print(bool) |
b67edd375c561a58e796387d4b80c4797bbfc0f2 | JosephAntonioo/RGWEBCAMPPUB20212 | /RGWEBCAMPPUB20212/modulos/extrator_POSICAO.py | 4,244 | 3.953125 | 4 | pontos = []
posicoes = []
# Para verificar se os dedos estão dobrados ou esticados,
# esta função faz a comparação da distancia entre pontos
# e adiciona a lista de posições se o dedo está esticado, acima ou abaixo da base do dedo se está próximo ou afastado do dedo subsequente.
# Para o dedo polegar, precis... |
fc8ba420b2c22edcee8ce857ad059e28dddf11aa | MathiasLuo/PySchool | /dbutil.py | 2,885 | 3.953125 | 4 | import sqlite3
CREART_TABLE = "CREATE TABLE STU (ID INTEGER AUTO_INCREMENT PRIMARY KEY,NAME CHAR(100),STUID CHAR(50),MAJOR CHAR(150),SEX CHAR(50),COLLEGE CHAR(50));"
conn = sqlite3.connect("students.db")
# cursor = conn.cursor()
# cursor.execute(CREART_TABLE)
# cursor.close()
# conn.commit()
# conn.close()
def in... |
4d2caa5acee1ad54f7b70680c69263a2fff64a30 | eqgriffin/class-work | /newword.py | 62 | 3.890625 | 4 | word = 'banana'
newword = word.replace('a','o')
print(newword) |
64cf71da0b6d94d32d16e7357a1982784e609cc4 | ziadawn/codeguild-class | /Python Assignments/Week 1 Python/lab11-average-numbers.py | 1,013 | 4.40625 | 4 | '''
Lab 11: Average Numbers
Version 1: Calculate the average of a given list.
Version 2
Ask the user to enter the numbers one at a time, putting them into a list.
If the user enters 'done', then calculate and display the average.
The following code demonstrates how to add an element to the end of a list.
nums = []
... |
f24ed98bbaab7c0b69b1a7e8c38d5c428a80db4d | ChenuyuRick/data-structure | /002 Add Two Numbers.py | 1,375 | 3.6875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
head1 = l1
head2 = l2
fake_head = ListNode(None)
curr_node = fake_he... |
a0ab0195d0dabbfbca6bd9606e567e7ade9722dd | shoeffner/monty | /06_Packages/code/lecture/magicsquare_bt.py | 808 | 3.796875 | 4 | upright = (-1, 1)
down = (1, 0)
def init(order):
square = [[0] * order for i in range(order)]
square[0][order // 2] = 1
return square, (0, order // 2)
def solved(square):
for row in square:
if not all(row):
return False
return True
def magic(square, position, number=1):
... |
cbb605379bf7591f29f71a614dbc088de69c5afb | tapans/Algorithms-Puzzles-Challenges | /CTCI_6e/8.3_magic_index.py | 1,605 | 3.8125 | 4 | #!/usr/bin/python
import unittest
def get_magic_index_slow(A):
'''
Returns A magic index i in a sorted array A of distinct ints, -1 if it doesn't exist.
Magic Index is an index such that A[i] = i.Count of how many possible ways the child can run up the stairs
Time Complexity: O(n)
Space Complexity: O... |
a94cb57ada6068ff974b40508a2bdfef2ffff6e8 | AviGuner/thenewwall-flask | /message.py | 675 | 3.53125 | 4 | import sqlite3
class Message():
def __init__(self):
self.connection = sqlite3.connect('thenewwall.db')
self.cursor = self.connection.cursor()
def save(self, username, text):
query = "INSERT INTO messages (username, text) VALUES (?, ?)"
self.cursor.execute(query, (username, text))
self.connec... |
1dece8873ea1b83d65a7dd3fd777bf03b457aac4 | toyijiu/my_code | /compiler/pascal_compiler_demo/calc3.py | 3,246 | 3.828125 | 4 | '''
about the syntax demo code
'''
from enum import Enum
import numpy as np
class Type(Enum):
INTEGER = 'INTEGER'
PLUS = 'PLUS'
MINUS = 'MINUS'
EOF = 'EOF'
MUL = 'MUL'
DIV = 'DIV'
op_list = [[Type.PLUS,'+'],[Type.MINUS,'-'],[Type.MUL,'*'],[Type.DIV,'/']]
class Token(object):
def __init__(... |
ca6f66127013fd805c18e0d1f4d085a554e2dc76 | markuswesterlund/beetroot-lessons | /python_skola/Beetroot_Academy_Python/Lesson 10/lesson10task1.py | 357 | 3.75 | 4 | class Person:
def __init__(self, first_name, last_name, age):
self.first_name = first_name
self.last_name = last_name
self.age = age
def talk(self):
return f"Hello, my name is {self.first_name} {self.last_name} and I am {self.age} years old."
a_string = Person("Markus", "Weste... |
3c0dd4d92ee7565c99517ef5f59d87df4484992d | KrauserSan/CodeAbbey_SolutionSet | /src/bubble_sort.py | 580 | 3.59375 | 4 | '''
Created on Jun 9, 2017
@author: vivpa
'''
def swap(arr):
swaps = 0
for i in range(len(arr)-1):
if arr[i] > arr[i+1]:
temp = arr[i+1]
arr[i+1] = arr[i]
arr[i] = temp
swaps += 1
return swaps,arr
def main():
arr_size = input()
arr = ma... |
b99298af1802fa90301506eac43cc030eb4be27f | lfylfy027/MyQQ | /Dailywork/lc1518/lc1518_yyk.py | 538 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 28 23:53:19 2020
@author: 30480
"""
class Solution:
def numWaterBottles(numBottles: int, numExchange: int) :
bottle, ans = numBottles, numBottles
while bottle >= numExchange:
bottle -= numExchange
ans += 1
bottle +=... |
42b32861637e9498f5089bb508001db86109a2ff | Environmental-Informatics/03-working-with-files-in-python-huan1441 | /huan1441_Evaluate_Raccoon_Life.py | 3,875 | 3.578125 | 4 | # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#
# Name: ABE65100 Lab03 Evaluate_Raccoon_Life.py
#
# Purpose: Script to read the data file 2008Male00006.txt, process the data,
# and create a new output file called "Georges_life.txt".
#
# Author: Tao Huang (huan1441)
#
# ... |
efe5d07cdc719c8fb8f734db7e5ee1ac5a28b791 | jcockbain/ctci-solutions | /chapter-02/Q04_partition.py | 1,279 | 3.859375 | 4 | import unittest
class Node:
def __init__(self, val, next=None):
self.val = val
self.next = next
def partition(head, partition):
lowerHead = None
lowerEnd = None
upperHead = None
upperEnd = None
while head:
if head.val < partition:
if not lowerHead:
... |
a43f4254ca8a11ee20593e2ad2b60b6b897c51c0 | Eduflutter/EXE_python | /EX - 40.py | 503 | 3.734375 | 4 |
print('{:=^30}'.format(' \33[32mColégio Salvador\33[m '))
n1 = float(input('Primeira nota: '))
n2 = float(input('Segunda nota: '))
md = (n1+n2)/2
print('-=-'*7)
if md < 5.0:
print('\33[1;31m[{:^20}]\33[m'.format(' Reprovado '))
elif md >= 5.0 and md <= 6.9:
print('\33[1;35m[{:^20}]\33[m'.format(' Re... |
7223fca65f0ae3de6f02c8cbbdfb17827c4b8be6 | Ruia-ruia/Small-Tools | /atoi.py | 681 | 3.625 | 4 | def integer(x):
digits = list('0123456789')
found = list()
#correspond and preserve index of digit to string present in x string
for j in x:
i = 0
while i < len(digits):
if digits[i] == j:
found.append(i)
i += 1
final = 0;
... |
426ae20b29dc88ea568830c4c22b376db7e132a5 | cybelewang/leetcode-python | /code383RansomNote.py | 1,242 | 3.65625 | 4 | """
383 Ransom Note
Given an arbitrary ransom note string and another string containing letters from all the magazines,
write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.
Each letter in the magazine string can only be used once in ... |
9a8ac820c38af6e84c50d6ca3c60a3d357a814f4 | ViktorWase/TSP | /triangulation.py | 1,125 | 3.65625 | 4 | from copy import deepcopy, copy
class Point():
def __init__(self, pos, idx, neighs):
self.pos = pos
self.idx = idx
self.neighs = copy(neighs)
class Triangle():
def __init__(self, pnt_idxs):
self.pnt_idxs = copy(pnt_idxs)
class Triangulation():
def __init__(self, points):
self.n = len(points)
self.di... |
c63ae79f185a8c04be0ac8ea9b07501c52fbee22 | CIDARLAB/pyparchmint | /parchmint/port.py | 2,271 | 3.609375 | 4 | from typing import Dict, Optional
class Port:
"""Describes the port on a component"""
def __init__(
self,
label: Optional[str] = None,
layer: Optional[str] = None,
x: float = -1,
y: float = -1,
json_data: Optional[Dict] = None,
):
"""Creates a Compo... |
f4f38c7bacae6fe376a6d927017127348815815b | jenntang1/holberton-system_engineering-devops | /0x15-api/1-export_to_CSV.py | 2,346 | 3.5625 | 4 | #!/usr/bin/python3
""" Exports data into CSV format """
import csv
import requests
import sys
if __name__ == "__main__":
""" If second argument is an integer, then it's an employee id """
empl_id = sys.argv[1]
if empl_id.isdigit():
""" Gets EMPLOYEE_NAME """
empl_url = "https://jsonplac... |
bc6f22d56409714bb9c2671ab0381add50149c11 | gabriellaec/desoft-analise-exercicios | /backup/user_236/ch28_2019_03_08_14_47_12_668126.py | 113 | 3.828125 | 4 | a=float(input(quantos km/h))
if a>80:
b=(a-80)*5
return b
print ("você foi multado em R$ {0}".format(b)) |
094870e174d193487d83b03e5a2270ceff038abe | sainas/LeetCode | /24.swap-nodes-in-pairs.py | 2,522 | 3.765625 | 4 | #
# @lc app=leetcode id=24 lang=python3
#
# [24] Swap Nodes in Pairs
#
# https://leetcode.com/problems/swap-nodes-in-pairs/description/
#
# algorithms
# Medium (43.00%)
# Total Accepted: 284.2K
# Total Submissions: 656.8K
# Testcase Example: '[1,2,3,4]'
#
# Given a linked list, swap every two adjacent nodes and ret... |
c71fdea43d7b08da7c1e2951713004f6bf42fab0 | NWood-Git/other_challenge_questions | /hare_and_tortise_algorithim.py | 2,692 | 3.5625 | 4 |
# Hare and Tortise Algorithm
# https://www.youtube.com/watch?time_continue=1&v=-YiQZi3mLq0&feature=emb_title
# Use to dectect if a linked likst has a loop in a linked list
# ex: 0 -> 1 -> 2 -> 3 -> 4 -> 5 -> back to 2
# Tortise moves 1 node per iteration
# Hare moves 2 nodes per iteration
# Both start at 0. After 1... |
a6fe155f33cca7bda754a26f69f9980b66e19c17 | acelletti/codility_lessons_python | /lesson_4/max_counters.py | 1,410 | 3.71875 | 4 | """
Task Score: 100%
Complexity: O(N + M)
"""
def solution(N, A):
"""
This problem took me a good while to solve. The problem in itself is not
hard, but the description is not very clear. I had to read it several times
and even then, it took me a good few tries until I realised what it was
asking ... |
5bf0b548a81537bbe378c071df4c98fd387c2ee4 | sidcool1234/Code_For_Fun | /problem_set_one/problems.py | 671 | 4.03125 | 4 | # 1. Given a set of integers (distinct), find pairs which differ by a given integer k
def find_pairs_with_difference(input_set, difference):
sorted_set = sorted(input_set)
return [(value, value+difference) for value in sorted_set if value + difference in sorted_set]
def test_find_pairs_with_difference():
inp... |
be48c5bb90a2e12e6782e16dd5153ecb6a4d8d4d | bsamanvitha/Cryptanalysis_Project | /Code/complete_program.py | 7,735 | 3.90625 | 4 | # File name: Cryptanalysis_Project, complete_program
# Date created: 3/23/18
# Python v: 2.7
#!/usr/bin/python
'''
Book Cipher
'''
text = "SIERRA-ZERO-JULIET-SIX-YANKEE-ONE-ROMEO-PAPPA-EIGHT-KILO-FIVE-UNIFORM-XRAY-XXX-BRAVO-VICTOR-TWO-FOUR-TANGO-MIKE-OSCAR-HOTEL-DELTA-QUEBECK-FOXTROT-ALPHA-YYY-LIMA-INDIA-THREE... |
6f3ce548448195b84b6ae6ee9c1bda91ccb4cdba | neetiv/SelfTaughtPythonPrograms | /Functions Programming Puzzles.py | 629 | 3.890625 | 4 | print('''Functions: Programming Puzzles
''')
print('''#1: Mystery Code
''')
print(''' I think that when the code prints 'a' it will print the number 20, and when it prints 'b' it will print the number 0''')
print('''code test:
''')
a = abs(10)+abs(-10)
print(a)
b = abs(-10)+-10
print(b)
print('''
#2: Copying a Fi... |
78f60bd967983e341f6e8a89fb7e81c4e54ff3bd | q7h0u6h7/competition_coding | /street_numbers/street_numbers.py | 562 | 3.71875 | 4 |
from math import sqrt
from math import floor
def compute_sum(n, m, sum):
return n * n + n + m - m * m - 2 * sum
def print_house_nums(house_num):
sum = house_num * (house_num-1) / 2
n = floor(sqrt( (-1) * compute_sum(0, house_num+1, sum)))
if compute_sum(n, house_num+1, sum) == 0 and house_num < n:
print... |
298f6e095183e37b956e9c2485b05a1f49ed208e | ugaemi/algorithm | /leetcode/runningSum.py | 564 | 3.71875 | 4 | import unittest
class Solution:
def runningSum(self, nums):
i = 1
while i < len(nums):
nums[i] += nums[i - 1]
i += 1
return nums
class Test(unittest.TestCase):
def test_addStrings(self):
solution = Solution()
self.assertEqual(solution.runningSu... |
72fbbfe868ec5427eb7a76a11ea8d3ab72843988 | Jayesh598007/Python_tutorial | /Chap11_inheritence/02_single_inheritence.py | 584 | 3.75 | 4 | '''
Types of Inheritence:
1) single inheritence
2) miltiple inheritence
3) Multilevel inheritence
'''
# Single Inheritence
# it occurs when child class inherits only one/single base class
# parent ------> child1
class Employee:
company = "Google"
def showdetails(self):
print("This is an ... |
5748dc234dd9d125f25a170cb43af6d8dbbea319 | Govard9/my_projects_book | /Traveler_game(not finished).py | 6,378 | 3.5625 | 4 | import random
class Location:
COUNTRY = ['1) Россия'], ['2) Африка'], ['3) Испания'], ['4) Аргентина'], ['5) США']
COUNTRY_TELEPORT = [['1) Россия']], \
[['2) Африка']], \
[['3) Испания']], \
[['4) Аргентина']], \
[['5... |
6bb88423a1dc891cc5ec7838ebfaf55769ee0ace | Santkey/KoW | /a-38.py | 400 | 3.984375 | 4 | #skrócony operator if, inne zastosowanie else
#print("Prawda") if 5 > 2 else print("fałsz")
a = "Parzysta" if 10 % 2 == 0 else "nieparzysta" #mozna zwracać wartości string i int
print(a)
for i in range(10):
if i > 5:
continue
else:
print()
try:
a = 5/0
except ZeroDivisionError:
print("Dziel... |
8b1684502ace61945127e5195b5b9ff582527424 | weslleyrodrigues/Estudos | /EstudosPython/CSV.py | 765 | 3.625 | 4 | """
Nexte exemplo, desejo pegar a primeira coluna do csv e verificar se há valores com
menos de 4 caracters
"""
import csv
with open('teste.csv','r') as entrada: #a letra r é de read - leitura
arquivo_csv = csv.reader(entrada) #armazeno o arquivo csv em uma variavel
next(arquivo_csv) #Pula a primeira linha (d... |
43bfe303aa37bf248d2d7deeece770d883be2697 | kuzin2006/codewars | /next_bigger.py | 431 | 3.6875 | 4 | # https://www.codewars.com/kata/55983863da40caa2c900004e
def next_bigger(n):
digits = list(reversed(sorted(list(str(n)))))
iterator = n+1
while True:
if list(reversed(sorted(list(str(iterator))))) == digits:
return iterator
else:
if iterator > int(''.join(digits)):
... |
8e7f328491dc3de5a3baef23ec7c69facd6177e4 | rjulien1994/codeWars | /weightFweight.py | 769 | 3.546875 | 4 | #method 1
def order_weight(strng):
score = []
strng = strng.split(" ")
for n in strng:
digits = [int(d) for d in str(n)]
score.append(sum(digits))
output = " ".join([x for y,x in sorted(zip(score,strng))])
return output
#method 2
def order_weight(strng):
strng = st... |
08da0697ac661d7956b7ecb1ec26d62cf33e2134 | indrawaspada/online_process_monitoring_using_incremental_state-space_expansion_an_exact_algorithm | /pm4py/objects/log/util/compression.py | 1,191 | 3.828125 | 4 | import gzip
import os
import shutil
import tempfile
def compress(file):
"""
Compress a file in-place adding .gz suffix
Parameters
-----------
file
Uncompressed file
Returns
-----------
compressed_file
Compressed file path
"""
extension = fi... |
cd65c3a9e95e19ca32e442f1d63394a8b3b706d4 | mgtools/guttree | /metaproteome_application/peptide2sequenceStringMatching_parallel.py | 3,230 | 3.515625 | 4 | """
script that will perform an exact string matching between the peptides
and protein sequences from the genomes and will rerturn a table
reporting these matches.
this script requires three command line arguments
the first argument being the file that has the peptides to be searched in fasta format
these peptides cou... |
3c4b0de00d11bd2eb9e750b572b186a731d2f815 | Aasthaengg/IBMdataset | /Python_codes/p02574/s520369918.py | 1,055 | 3.5 | 4 | from sys import exit
def gcd(x,y):
if x == 0: return y
else: return gcd(y%x,x)
N = int(input())
A = list(map(int,input().split()))
is_prime = [True]*(10**6+10)
is_prime[0] = False
is_prime[1] = False
for i in range(2,10**6+10):
if not is_prime[i]:
continue
else:
for j in range(i*i,1... |
6d5b2eb86b2b1fc219c43260a1f1fce1e838220f | kivy-garden/garden.stiffscroll | /__init__.py | 6,099 | 3.578125 | 4 | """An Effect to be used with ScrollView to prevent scrolling beyond
the bounds, but politely.
A ScrollView constructed with StiffScrollEffect,
eg. ScrollView(effect_cls=StiffScrollEffect), will get harder to
scroll as you get nearer to its edges. You can scroll all the way to
the edge if you want to, but it will take ... |
2604aba86c8047639f009ec066081b25ffc3db14 | 1315groop/simple_drawing_tool | /draw_man/paint.py | 2,438 | 3.984375 | 4 | class Paint:
""" base class for simple drawing tool """
def __init__(self, width, height):
self.width = width
self.height = height
self.canvas = [[x for x in " " * self.width] for y in " " * self.height]
def draw_me(self):
""" draw borders of the field and figures"""
... |
acc2c04e6f5d08c66eba9df90d93a5f0181b312f | coertquinton/number_sequences | /printer/vertical_dots_printer.py | 1,373 | 3.546875 | 4 | '''
Created on 18 Jan 2017
@author: Quinton
'''
#==============================================================================
class VerticalDotsPrinter:
#--------------------------------------------------------------------------
def print_output(self, number_sequence):
prin... |
f5cd5c28bc0c7c7892ddd1c25bffa9e65d5fa8c4 | skypearl85/python-datascience | /module1-slide5.py | 393 | 3.90625 | 4 | randomList = ['Test', 'Random', 'Orange', 'Blue', 'Rabbit', 'Best']
search = input('Search: ')
#Without lambda
woLambdaList = []
for item in randomList:
if search.lower() in item.lower():
woLambdaList.append(item)
print('Without lambda: ', woLambdaList)
#With lambda
lambdaList = list(filter(lambda i: se... |
3ffdc5148f3b6353492e71b6901924363479a572 | viroee/python-code | /Desafio/TiposPremitidos/Desafios/PRODUTO COM DESCONTO.py | 192 | 3.53125 | 4 | preço = float(input('Qual é o preço do produto ? R$'))
novo = preço - (preço * 5 / 100)
print('o preço do seu produto de {}, agora com desconto de 5% custará R${}'.format(preço, novo)) |
ec031e0c637e52f6a7a0d3b8d1a8de31cc1c1f62 | FlanFlanagan/mlgrid | /parry/plotting_functions.py | 1,905 | 3.5 | 4 | import matplotlib.pyplot as plt
import geopandas as gp
import pandas as pd
import geoplot.crs as gcrs
import geoplot as gplt
def plot_gdf_kde(gdf, plotname, gridsize=300):
'''
This function converts the lat/long distance into
a meters distance.
Parameters
----------
gdf: GeoDataFrame
... |
a028e2f6a08842eba9ddf92f5b5778da1dc5a104 | SherryYeh/Python-HW | /014.py | 1,482 | 3.546875 | 4 | import math
def compute(total):
sum=0
if(total>=120):
sum+=120
total-=120
if(total>=120):
sum+=160
total-=120
return sum+math.ceil(total/30)*60
else:
return sum+math.ceil(total/30)*40
else:
return sum+(total//30)*30 ... |
e810d499014bb687082a0477a5f1ce306f3a0d38 | guohanli/Python-programming-exercises | /Python-programming-exercises-solutions/43.py | 80 | 3.609375 | 4 | t = (1,2,3,4,5,6,7,8,9,10)
new_t = tuple(x for x in t if not x % 2)
print(new_t) |
f632d57e1adf5da208de342f5beb4a3d76a7cf04 | CesarAzambuja/Python_Curos_em_Video | /ex007.py | 318 | 3.921875 | 4 | #007 Desenvolva um programa que leia as duas notas do um aluno, e calculo e mostre sua média
nome = input('Digite o nome do aluno: ')
n1 = float(input('Digita a nota da primeira prova: '))
n2 = float(input('Digite a nota da segunda prova: '))
m = (n1+n2)/2
print ('A media do aluno {} é: {}'.format (nome, m)) |
075d6f8959f5ecc2453dc4e1fc75fb6c7d260b2d | neuralbotnetworks/Geek-Brains-Homework | /Python/Lesson4/task7.py | 1,071 | 3.78125 | 4 | # 7) Реализовать генератор с помощью функции с ключевым словом yield, создающим очередное значение.
# При вызове функции должен создаваться объект-генератор.
# Функция должна вызываться следующим образом: for el in fact(n).
# Функция отвечает за получение факториала числа,
# а в цикле необходимо выводить только пер... |
86d461b1ad4b85af91fc66079c15a3d2d18e4408 | hzaman193/Practice-Python | /Calculator2.py | 934 | 4.15625 | 4 | class Calculator2:
"""Do addition, subtraction, multiplication and division."""
def addition(self, a, b):
return a + b
def subtraction(self, a, b):
return a - b
def multiplication(self, a, b):
return a * b
def division(self, a, b):
try:
return a / b
... |
a925a030c4ae9af477d52b29040b041584066483 | vsmalladi/mrboddy | /player_test.py | 1,428 | 3.890625 | 4 | #! /usr/local/bin/python
import unittest
from player import Player
class PlayerTestCase(unittest.TestCase):
def setUp(self):
""" Sets up test senario """
self.player = Player("Venkat")
self.player.character = "Miss Scarlet"
self.player.position = "Hall"
self.player.han... |
425cc3a68194f4323ef53075772e6edf97e5ae20 | jschnab/sqlitetools | /sqlitetools/query_db.py | 5,982 | 4 | 4 | #script which queries a database with a query from a text file and outputs
#the results in another text file
#import modules
import sys
import getopt
import sqlite3
import re
def print_help():
"""Print help text."""
help_text = \
"""Query an SQLite database with query from a string or text file and \
retu... |
e0c0639a6ecd70c37bfbfb0cd9df3e8598875a6f | AkshdeepSharma/Classroom | /Firecode.io/Level 3/nthlinkedlistelementfromend.py | 890 | 3.65625 | 4 | class Node:
def __init__(self):
self.data = None
self.next = None
def setData(self, data):
self.data = data
def getData(self):
return self.data
def setNext(self, next):
self.next = next
def getNext(self):
return self.next
def __str__(self):
... |
09dfe98e4c404544114d85f19292f4f8e7a51742 | duxiaobu/data_structure | /20_04_21/是否为对称二叉树.py | 1,179 | 4.03125 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
def check(p, q):
if not p and not q:
return True
if... |
70325402b5283b51c7e8b7c2a8f96421ecfd5752 | Erikfj/edu-editor | /if_example.py | 119 | 3.625 | 4 | example_dict = {'a': 1, 'b': 2, 'c': 3}
if example_dict:
print "The dictionairy is not empty."
print example_dict['c'] |
0cd29b526a6529faf9188b8176d1c3dfb5fd6a6f | Nerobeats/calculator | /calculator.py | 678 | 4.21875 | 4 | def main():
firstNumber = input("Enter the first number: ")
secondNumber = input("Enter the second number: ")
operation = input("Choose the operation (+, -, /, *):")
try:
firstNumber = int(firstNumber)
secondNumber = int(secondNumber)
except ValueError as err:
print("The numbers you entered were invalid, pl... |
3cb2f55fa4772bd968adeac275fb41060372a971 | PieterWiersma/advent2020 | /advent2.py | 1,199 | 3.734375 | 4 |
import argparse
def read_input(location):
l = []
with open(location) as f:
for line in f:
l.append(line.strip())
return l
def split_input(s):
l = s.split(' ')
min_max = [int(x) for x in l[0].split('-')]
required_letter =l[1][:1]
password = l[2]
return min_max, r... |
8189d94074fae1886d47e6f8b0ab71375d0ca0fa | ChristyLeung/Python_Green | /Green/4-1--2 pizzas_animals.py | 371 | 3.640625 | 4 | # Try 4-1
pizzas = ['cheese', 'durian', 'pepperoni']
for pizza in pizzas:
print(pizza)
print("I like " + pizza + " pizza." + "\n")
print("I really love pizza!")
# Try 4-2
pets = ['cat', 'dog', 'rabbit']
for pet in pets:
print(pet)
print("A " + pet + " would make a great pet." + "\n")
prin... |
229a3828e64531236678f0cd9e5143774af50706 | MilosSimek/Python-ITStep | /lekce4.py | 154 | 3.84375 | 4 | x = int(input("Zadej prvni cilso:\n"))
y = int(input("Zadej druhe cilso:\n"))
if x > y:
print ("Maximum is: ", x)
else:
print ("Maximum is: ", y) |
d95c0e3c7a150acd3e27a5f35980de3526c4d17c | xiaoxue11/02_python_multi_task | /02_python核心编程/多任务/线程/05_share_global_variables.py | 611 | 3.671875 | 4 | import time
import threading
g_num = 100
def test1():
global g_num
g_num +=1
print('g_num is : {} in test1......'.format(g_num))
def test2():
print('g_num is : {} in test2......'.format(g_num))
def main():
# create threading: execute globle variable addition
t1 = threading.Thread(target=te... |
16248dc323c93094a0295ce2dfbe80f131e95e91 | Spless01/HelloMac | /[nezdal]lab16_3.py | 607 | 4.34375 | 4 | #Напишите программу,
# выполняющую различные вычисления и выводящую значений с применение методов форматирования, манипуляторов и флагов объекта cout.
x = int(input("x: "))
y = int(input("y: "))
z = x * y
product = ('Умножили : {}'.format(z))
print('Первая буква Умножили будет с маленькой ----',product.lower())
p... |
2a33c8b27fcdcfbb513e19688070a91c8b013e83 | nzhoward/daily-coding-problem | /solutions/day8.py | 1,392 | 4.09375 | 4 | class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def count_unival(node):
global cnt
if node is None:
return
elif node.left is None and node.right is None:
cnt += 1
elif node.left is None or node.r... |
70e81f57b296bb14e2130670d782c897ecf81dc9 | mpoullet/NumCSE | /LectureCodes/IterativeMethods/newton1D/Python/newton1D.py | 503 | 3.75 | 4 | import numpy as np
def newton1D(F, DF, x0, rtol, atol):
x = x0
while True:
s = F(x) / DF(x)
x -= s
if abs(s) <= rtol * abs(x) or abs(s) <= atol:
return x
def example():
def F(x):
return np.sin(x) * np.cos(x)
def DF(x):
return np.cos(2 * x)
pr... |
dcaf42d380532abe2d5fd91d53861f977b82f659 | MatteoAnelliBePower/sphinx-from-scratch | /quadrilaterals/kites/kite.py | 894 | 3.65625 | 4 | import math
from ..quadrilateral import Quadrilateral, AngleInformationRequired
class Kite(Quadrilateral):
"""
Base class common to all kites.
>>> q = quadrilaterals.Kite(3, 5, 2.4)
"""
def __init__(self, side_A_length, side_B_length, angle_AB=None):
super().__init__(
side_A_len... |
1134b5ee3e9688b4444378880e0d3534e8a224ef | aditya98-ss/Python-Learning | /if else statement.py | 360 | 3.953125 | 4 | # coding=utf-8
name=input("what is your name?: ")
print("hello" + name +"!")
age=input("what is your age?: ")
print("that's great" + name)
tempreature=float(input("what is the tempreature now?"))
if tempreature > 70:
print("wear shorts")
print("enjoy your day " + name)
else:
print("wear long pants")... |
b4660e539aa26b62dd352f3758289eebb7b98ff0 | Ezzard23/code-practice | /Odd or Even.py | 401 | 4.21875 | 4 | num = int(input("Enter Number: "))
check = int(input("Enter Number: "))
def even_odd(num,check):
if num % check == 0:
return f"{check} divides evenly into {num}"
elif num % 4 == 0:
return "This number is divisible by 4"
if num % 2 == 0:
return "This number is even"
if ... |
6143dff3d3c701dc71f728dbc6845c9ca7b4b10a | SuveenMekala/Hackerrank | /30 days of Code/Day 8: Dictionaries and Maps.py | 280 | 3.5 | 4 | import sys
n=int(input().strip())
phoneBook={}
for i in range(n):
S=(input().split())
#print(S)
phoneBook[S[0]]=S[1]
#print(phoneBook)
while True:
k= str(input())
if k not in phoneBook:
print('Not found')
else:
print((k+'='+phoneBook[k]))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.