blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
04134e6994e86f42d3d3672f474f0d4c9255a366 | gergelykom/qa-python-exercises | /grade-calculator.py | 567 | 4.03125 | 4 | maths = int(input('Please enter your maths mark: '))
chem = int(input('Please enter your chemistry mark: '))
phys = int(input('Please enter your physics mark: '))
result = round((maths + chem + phys) / 3, 2)
def grade():
if result >= 70:
return 'You scored a grade of: A'
elif result >= 60:
... |
96e7890ba171743900a838dc6d9a5022011ceb58 | davide-coccomini/Algorithmic-problems | /Python/negativeIntegers.py | 546 | 3.828125 | 4 | # Find the number of negative integers in a row-wise / column-wise sorted matrix
# EXAMPLE
# -3 -2 -1 1
# -2 2 3 4
# 4 5 7 8
# Output: 4
# A good solution could be to use the fact that the matrix is sorted, to find the first negative number in a row and understand that the next number will be negative too
... |
8782817b87ac1f819b078b3c773778f2c72a93ee | davide-coccomini/Algorithmic-problems | /Python/steps.py | 988 | 4.15625 | 4 | # Given the number of the steps of a stair you have to write a function which returns the number of ways you can go from the bottom to the top
# You can only take a number of steps based on a set given to the function.
# EXAMPLE:
# With N=2 and X={1,2} you can go to the top using 2 steps or you can use a single step... |
6415d5691ba1eaa29bd07d2dbd27b2f2b587a689 | SwordWen/python_demo | /example/src/print_add_sub.py | 1,702 | 3.75 | 4 | import random
def print_to_file(f, no):
#print("print_to_file")
x = random.randint(0, 9)
y = random.randint(0, 9)
op = random.randint(0, 1)
op_str = "+"
if op == 0 and x>=y:
op_str = "-"
f.write("({0:3d}) {1} {2} {3} = ".format(no, str(x), op_str, str(y)))
def print_to_file_add_20(f, no):
print_to_file... |
bbd433169501fb1207b7ceeb49d6a9be8fdd1b21 | DimitriyL/chi_data | /vac_freq.py | 4,530 | 3.9375 | 4 | import csv
import sqlite3
# connecting to the database
connection = sqlite3.connect('per_capita.db')
# cursor
crs = connection.cursor()
# sql command to create the preliminary table
sql_command = """CREATE TABLE prelim_pop (
community CHAR PRIMARY KEY,
population REAL
);
"""
crs.execute (sql_command)
sql_command = "... |
d0a3332f64adf879f38cbb8b105851357287772f | KrzysztofKarch/Python-Programming-for-the-absolute-beginner | /chapter 4/exercise 2.py | 518 | 4.1875 | 4 | # "Python Programming for the Absolute Beginner", Michael Dawson
#
# chapter 4, exercise 2
print("Program wypisujący komunikat wspak. \n")
statement=input("Wprowadź komunikat: ")
# Pythonic way to get backwards
backward=statement[::-1]
print("Komunikat wspak utworzony za pomocą wycinka [::-1]:",backward)
# Using 'f... |
967fc1c06badeece90a1ff960f1f813e2e084fb7 | KrzysztofKarch/Python-Programming-for-the-absolute-beginner | /chapter 7/exercise 3a create_scores.py | 604 | 4 | 4 | # "Python Programming for the Absolute Beginner", Michael Dawson
#
# chapter 7, exercise 2
# creating empty list of best scores
# number of scores to save on list
MAX_SCORES = 3
print("Creating empty list of best scores. \n")
print("WARNING - THIS WILL RESET ALL SCORES! ")
answer = input("Do you want to continue? [Y... |
aa72b4a938098844d67497b5c50353dd6e2e78e8 | KrzysztofKarch/Python-Programming-for-the-absolute-beginner | /chapter 10/exercise 3 oop.pyw | 7,724 | 3.859375 | 4 | # "Python Programming for the Absolute Beginner", Michael Dawson
#
# chapter 10, exercise 3
import tkinter as tk
class App(tk.Frame):
def __init__(self, master):
super(App, self).__init__(master)
self.grid()
self.bill_log = '' # represents ordered meals
self.bill_total = 0 ... |
f4c92211d9fea87f535d05efa6029dd26bbdc5ea | kasyeb/cs_assignments2 | /pancake.py | 954 | 4.09375 | 4 | # File: Pancake.py
# Description: Sorting by flips only
# Student's Name: Vinayak Sahal
# Student's UT EID: vs9736
# Course Name: CS 313E
# Unique Number: 50725
# Date Created: 3/8/2019
# Date Last Modified: 3/8/2019
# function to sort array
def pancake(arr):
flipped = False
orderedArr = sorted(arr)
# chec... |
872c1fccb3d399c3ac77e95fd43f41b8ce881e01 | kasyeb/cs_assignments2 | /TestLinkedList.py | 11,756 | 3.96875 | 4 | # File: TestLinkedList.py
# Description: Linked list functions
# Student Name: Vinayak Sahal
# Student UT EID: vs9736
# Course Name: CS 313E
# Unique Number: 50725
# Date Created: 4/9/2019
# Date Last Modified: 4/12/2019
import random
class Link(object):
def __init__(self, data, next=None):
sel... |
2b54241b10e5b4600964e6027f60383e5840529d | Karodips/Hello-fella | /IDKx2.py | 577 | 4.09375 | 4 | '''
Задание 5 сумма, произведение, разность, частное модулей
'''
print('Enter numbers')
a = float(input())
b = float(input())
if (a != 0) or (b != 0):
if a < 0 :
a = a*(-1)
if b < 0:
b = b*(-1)
print('Вот сумма, разность, произведение и частное соответственно: ', a+b, a-b, a*b, a/b )
else :
... |
938f8743036cf77890eabd9b1b2e7bd0f1ac73f2 | inesbeltran/1-Evaluacion | /bucle_3.py | 182 | 3.8125 | 4 | def bucle_3():
n= input("Que tabla de multiplicar quieres?: ")
for i in range (0,11):
print str(n) + "x" + str(i) + " = "+ str(n*i)
bucle_3()
|
64575725c4e761b7f2c7a4c74edb383f3fc38b69 | inesbeltran/1-Evaluacion | /bublesuma_paraes_ompares.py | 497 | 3.71875 | 4 | def bucle_10():
nfinal=input("hasta que numero quieres sumar")
numeros_pares=0
numeros_impares=0
for numero in range(1,nfinal+1):
if(numero%2==0):
print str(numero), "es par"
numeros_pares=numeros_pares+1
else:
print str(numero), "es impar"
... |
392f0e24c5971943ad6b4b88fc9fcd0eb523d91a | glncmd/bookish-potato | /solutions/reverse-integer.py | 200 | 3.671875 | 4 | def reverse(x: int) -> int:
sign = 1 if x > 0 else -1 #can be written as [-1, 1][x > 0]
x_rev = sign * int(str(abs(x))[::-1])
return x_rev if -2 ** 31 <= x_rev <= (2 ** 31) - 1 else 0
|
05f7a4309cdce1bf511f4fc387160d0ae792b5a3 | glncmd/bookish-potato | /solutions/palindrome-number.py | 481 | 3.796875 | 4 | def isPalindrome(x: int) -> bool:
return True if str(x) == str(x)[::-1] else False
#Interesting solution from leetcode:
def isPalindrome(x):
if x < 0 or (x > 0 and x % 10 == 0):
return False
return x == self.reverseUtil(x)
def reverseUtil(self, x):
result = 0
... |
6d87194098d66d4d6712f67ee721d14c529a11ad | Ponyduelist003/4663-Cryptography-Forsgren | /Assignments/A08/Messaging.py | 7,628 | 3.515625 | 4 | import sys
import os
import requests
import json
def mykwargs(argv):
'''
Processes argv list into plain args (list) and kwargs (dict).
Just easier than using a library like argparse for small things.
Example:
python file.py arg1 arg2 arg3=val1 arg4=val2 -arg5 -arg6 --arg7
Would create:
... |
d102082a3e1ae6ab88084b940b37afe8f51513c9 | ismailgunayy/project-euler | /python-solutions/Problem10 - PE.py | 417 | 3.53125 | 4 | """
Created by İsmail GÜNAY
Start Date: 15:20 / 18.01.2020
End Date: 15:31 / 18.01.2020
ProjectEuler Problem10
The sum of all the primes below two million
"""
def is_prime(n):
for i in range(2, round((n**0.5) + 1)):
if n % i == 0:
return False
return True
sum = 0
for j in ra... |
0e4a9ed6b2a4e5ab3518ca43328a70d0bdf377a2 | ismailgunayy/project-euler | /python-solutions/Problem2 - PE.py | 397 | 3.71875 | 4 | """
Created by İsmail GÜNAY
Start Date: 12:50 / 17.01.2020
End Date: 12:59 / 17.01.2020
ProjectEuler Problem2
The sum of even numbers in fibonacci sequence until a limit
"""
def fib(n):
if n == 0:
return n
elif n == 1:
return n
else:
return fib(n - 1) + fib(n - 2)
evenFibs = list()
for i in range(34)... |
241dfa6e8ec275d25e78d647199635c9489dc438 | josuel23/Exercicio_01_Python | /Relacionamento_entre_Classe.py | 850 | 3.875 | 4 | class Produto:
def __init__(self, nome , preco, quantidade):
self.nome = nome
self.preco = preco
self.quantidade = quantidade
class Pedido:
def __init__(self):
self.produtos = []
def adicionar_produtos(self, prod):
self.produtos.append(prod)
def calcular_valor(... |
fafc20e757e5f69a1fe734520c962541dae12109 | hoangtrung1999/UIT_Homework | /[Second Year] AI/[TH5] 17521176_17520208_17520474_17520271/Dijkstra.py | 1,940 | 3.75 | 4 | import numpy as np
def dijkstra(graph, start, end):
n = graph.shape[0]
dist = np.array([float('inf')] * n) #init distance
dist[start] = 0
route = []
flag = np.array([1] * n) #if vertex is taken out
prev = [-1] * n #previous vertex of i
while np.sum(flag) > 0:
temp = np.copy(dis... |
bb4a8b31b0334748cb71a7c7ee94042e426bfe19 | abzanganeh/first-semester | /digNumberInHtml.py | 347 | 3.5 | 4 | import re
import urllib
from BeautifulSoup import *
url= raw_input('Enter:')
try:
html=urllib.urlopen(url).read()
except:
print"Not a valid URL"
quit()
soup= BeautifulSoup(html)
spn=soup('span')
sum=0
num=[]
count=0
for i in spn:
i=str(i)
num=re.findall(">([0-9]+)<",i)+num
for j in num:
j=int(j)
sum=j+sum
cou... |
af44b33c7aa0e85e8910b673992dd9f5ee03a941 | abzanganeh/first-semester | /backwardWhile.py | 94 | 3.78125 | 4 | text=raw_input("Enter your text: ")
l= len(text)
i=1
while i<=l:
x=text[l-i]
print x
i+=1
|
92c0be12528630740fdd2b7611f83bf3674f6a8d | andelgado53/OrderProcessingService | /app/src/shelf/ShelvesManager.py | 3,632 | 3.609375 | 4 | from app.src.shelf.Shelf import Shelf
class ShelvesManager:
def store_order(self, internal_order, shelves):
"""Recieves an order and the shelves and puts the order in the appropiate shelf"""
shelve = shelves[internal_order.get_temp()]
overflow_shelve = shelves["overflow"]
if sh... |
a8581d920a6f7d05b271ebff15d6ae94f22ca8d6 | Eytan425/Cube-Timer | /Cube Timer with Pygame.py | 7,708 | 3.75 | 4 | """Name: Philips Xu
Date: June 2, 2018
Description: Rubik's Cube Timer. Generates scramble and saves times in a file.
Times can be deleted.
"""
import pygame, cubeTimerSprites, random, math
pygame.init()
pygame.mixer.init()
def generate_random_scramble(moves, scramble_text):
'''Generates a random scramb... |
233c7f9b79a2f4ff1f6369682d0510d7475e0587 | YutoTakaki0626/My-Python-REVIEW | /oop/car.py | 635 | 3.59375 | 4 | class Car(object):
def __init__(self, model_name, mileage, manufacture):
self.model_name = model_name
self.mileage = mileage
self.manufacture = manufacture
def gas(self):
print('{0.manufacture}の{0.model_name}(燃費:{0.mileage}), アクセル全開!!'.format(self))
def brakes(self):
... |
9bee276add9c08bfad384fe788c400d7749e5560 | YutoTakaki0626/My-Python-REVIEW | /style_guide/style_guide.py | 4,253 | 3.625 | 4 | # 変数定義
# correct
x = 1
y = 1
# wrong
xxxx = 1
y = 1
# 関数の引数の=にはスペース不要
def complex(real, imag=0.0)
return magic(r=real, i=imag)
# operatorの周りにスペース一個, operatorにpriorityがある場合はスペースをなくす
x = x + 1
x += 1
x = x*2 - 1
a = x*x + y*y
c = (a+1) * (a-1)
# カンマの後にはスペースをいれる
range(1, 11)
a = [1, 2, 3, 4]
b = (1, 2... |
7cdaaed456af8a41dd627feb595823b98dd3713e | YutoTakaki0626/My-Python-REVIEW | /basic/dictionary.py | 529 | 4.28125 | 4 | # dictionary:キーと値の組み合わせを複数保持するデータ型
fruits_colors = {'apple':'red', 'lemon': 'yellow', 'grapes': 'purple'}
print(fruits_colors['apple'])
fruits_colors['peach'] = 'pink'
print(fruits_colors)
dict_sample = {1: 'one', 'two': 2, 'three': [1, 2, 3], 'four':{'inner': 'dict'}}
print(dict_sample)
print(dict_sample['four']['in... |
c9f9154b5b9f95bdd947f7a964cf1efedf8a05b2 | YutoTakaki0626/My-Python-REVIEW | /function/function.py | 287 | 3.90625 | 4 | # 関数(function)
# # 華氏から摂氏に変換する
fahrenheit = 72
# celsius = ( fahrenheit - 32) * 5/9
# print(celsius)
def faherenheit_to_celsius(fahrenheit):
celsius = ( fahrenheit - 32) * 5/9
return celsius
celsius = faherenheit_to_celsius(fahrenheit)
print(celsius) |
de74f86258c9196ae10b56e7c41b60cd0c3ec5d6 | YutoTakaki0626/My-Python-REVIEW | /database/select.py | 405 | 4.03125 | 4 | import sqlite3
con = sqlite3.connect('sample.db')
cursor = con.cursor()
for row in cursor.execute('select * from User'):
print(row)
# .fetchall():現在のcursor以下全てをタプルのリストで返す
cursor.execute('select * from User')
print(cursor.fetchall())
# .fetchone():現在のcursorのレコードをタプルで返す
cursor.execute('select * from User')
print(... |
bd1f9204c41a5e434a4b80d45c8b162b0e95e080 | KimJinYounga/Algorithm_python-2019- | /OWL/퀵정렬.py | 406 | 4.09375 | 4 | numbers=[40,35,27,50,75]
def quickSort(array):
if len(array)<2:
return array
else:
pivot=array[0]
# print(pivot)
less=[number for number in array[1:] if number < pivot]
greater=[number for number in array[1:] if number >= pivot]
# print(less)
# print(grea... |
982a38296cc89a84ee480e257f81eef9b54ad8c0 | KimJinYounga/Algorithm_python-2019- | /OWL/ABC.py | 493 | 3.6875 | 4 | N = input() # 배열
O = input() # 순서
list = N.split()
order = O.split()
result = []
list_int = [int(n) for n in list] # 문자열을 int형으로 전환
list_int.sort()
print(order)
for i in range(len(order)):
if order[i] == 'A':
result.append(list_int[0])
elif order[i] == 'B'... |
2959e470cb8e18b0edd7f5c8b1a46b2272d3edc5 | KimJinYounga/Algorithm_python-2019- | /Stack/ironbar.py | 484 | 3.59375 | 4 | arrangement = "()(((()())(())()))(())"
def solution(arrangement):
answer = 0
line = 0 # 몇차원인지 (예시에서는 3줄 -> 3차원)
num=0 # 막대 총 갯수
for i in range(len(arrangement)-1):
if arrangement[i:i+2]=='()':
answer += line
if arrangement[i:i+2]=='))':
line-=1
num+... |
d4bb5cfce81d64e3da5ded47e9c6e4f770322ab1 | jonlwil/chem160homework4 | /point.py | 128 | 3.5 | 4 | import math
def distance(x1,y1,x2,y2):
dist = math.hypot((x2-x1)**2+ (y2-y1)**2)
return dist
print distance(x1,y1,x2,y2) |
b88b7ba9af6f12f7fc625d949253a7f990064b9d | wWX152939/script | /python/generate_name.py | 919 | 3.703125 | 4 | def str2Hump(text):
arr = filter(None, text.lower().split('_'))
res = ''
for i in arr:
res = res + i[0].upper() + i[1:]
return res
def change_variable_name(listx):
listy = listx[0]
for i in range(1,len(listx)):
if listx[i].isupper() and not listx[i-1].isupper():
... |
03f049999ce1eea68e4992ec6bcfc25fd929ee09 | niksm7/March-LeetCoding-Challenge2021 | /Check If a String Contains All Binary Codes of Size K.py | 855 | 4 | 4 | '''
Given a binary string s and an integer k.
Return True if every binary code of length k is a substring of s. Otherwise, return False.
Example 1:
Input: s = "00110110", k = 2
Output: true
Explanation: The binary codes of length 2 are "00", "01", "10" and "11". They can be all found as substrings at indicies 0, ... |
4563f9cfd76020c2652d8de971b89ca93e224e9d | niksm7/March-LeetCoding-Challenge2021 | /Pacific Atlantic Water Flow.py | 1,463 | 4.0625 | 4 | '''
You are given an m x n integer matrix heights representing the height of each unit cell in a continent. The Pacific ocean touches the continent's left and top edges, and the Atlantic ocean touches the continent's right and bottom edges.
Water can only flow in four directions: up, down, left, and right. Water flows... |
b66eaae92036f6eec6e3a4ffd354e94bf328cdae | niksm7/March-LeetCoding-Challenge2021 | /Swapping Nodes in a Linked List.py | 1,148 | 3.9375 | 4 | '''
You are given the head of a linked list, and an integer k.
Return the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed).
Example 1:
Input: head = [1,2,3,4,5], k = 2
Output: [1,4,3,2,5]
'''
# Definition for singly-linked li... |
b3080fe028e3a62ade5b64a57da7ce9276c650ae | niksm7/March-LeetCoding-Challenge2021 | /Palindromic Substrings.py | 622 | 4.15625 | 4 | '''
Given a string, your task is to count how many palindromic substrings in this string.
The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.
Example 1:
Input: "abc"
Output: 3
Explanation: Three palindromic strings: "a", "b", "c".
'''
... |
1737697788e38561dbe250977448436252d85cf6 | MLGNateDog/Capstone-Mini-Projects | /Mini Projects/wordReverse.py | 756 | 4.03125 | 4 | """ wordReverse.py
demostrates how to use loops
for sting manipulation
17 Jan 2021"""
inWord = input("Please type a word or phrase: ")
outWord = " "
# remember, I want to count backwards to character zero, so negative one is the boundary
firstChar = -1
# The length of the word is how many ch... |
d4acd235979ade6db5389d6af14e26703e4fced3 | MLGNateDog/Capstone-Mini-Projects | /Mini Projects/LinusOrGuidoOrNot.py | 638 | 3.90625 | 4 | """ LinusOrGuidoOrNot.py
Illustrates if - else structure
Say something nice if the user's name is Guido
and asks for Guido if user enters another name. """
firstName = input("What is your first name? ")
firstName = firstName.title()
print("Nice to see you, " + firstName + ".")
if(firstName.upper(... |
6128b61b37b46b318d273056a6d24e8631b2bcbc | quockhanhtn/artificial_intelligence_exercise | /ex1_solve_8_puzzle/model/search_algorithm.py | 5,014 | 3.53125 | 4 | from .Problem import *
import queue
import sys
def breadth_first_search(_problem) :
'''
Tìm kiếm theo tìm rộng
Input: problem
Output : string ('failure', or list actions seperated by '-' to slove problen)
'''
_node = _problem.initial_node
if (_problem.goal_test(_node.stage)) : return _node... |
35104eeac272e1d114eebfe77e0585da7498b659 | AlejandraBonilla/Computacional2 | /clase3108.py | 415 | 3.828125 | 4 | #librería numpy
import numpy as np
from numpy import matrix
from pylab import *
print (np.arange(15)) #genero un lista de los primeros 15 números : 0 a 14
print ('---------------------------------------')
r=2
i=np.arange(n)
j=np.arange(n)
n=5
a = np.zeros(n*n).reshape(n,n) # acomodo los valores en una matriz de 3 ... |
c4c07531bd3744c6f695e443ed2c050f21b1b2aa | grafdog/SEMINARI | /28.10.n1.py | 134 | 3.6875 | 4 | #!/usr/bin/env python3
import sys
d = 0
#sys.argv.pop(0)
for arg in sys.argv[1:]:
if len(arg) % 3 == 0:
d +=1
print(d)
|
387b4a8c0e1e472d66a008f0eb62fb52ea64c447 | coperyan/code-snippets | /python/day_of_week.py | 298 | 3.609375 | 4 | def get_dayofweek():
#Returns day of the week
list = [
'Sunday','Monday','Tuesday',
'Wednesday','Thursday','Friday',
'Saturday'
]
#Returns integer for day # of week - starting with sunday at 0
dayint = int(dt.datetime.today().strftime('%w'))
return list[dayint]
|
85a9a51e49320d315cc7a35eddb6be5fad03e5d6 | LuisEnMarroquin/python-examples | /V014.py | 182 | 3.859375 | 4 | # Bucle for
for i in [2,4,6]: # Repetirá lo que hay dentro del bucle 3 veces
print('Hola')
for i in ['primavera', 'verano', 'otoño', 'invierno']:
print('Estacion: ' + i)
|
7e38b3de73bbc91bcab8dd72fbb0238feffd4956 | LuisEnMarroquin/python-examples | /V021.py | 833 | 4.03125 | 4 | # Excepciones
def suma(num1, num2):
return num1+num2
def resta(num1, num2):
return num1-num2
def multiplica(num1, num2):
return num1*num2
def divide(num1,num2):
try:
return num1/num2
except ZeroDivisionError:
print('No se puede dividir entre 0')
return "Operación erronea"
op1=(i... |
a3f2886376c4ecccb647fb510742d475ec91a124 | olaboga13/Pyt1 | /zad3B.py | 600 | 3.609375 | 4 | __author__ = 'Ania'
# Dla danych napisz kod wypisujacy na konsoli elementy
# list pogrupowane wg dlugosci elementow
list1 = ['orange', 'apple', 'banana']
list2 = ('carrot', 'potato', 'lettuce')
list3 = {'milk', 'sugar', 'butter', 'flour'}
slownik = {}
lista=[]
"""
Stworz jedna liste
"""
lista += list1
lista += list2... |
cb66581e7733ab71c6ba9872405b81250e797dc2 | TheDarkKnight1939/FirstYearPython | /1.py | 296 | 4.0625 | 4 | #!/usr/bin/python3
a=45 #Initialises variable a to 45
print(a) #prints the number in variable a
print(a+3) #adds 3 to variable a and prints it
print(a-23) #Minuses 23 from variable a
print(a/12) #Divides variable a by 12
print(a%3) #Finds the reminder of the number when it is divided by 3
|
77de892bfce5df9d0d5c9bad7cde7b401e1ba38e | TheDarkKnight1939/FirstYearPython | /3.py | 539 | 4.28125 | 4 | #!/usr/bin/python
import random #Imports the class random
r=random.randint(10,66) #Uses the randint function to choose a number from 10 to 66
print(r) #Prints the random number choosen
if r<35: #If loop which checks if the number is lesser than 35
print(r)
print(": is less than 35 \n")
exit
elif r==30:#If loop whi... |
f460cc00a202b991b5bc9f5f99b3938df452c5db | lkarnes/Sorting | /src/iterative_sorting/iterative_sorting.py | 897 | 4.03125 | 4 | # TO-DO: Complete the selection_sort() function below
def selection_sort( arr ):
# loop through n-1 elements
for i in range(0, len(arr)-1):
current = i
smallest = current
for n in range(i+1, len(arr)):
if arr[n]< arr[smallest]:
smallest = n
arr[current],... |
e4134ccd497be10857cae5723feba9983b842ce5 | ThatSimplex/random_python_programs | /seeds/board.py | 4,316 | 3.609375 | 4 | from cell import Cell
from random import randint
class Board:
def __init__(self, rows, columns):
self._rows = rows
self._columns = columns
self._grid = [[Cell() for column in range(0, columns)] for row in range(0, rows)]
for row in range(0, rows):
for column in range(0,... |
11bcd71a1cb45309e6690c64e0fe2a6783b0c420 | wanghongbo122333/python_start | /ThreadTest-join.py | 750 | 3.65625 | 4 | #!/usr/bin/python3
# -*- coding:utf-8 -*-
# Author:user
# Date:2020/8/31
# Comment: test join
import threading, time
def run():
time.sleep(2)
print('current thread :', threading.current_thread().getName())
time.sleep(2)
if __name__ == '__main__':
s_time = time.time()
print('this is mainThread', ... |
a6f0727f445e8a2d3af729b3b5d3a763ff4f089d | runngezhang/sword_offer | /leetcode/python/143. 重排链表.py | 2,988 | 3.9375 | 4 | #!/bin/bash/python
"""
143. 重排链表
思路一:
递归(超时)
思路二:
使用list保存所有节点
依次从首尾添加节点
思路三:
找到中间节点
把后半部分保存到list
依次插入到前半部分中
思路四:
找到中间节点
后半部分翻转链表
两个子链表从头归并
"""
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
def reorderList(self, head)... |
ec9a24e232e1f733b284a2958e204a2dca212263 | lirus7/Smart_Blinds | /Capture.py | 715 | 3.625 | 4 | import RPi.GPIO as GPIO
import picamera
import time
GPIO.setwarnings(False)
#Access Button
GPIO.setmode(GPIO.BCM)
buttonPin = 17
GPIO.setup(buttonPin, GPIO.IN, GPIO.PUD_DOWN)
#Access Red LED
LED = 4
GPIO.setup(LED, GPIO.OUT)
#Intializing Pi Camera
camera = picamera.PiCamera()
print("Press button to take picture, C... |
79b2b7eb5e51c55a0dee2e9eb98190299e4cab95 | Adarsh1193/Python-Udemy-Course | /Control Structures/Coding challenge 3.py | 125 | 3.671875 | 4 | for x in range(5):
print("I am a programmer")
def square():
for x in range(1,10):
print(x**2)
square() |
9401cbac50144eb4d7b88706db3c09caef3aa251 | Adarsh1193/Python-Udemy-Course | /Control Structures/For loop.py | 203 | 3.96875 | 4 | for x in range(1,11):
print(x)
for x in range(1,6):
print("Adarsh")
fruits = ["Apple", "Banana", "Peach", "Mango"]
for x in fruits:
print(x)
for x in range(0,21,2):
print(x) |
e1dbe9d141a0a5a876f024307611964131875415 | Adarsh1193/Python-Udemy-Course | /Exception Handling and File Handling/Coding Challenge 5.py | 258 | 3.953125 | 4 | def divide(a,b):
try:
return a / b
except ZeroDivisionError:
print('Divide by zero exception')
x = int(input('Enter the first number'))
y = int(input('Enter the second number'))
result = divide(x,y)
print(result)
|
5015fae88e94cc764e16ba49e8f5d7ba8e71ebe1 | Adarsh1193/Python-Udemy-Course | /Regular Expressions/Group.py | 157 | 3.921875 | 4 | import re
pattern = r"bread(eggs)*bread"
if re.match(pattern, "breadeggseggseggsbread"):
print('Match found')
else:
print('Match not found') |
bea0d7f894722d03afd8ff9ed490e6f09cb2840d | ishine/tal-asrd | /tal/utils/prune_bad_utterances.py | 1,417 | 3.71875 | 4 | import argparse
import os
import json
def prune_bad_utterances(index: list, score_data: list, threshold: float = 9.1):
"""
Prunes away "bad utterances" by thresholding all utterances
above a certain loss threshold, then removing them from index.
Args:
score_data: A list of [filenam... |
a1a4bf417a5d4aa6c6cfc5444c389e70cbd7ea9b | jrinder42/Advent-of-Code-2020 | /day6/day6.py | 1,485 | 3.734375 | 4 |
'''
Advent of Code 2020 - Day 6
'''
# Part 1 - Union
groups = []
with open('day6.txt', 'r') as file:
group = ''
for line in file:
line = line.strip('\n').split(' ')
if len(line) == 1 and line[0] == '':
groups.append(group)
group = ''
continue
for... |
eee031351c4115a1057b3b81293fe25a17ad8066 | jrinder42/Advent-of-Code-2020 | /day15/day15.py | 767 | 3.5 | 4 |
'''
Advent of Code 2020 - Day 15
'''
lookup = {0: [1],
3: [2],
1: [3],
6: [4],
7: [5],
5: [6]}
turn = 7
prev = 5
while turn != 2020 + 1: # Part 1
#while turn != 30_000_000 + 1: # Part 2
if prev in lookup and len(lookup[prev]) == 1:
prev = 0
i... |
69499303e18f872dae9c36e0665e17628b3f945c | jrinder42/Advent-of-Code-2020 | /day21/day21.py | 2,020 | 4 | 4 |
'''
Advent of Code 2020 - Day 21
'''
allergens = {}
allergens_raw = []
with open('day21.txt', 'r') as file:
for line in file:
line = line.strip()
if ')' in line:
ingredients = line[:line.index('(') - 1].split(' ')
ingredients = [ingredient.strip() for ingredient in ingred... |
ae87b44d03f4fbef2ad8d5a51a86220660945e3a | SultanovDastan/task2_21 | /task2_21.py | 217 | 4.09375 | 4 | def sum_(sum_1, sum_2, sum_3):
return sum_1 + sum_2 + sum_3
s1 = int(input('First number ='))
s2 = int(input('Second number ='))
s3 = int(input('Third number ='))
print('Result sum of 3 numbers = ',sum_(s1,s2,s3)) |
fe774b0ebc519e2b2494467864f9878510901ca2 | magnus188/pmx | /Oppgaver/fellesBokstaver.py | 271 | 3.828125 | 4 | name1 = str(input('Skriv inn navn 1: '))
name2 = str(input('Skriv inn navn 2: '))
similarCharacters = []
for i in name1.lower():
if i in name2.lower() and i not in similarCharacters:
similarCharacters.append(i)
print('Like boksatver', similarCharacters)
|
7a318764da1d6aed2b274479adbcac20ac561427 | magnus188/pmx | /Oppgaver/password.py | 170 | 3.5 | 4 | import string
import random
passwordLength = int(input("Velg lengde på passordet: "))
password = ""
print(string.ascii_letters)
for i in range(passwordLength):
break |
9fa66c5385dadbfdf335a217d002374f30f806b3 | magnus188/pmx | /Oppgaver/hangman.py | 1,638 | 3.96875 | 4 | import re
from random_word import RandomWords
print("Welcome to hangman")
word = RandomWords().get_random_word()
hiddenWord = ""
lives = 8
guessedLetters = set()
for i in range(len(word)):
hiddenWord += "_"
print("_",end=" ")
print("\n")
def convert(s):
new = ""
for x in s:
new += x ... |
d728c9a7bca688952525a9a52daaf1ecd5151695 | magnus188/pmx | /escapeRoom/6.py | 113 | 3.5625 | 4 |
word = 'Mats Rongved'
summ = 0
sumList = [ord(c) for c in word]
for i in sumList:
summ += i
print(summ)
# 1162 |
c74ca6f0e5e5e58ff06bedd3b21e3be680a4b347 | magnus188/pmx | /escapeRoom/2.py | 99 | 3.5 | 4 | tot = 0
for i in range(1,101):
if i%3 == 0 and i%7 ==0:
tot+=i
print(tot)
# 210
|
4c1fd7ced11d7aff3de4cb487cb7c76cb7676bc9 | khvesiukdaniil/project-Euler | /python/p002.py | 235 | 3.546875 | 4 | def stupid_solver(n):
prev = 1
curr = 2
sum_ = 2
while curr < n:
prev, curr = curr, prev + curr
if curr % 2 == 0:
sum_ += curr
return sum_
print(stupid_solver(4*10**6)) |
569400dbb0633d3ba77ed5907eba64c3f588281f | guoqing-tang/algorithm | /algorithm3.py | 332 | 3.59375 | 4 | # * -- utf-8 -- * # python3
# Author: Tang Time:2018/4/17
import math
for i in range(100000):
x = int(math.sqrt(i+100))
y = int(math.sqrt(i+268))
if (x*x == i+100) and (y*y ==i+268):
print(i)
'''简述:一个整数,它加上100和加上268后都是一个完全平方数 提问:请问该数是多少?''' |
0224bb75455561701ed3b7a54ac40e00fa58dcc6 | guoqing-tang/algorithm | /algorithm5.py | 266 | 3.828125 | 4 | # * -- utf-8 -- * # python3
# Author: Tang Time:2018/4/17
'''从键盘获取x y z三位数,输出其中最大的'''
x = int(input("x:"))
y = int(input("y:"))
z = int(input("z:"))
if x > y:
c = x
else:
c = y
if z > c:
print(z)
else:
print(c)
|
3c95f08b21ee8b7786bf2540ccf777dbe90f1b61 | Mrtcnakcy/python | /Temel Veri Yapıları/vucut_kitle.py | 172 | 3.53125 | 4 | kilo = input("Kilonuzu Giriniz (kg): ")
boy = input("Boyunuzu giriniz (m): ")
bke= round(float(kilo) / (float(boy)**2),2)
print("Benden Kitle Indeksiniz: {}".format(bke)) |
65b3ee08711fee0c81b69de43ceb4f4e90167de3 | BenitoMarculanoRibeiro/TrabalhandoComJSONPython | /coverter.py | 1,176 | 3.578125 | 4 | import pandas as pd
import json
# Exemplo de um dicionário que virará um arquivo .json
dict = {"students": [{"name": "Alan", "lastname": "Silva", "exam1": 50, "exam2": 80, "exam3": 91},
{"name": "Paula", "lastname": "Souza", "exam1": 95, "exam2": 98, "exam3": 99}]
}
# Criar uma função que escreve um arquivo ... |
4ad3bb18565e9785a5082c1d13e3ccd826228d8e | gaurav-singh-au16/Online-Judges | /Binary_Search_Problems/longest_consucetive_duplicates.py | 970 | 3.75 | 4 | """
Longest Consecutive Duplicate String
Given a lowercase alphabet string s, return the length of the longest substring with same characters.
Constraints
0 ≤ n ≤ 100,000 where n is the length of s
Example 1
Input
s = "abbbba"
Output
4
Explanation
The longest substring is "bbbb".
Example 2
Input
s = "aaabbb"
Output
... |
138561e4f2baa079e0741c0b63c155ed58025d94 | gaurav-singh-au16/Online-Judges | /Binary_Search_Problems/check_power_of_two.py | 534 | 4.03125 | 4 | """
Check Power of Two
Given an integer n greater than or equal to 0, return whether it is a power of two.
Constraints
0 ≤ n < 2 ** 31
Example 1
Input
n = 0
Output
False
Example 2
Input
n = 1
Output
True
Explanation
2^0 = 1
Example 3
Input
n = 2
Output
True
Explanation
2^1 = 2
Solved
1,548
Attempted
1,742
Rate
88.8... |
b852f4c777800af91dcb1163680e1f79ceb15d06 | gaurav-singh-au16/Online-Judges | /Leet_Code_problems/7.reverse_integer.py | 953 | 4.0625 | 4 | """
7. Reverse Integer
Given a 32-bit signed integer, reverse digits of an integer.
Note:
Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer ove... |
aad35df15da4265e65defc8f609290a342e727f3 | gaurav-singh-au16/Online-Judges | /Binary_Search_Problems/nth_fibonacci_no.py | 916 | 4.1875 | 4 | """
Nth Fibonacci Number
The Fibonacci sequence goes like this: 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
The next number can be found by adding up the two numbers before it, and the first two numbers are always 1.
Write a function that takes an integer n and returns the nth Fibonacci number in the sequence.
Constraints
n ... |
4351facc61673683fa48ee707e37d38518df5b0f | gaurav-singh-au16/Online-Judges | /Binary_Search_Problems/sorting_mail.py | 1,031 | 4.0625 | 4 | """
Sorting Mail
You are given a list of mailboxes. Each mailbox is a list of strings, where each string is either "junk", "personal", "work". Go through each mailbox in round robin order starting from the first one, filtering out junk, to form a single pile and return the pile.
Example 1
Input
mailboxes = [
["wor... |
d7dda6a7263ed3dc941aceb3726cf55095d961c3 | gaurav-singh-au16/Online-Judges | /Binary_Search_Problems/high_frequency.py | 749 | 3.75 | 4 | """
High Frequency
Given a list of integers nums, find the most frequently occurring element and return the number of occurrences of that element.
Constraints
n ≤ 100,000 where n is the length of nums
Example 1
Input
nums = [1, 4, 1, 7, 1, 7, 1, 1]
Output
5
Example 2
Input
nums = [5, 5, 5, 5, 5, 5, 5]
Output
7
Exampl... |
db570e406331720fe31ed39a8fbbfbe6bf9afd0a | gaurav-singh-au16/Online-Judges | /Binary_Search_Problems/add_one.py | 725 | 3.96875 | 4 | """
Add One
Question 235 of 991
You are given a list of integers nums, representing a decimal number and nums[i] is between [0, 9].
For example, [1, 3, 9] represents the number 139.
Return the same list in the same representation except modified so that 1 is added to the number.
Constraints
n ≤ 100,000 where n is t... |
86a7c2270c42fdd3e898d027dac3f0c63d07fbc8 | gaurav-singh-au16/Online-Judges | /Leet_Code_problems/69. Sqrt(x).py | 543 | 4.15625 | 4 | """
69. Sqrt(x)
Easy
1657
2143
Add to List
Share
Given a non-negative integer x, compute and return the square root of x.
Since the return type is an integer, the decimal digits are truncated, and only the integer part of the result is returned.
Example 1:
Input: x = 4
Output: 2
Example 2:
Input: x = 8
Outpu... |
8f6712b55118fb3c827f6bed2b327bb6647385c0 | suren-star/BDG-Trainings2021 | /armen.mkhoyan/repo/Lesson_3/exercise_26/exercise_26.py | 197 | 4.21875 | 4 | #!/usr/bin/env python3
passport_name = str(input("Enter a First Name: "))
passport_last_name = str(input("Enter a Last Name: "))
print(passport_name.capitalize(), passport_last_name.capitalize()) |
72ebc543b16ec1454e16f53a02cff1c3c5d2b708 | SangavaiKSPillai-Draup/Training_Python | /class_SOP.py | 882 | 3.65625 | 4 | """
A hypothetical mobile phone brand, that has the features of Oppo and Samsung.
This class is implemented to understand the concept of Method Resolution Order,
and Class Decorators
"""
from class_Samsung import Samsung
from class_Oppo import Oppo
def sop_deco(cls):
print("\nDecorating SOP class with SOP_DECO")... |
12dbe03839a15604f0a900c2fffe524b5c12d089 | gongfei6644/gongfei | /gongfei/month01_gf/ProjectMonth01-1/2048game_core01.py | 1,235 | 4.0625 | 4 | # 练习:定义函数,将列表中0元素,移动到末尾。
# [2,0,2,0] --> [2,2,0,0]
# [0,4,2,4] --> [4,2,4,0]
# 适合零基础同学
# def zero_to_end(list_target):
# # 选出非零元素 形成新列表
# # [2, 0, 2, 0] --> [2, 2]
# new_list = []
# for item in list_target:
# if item != 0:
# new_list.append(item)
# # 追加零元素 [2, 2] ... |
e6250bd1fc11559aa6050aeb8f827754ed57b7c1 | gongfei6644/gongfei | /gongfei/month03/tkinter/code/mycal.py | 596 | 3.53125 | 4 |
import tkinter
root = tkinter.Tk()
entry1 = tkinter.Entry(root) # 被加数
entry2 = tkinter.Entry(root)
label_plus = tkinter.Label(root,text='+')
def onCal():
s1 = entry1.get()
s2 = entry2.get()
try:
result = int(s1) + int(s2)
s = str(result) # 转为字符串
label_result.config(text=s)
ex... |
3f59286d27350f6d7f805ce1928f373cdbceefc7 | gongfei6644/gongfei | /renting-std/test/test_datetime.py | 1,148 | 3.53125 | 4 | # -*- coding: utf-8 -*-
import unittest
from datetime import datetime
from datetime import time
from datetime import timedelta
class DateTimeTestCase(unittest.TestCase):
def test_01(self):
print("time: {}, {}".format(datetime.today(), datetime.today()))
print(datetime.combine(datetime.now(), tim... |
d1d10772ad8583c237ed1fa7b078f8d411fd262c | TJHasel/daillyhealthtracker | /classes.py | 3,770 | 4.375 | 4 |
class User():
'''
A class object to contain information on the user's current weight,
ideal weight, and calculate ideal intake to achieve their weight goals
Attributes:
__current_weight (int): The user's current weight in lbs
ideal_weight (int): The user's target weight to be achieved in... |
589a1cc68dd12ec8d8ee9b3916cd855fd73d6867 | jr1980239/uno | /practica2.py | 577 | 4.0625 | 4 | # es la ruta de instalacion de python esto del shebang
#!/usr/local/bin/python
print ("------- TIPO DE DATOS -----------")
#tipo de datos ---> Para comentarios el #
# ctrl + / par ponerle a todas las lineas los comentarios..
print(type (10))
print(type (5.5))
print(type (1+5j))
print (2+4)
print (8**3)
print((1+5j... |
1cd127a876cbb72785ada904f2c2e2bae0cf2c38 | jr1980239/uno | /practica8.py | 1,140 | 3.78125 | 4 | #OPERACIONES CON CADENAS DE CARACTERES
datos = "usuario\contraseña\correo"
datos = "fmalo\\123456\\fmalo@espol.edu.ec"
print(datos)
print(len(datos))
print("total de back-slash:", datos.count("\\"))
usuario = datos[:datos.find("\\")]
print(usuario)
inicio = datos.find("\\") + 1
posi = datos.find("\\", inicio)
corre... |
3ffdfad5cc04e93d0d35ee0b858050ae4afd5b1e | jr1980239/uno | /practica22.py | 566 | 3.9375 | 4 | #DICCIONARIOS
d = {1:"test", 1.1:[5,7,"otro test"], "tercer":"otra cadena", (1,0):5}
"""
print(d[1])
print(d[1.1])
print(d["tercer"])
print(d[1,0])
print(d[1,1])
print(d[5:4])
d[3]="Nuevo elemento"
d[1]="Reemplazo de valor"
del d[1.1]
print(d)
print(d.keys())
print(d.values())
print(d.items())
# recorrer un dic... |
a784ff05ed4bb91af14eb1d47bca794cb6032257 | wangyum/Anaconda | /pkgs/statsmodels-0.6.1-np110py27_0/lib/python2.7/site-packages/statsmodels/sandbox/formula.py | 22,903 | 3.609375 | 4 | """
Provides the basic classes needed to specify statistical models.
namespace : dictionary
mapping from names to data, used to associate data to a formula or term
"""
from statsmodels.compat.python import (iterkeys, lrange, callable, string_types,
itervalues, range)
import copy
... |
d1b32712f93a4472b32f652ede216932bc5e46fa | wangyum/Anaconda | /lib/python2.7/site-packages/FuncDesigner/examples/PythonFuncs.py | 1,015 | 3.71875 | 4 | # The example illustrates how oovars can pass through ordinary Python functions
# provided FuncDesigner has appropriate overloads for all functions/operators used inside those ones
from FuncDesigner import *
a, b, c = oovars('a', 'b', 'c')
def func1(x, y):
return x+4*y
func2 = lambda x, y, z: sin(x)+4*y+3*... |
8bf4dc504494b622c88135a2caea2b83b570ce66 | wangyum/Anaconda | /pkgs/networkx-1.11-py27_0/lib/python2.7/site-packages/networkx/generators/community.py | 11,832 | 3.796875 | 4 | """Generators for classes of graphs used in studying social networks."""
import itertools
import math
import random
import networkx as nx
# Copyright(C) 2011 by
# Ben Edwards <bedwards@cs.unm.edu>
# Aric Hagberg <hagberg@lanl.gov>
# All rights reserved.
# BSD license.
__author__ = """\n""".join(['Ben Edw... |
07723a65219e6734965ece13067f53d6d4c85b25 | wangyum/Anaconda | /pkgs/jedi-0.9.0-py27_0/lib/python2.7/site-packages/jedi/evaluate/dynamic.py | 4,936 | 3.796875 | 4 | """
One of the really important features of |jedi| is to have an option to
understand code like this::
def foo(bar):
bar. # completion here
foo(1)
There's no doubt wheter bar is an ``int`` or not, but if there's also a call
like ``foo('str')``, what would happen? Well, we'll just show both. Because
th... |
e990b83e19fbd16a2ac90d54b505cd53db11d8c8 | wangyum/Anaconda | /lib/python2.7/site-packages/networkx/algorithms/shortest_paths/generic.py | 11,600 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Compute the shortest paths and path lengths between nodes in the graph.
These algorithms work with undirected and directed graphs.
"""
# Copyright (C) 2004-2015 by
# Aric Hagberg <hagberg@lanl.gov>
# Dan Schult <dschult@colgate.edu>
# Pieter Swart <swart@lanl.gov>
# All righ... |
9494fdc823b30663642cb94506fe19dbce6b3877 | wangyum/Anaconda | /Examples/bokeh/embed/embed_responsive_width_height.py | 2,571 | 3.84375 | 4 | """ This example shows how a Bokeh plot can be embedded in an HTML
document, in a way that the plot resizes to make use of the available
width and height (while keeping the aspect ratio fixed).
To make this work well, the plot should be placed in a container that
*has* a certain width and height (i.e. non-scrollable),... |
c449a7d629944e3629e1b3d5037c42829463e2a7 | wangyum/Anaconda | /lib/python2.7/site-packages/networkx/algorithms/centrality/communicability_alg.py | 13,964 | 3.671875 | 4 | """
Communicability and centrality measures.
"""
# Copyright (C) 2011 by
# Aric Hagberg <hagberg@lanl.gov>
# Dan Schult <dschult@colgate.edu>
# Pieter Swart <swart@lanl.gov>
# All rights reserved.
# BSD license.
import networkx as nx
from networkx.utils import *
__author__ = "\n".join(['Aric Hagberg (... |
74355b4b8eca6c2a6bce299ed9ad73dedefd95e3 | wangyum/Anaconda | /lib/python2.7/site-packages/sympy/geometry/point.py | 28,721 | 3.671875 | 4 | """Geometrical Points.
Contains
========
Point
Point2D
Point3D
"""
from __future__ import division, print_function
from sympy.core import S, sympify
from sympy.core.compatibility import iterable
from sympy.core.containers import Tuple
from sympy.simplify import nsimplify, simplify
from sympy.geometry.exceptions imp... |
c157164b7cf7fcc98e492997fa75359ca78538f1 | wangyum/Anaconda | /lib/python2.7/site-packages/FuncDesigner/examples/eig1.py | 2,334 | 3.53125 | 4 | # An example of FuncDesigner eigenvalues/eigenvectors for a linear equations system,
# see http://openopt.org/EIG for more examples and details
from FuncDesigner import *
from numpy import arange
n = 100
# create some variables
a, b, c = oovar('a'), oovar('b', size=n), oovar('c', size=2*n)
# let's construct some linea... |
6d600bb36a3fc76156b0bf99118689b55f75e857 | wangyum/Anaconda | /pkgs/networkx-1.11-py27_0/lib/python2.7/site-packages/networkx/generators/threshold.py | 28,794 | 3.546875 | 4 | """
Threshold Graphs - Creation, manipulation and identification.
"""
__author__ = """Aric Hagberg (hagberg@lanl.gov)\nPieter Swart (swart@lanl.gov)\nDan Schult (dschult@colgate.edu)"""
# Copyright (C) 2004-2015 by
# Aric Hagberg <hagberg@lanl.gov>
# Dan Schult <dschult@colgate.edu>
# Pieter Swart <swart@l... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.