blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
bedb2a2c70ec6fd13f34ff94a64e891bf4bc2011 | xuaijingwendy/Class-assignment-29 | /循环/while.py | 96 | 4 | 4 | count = 0
while(count<9):
print ('The count is:',count)
count=count+1
print("Good bye!") |
707e6fba10638bed204c624e0a36f8ced3361c52 | SmischenkoB/campus_2018_python | /Viktor_Miroshnychenko/2/armstrong_numbers.py | 631 | 4 | 4 | def is_amstrong_number(number):
"""
:param number: - number to check weather it is an amstrong number
:type number: - str or int
:return: - True if param1 is Amstrong number, False otherwise
:rtype: - bool
"""
if isinstance(number, int):
number = str(number)
power = len(num... |
54f6465964e4e96a7d5214571a6b087995f7df7c | gargshiva/Python-DataStructureAlgo | /search/RotatedArray.py | 1,364 | 4.15625 | 4 | # Search an element in sorted and rotated array
def find_element(arr, element):
end = len(arr) - 1
pivot_index = find_pivot_index(arr, 0, len(arr) - 1)
print("Pivot Index : {} ".format(pivot_index))
if arr[pivot_index] == element:
return pivot_index
elif arr[pivot_index + 1] <= element <= a... |
a8ce8ce0b486f7c7d7315ebbe69c6aa7d83bb1da | Anoopsmohan/Python-Recursion | /fact_tail.py | 89 | 3.796875 | 4 | def fact(f,n):
if n==1:
return f
else:
return fact(f*n,n-1)
a=fact(1,3)
print a
|
1fedad368df49d614f0dd93616a762794e071ce8 | TurcsanyAdam/Gitland | /if10.py | 371 | 4.03125 | 4 | A = int(input("Give length of A side: "))
B = int(input("Give length of B side: "))
C = int(input("Give length of C side: "))
if (A*A + B*B) == C*C:
print("Derékszögű a háromszög")
elif(A*A + C*C) == B*B:
print("Derékszögű a háromszög")
elif(B*B + C*C) == A*A:
print("Derékszögű a háromszög")
else:
prin... |
98dc0711e54f8bab427585b0ca29fdbda326ae08 | jkcadee/A01166243_1510_labs | /Lab01/Valid and Invalid.py | 398 | 3.84375 | 4 | # 1. X = 1 is valid as you are just assigning an int value to a variable
# 2. X = Y is invali as Y does not have an assigned value
# 3. X = Y + 2 is invalid as Y does not have an assigned value
# 4. X + 1 = 3 is invalid as an operator cannot be on the variable side of an assignment
# 5. X + Y = Y + X is invalid as Y is... |
4d32355a45ad4d23d1fcdacd2e6e76ab2f4aa38f | lucasjct/app-flask | /overview/aula4/views.py | 487 | 3.734375 | 4 | from flask import Flask, request
"""Extensão Flask"""
def init_app(app: Flask):
@app.route('/')
def index():
print(request.args)
return "Hello Codeshow"
@app.route('/contato')
def contato():
return "<form><input type='text'></input></form>"
def page_other(app: Flask):
... |
f3ba86deeaf11d66c18813d381e74d3126905aa9 | ameeli/algorithms | /leetcode/range_sum_of_bst.py | 780 | 4.03125 | 4 | """
Given the root node of a binary search tree, return the sum of values of all
nodes with value between L and R (inclusive).
The binary search tree is guaranteed to have unique values.
Example 1:
Input: root = [10,5,15,3,7,null,18], L = 7, R = 15
Output: 32
Example 2:
Input: root = [10,5,15,3,7,13,18,1,null,6],... |
18da413dc6b5dfd2739d90f56474aa64d250a372 | jessicanina23/Jhessy | /Nina03.py | 167 | 4.0625 | 4 | # Calcular a área de uma circunferência
import math
raio = float(input("informe o raio: "))
area = math.pi * raio ** 2
print("Área do círculo", raio, "=", area)
|
6ba2ed11bb6c13d8677c76c45bb9a150f372100a | SI507-Waiver-Fall2018/si-507-waiver-assignment-f18-scarescrow | /part3.py | 1,810 | 3.75 | 4 | # these should be the only imports you need
import requests
from bs4 import BeautifulSoup
# My full name is Sagnik Sinha Roy
# My UMich uniqname is sagniksr
# write your code here
# usage should be python3 part3.py
URL = "https://www.michigandaily.com"
if __name__ == "__main__":
# First, use the HTTP GET method ... |
a4f9327fcbaeb8ab3a89f9624f244f51e5170728 | Hamiltonxx/pyalgorithms | /ds_tutorial/count_possible_paths.py | 187 | 3.5 | 4 |
def dfs(u,v,visited=[]):
visited.append(u)
for w in graph[u]:
if w==v:
return visited
elif w not in visited:
dfs(w,v,visited)
|
626bcc62f786c5cfb15559748a7cd7005d3e4a01 | Josh-Cruz/python-strings-and-list-prac | /PYthon_Dict_basics.py | 335 | 3.796875 | 4 | josh_C = {
"name": "Josh",
"age": 30,
"country": "Murica",
"fav_lan": "Python"
}
def print_info(dict):
print "My name is", dict["name"]
print "My age is", dict["age"]
print "My country of origin is", dict["country"]
print "My favorite language to code in is", dict["fav_lan"]
print(prin... |
c55595f6e05e605302f2f111569d16f0d1f08eeb | w2kzx80/py_algs | /7/1.py | 1,441 | 3.953125 | 4 | # 1. Отсортируйте по убыванию методом пузырька одномерный целочисленный массив, заданный случайными числами на
# промежутке [-100; 100). Выведите на экран исходный и отсортированный массивы.
# Примечания:
# a. алгоритм сортировки должен быть в виде функции, которая принимает на вход массив данных,
# b. постарайтесь сде... |
5a1e6ef7f70370ee7372b8de5a1b00e64c5174c7 | deepakmanktalaomni/python | /check year.py | 821 | 3.96875 | 4 | y = int(input("Year: "))
m = int(input("Month: "))
d = int(input("Day: "))
if 0 <= y and 0 < m < 13 and 0 < d < 32: #Check whether date is under limit.
if m in (4,6,9,11):
if d > 30:
print("<Wrong>")
else:
print("<Correct>")
elif y % 4 == 0: # Every 4 year ... |
3e9200da78d1b19e12f750d505a0e26383da9abd | Diando-Re12/OOP-Python | /OOP-python/Try-Except/pengujian-error.py | 998 | 3.9375 | 4 | #try except adalah proses pengujian error pada sebuah program hal ini sangat bermanfaat untuk mengetahui segala kesalahan dan memberikan peringatan
#kondisi ketika benar
'''
x=30
try:
print(x)
except:
print("ERROR")
'''
#kondisi ketika salah
'''
try:
print(x)
except:
print("ERROR")... |
f0a4f4733475075925dd9d7c2bd4c5547f5412bd | neelbhuva/Data-Mining | /HW4/wine.py | 1,053 | 3.515625 | 4 | import pandas as pd
import numpy as np
import math
import matplotlib.pyplot as plt
def plotHisto(df):
fig = plt.figure(figsize=(20,15)) #Creating a new figure with the mentioned figure size
cols = 4 # No of columns to display the charts
rows = 4 # No of rows to display the charts. These numbers are... |
8ee2a2458302eea90d63fce71e13dcf78d71d5d2 | TarPakawat/Python | /Bowling.py | 330 | 3.625 | 4 | Frame # = 1
d = 10
while Frame <= 10:
if d == 10:
d = int(input("Number of pins down: "))
s = 10
Frame # = Frame # + 1
elif d < 10:
e = 10-d
d = int(input("Number of pins down (0-%d)" % e))
if d = e:
s = 10
elif d != e:
s = 10 - e
print("Total score is... |
b647265accef90bafb57f008c8c52c431390bea8 | adityamhatre/DCC | /dcc #9/largest_sum_of_non_adjacent_numbers.py | 3,095 | 4.34375 | 4 | import unittest
"""Given a list of integers, write a function that returns the largest sum of non-adjacent numbers. Numbers can be 0
or negative.
For example, [2, 4, 6, 2, 5] should return 13, since we pick 2, 6, and 5. [5, 1, 1, 5] should return 10,
since we pick 5 and 5.
Follow-up: Can you do this in O(N) time and... |
9973f705b4ab1413c8e22632c7914296b5f09496 | hmoshabbar/Make_Estimate_anout_Earth_land_using_python-_code | /mean.py | 4,797 | 3.890625 | 4 | print " Workout the quantity of earth for an embankment 150m long Wide at the top.Side slope is 2:1"
print "and depts at each 30m interval are 0.60,.1.2,1.4,1.6,1.4, and 1.6 m "
Station=int(input("Enter Your Station:"))
width=int(input("Enter Your Wide:"))
side=int(input("Enter Your Side:"))
depth1=float(input("... |
d56c0cea3d9aaf18e0876cb3efb7db860b2c3715 | jaredchin/Core-Python-Programming | /第七章/练习/7-3.py | 141 | 3.890625 | 4 | adict = {'a':1,'b':2,'c':3,'d':4,'e':5}
print(sorted(adict))
for key in sorted(adict):
print('key %s has value %s' % (key, adict[key]))
|
8c56579272069351508a2d05d4086edffc062283 | ralex1975/rapidpythonprogramming | /chapter7/list2.py | 149 | 3.734375 | 4 | """
list2.py
Chapter 7 Cool Features of Python
Author: William C. Gunnells
Rapid Python Programming
"""
output = [i for i in range(10) if i > 3]
print(output)
|
5e48c8eff3d887ea6eac04e02eb4d0792f405e61 | protea-ban/programmer_algorithm_interview | /CH2/2.6/stack2queue.py | 1,220 | 4.3125 | 4 | # 用两个栈来模拟队列操作
# 基本栈
class Stack():
def __init__(self):
self.items = []
def isEmpty(self):
return len(self.items) == 0
def size(self):
return len(self.items)
def top(self):
if not self.isEmpty():
return self.items[len(self.items)-1]
else:
... |
692bd543de0c74ef98ca5377bb4afad5750d58ad | imercadovazquez/lab14_bdd | /retirement.py | 6,192 | 3.96875 | 4 | """
REATTEMPT ASSIGNMENT
This module contains functions for calculating retirement age and date.
The private validation functions parse and validate correct input values.
The public calculation functions validate inputs and calculate the desired values.
Write unit tests using pytest for the following functions... |
263cfb3234309a92b07af84f16b0df57eb350433 | jillvp/Personal_Projects | /Star Wars Mad Libs Game/madlibs.py | 1,679 | 3.890625 | 4 | # A GALAXY APART: STAR WARS YOUR WAY AD-LIB
print("<<<<<<<<<<<<<<<<<<<<<<<<< Mad Libs - A Galaxy Apart >>>>>>>>>>>>>>>>>>>>>>>>>")
name = input("Tell me your name, and click enter. ")
adj1 = input("Tell me an adjective, and click enter. ")
verb1 = input("Tell m... |
51ecc647f2c6c292f362031d6d4da1f2806bffa3 | akhilerm/Google-Foobar | /hall.py | 227 | 3.5625 | 4 | def answer(s):
salutes = 0
people = 0
for person in s:
if person == '-':
continue
elif person == '>':
people+=1
else:
salutes+=people
return salutes*2
|
de39263bfe2edf8523d682ae57229353988956ba | DarioCampagnaCoutinho/logica-programacao-python | /modulo01-introducao/exercicios/exercicio02.py | 146 | 4.15625 | 4 | fahrenheit = float(input('Digite a temperatura em Fahrenheit : '))
celsius = 5 * (fahrenheit - 32) / 9
print('Celsius = {:,3f}'.format(celsius)) |
f33e74e815f71661cd66bc5053117aa936650cf0 | Bralor/python-workshop | /materials/03_loops/kosik.py | 1,504 | 3.875 | 4 | #!/usr/bin/python3
""" Lekce #4 - Uvod do programovani, Nakupni kosik """
kosik = {}
ODDELOVAC = "=" * 40
POTRAVINY = {
"mleko": [30, 5],
"maso": [100, 1],
"banan": [30, 10],
"jogurt": [10, 5],
"chleb": [20, 5],
"jablko": [10, 10],
"pomeranc": [15, 10]
}
print(
"VITEJTE V NASEM VIRTUALNIM OBCHODE".cente... |
3e56d735450ffcc007bd34fbb5bfe3f4ce690bb7 | Xzooan/Profit-and-loss-finder | /Profit and loss finder.py | 373 | 3.921875 | 4 |
sp=float(input("The selling price="))
print(sp)
cp=float(input("The cost price="))
print(cp)
if sp>cp:
profit=sp-cp
print("Profit",'=',profit,'rupees')
_profit=profit*100/cp
print("Profit %",'=',_profit)
else:
loss=cp-sp
print("Loss",'=',loss,'rupees')
_loss=loss*100/cp
print("Los... |
c1194b1f3716bbec4b024f3c3f7868f0f46663c8 | skybrim/practice_leetcode_python | /offer/algorithm/left_rotate_string.py | 801 | 4 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@file: left_rotate_string.py
@author: wiley
@datetime: 2020/7/10 9:57 AM
左旋转字符串
字符串的坐旋转操作是把字符串前面的若干个字符转移到字符串的尾部。
请定义一个函数,实现字符串左旋转操作的功能。
举例:输入字符串 "abcdefg" 和数字 2,该函数将返回左旋转两位得到的结果 "cdefgab"
"""
def reverse_left_words(s, n):
"""
@param s: str
@param n: int
... |
d8f0788ab9863873ec8a4e2f726c14b19a09b2f6 | chenyan198804/myscript | /08day4/Virtuallife/Person.py | 381 | 3.59375 | 4 | #!/usr/bin/env python
#_*_coding:utf-8_*_
class Person(object):
def __init__(self,name,age,sexuality,work,salary,special):
self.name = name
self.age = age
self.sexuality = sexuality
self.work = work
self.salary = salary
self.special = special
def talk(se... |
1a7f97129c40da6128270dcfef3c3a00d98331a8 | jasonrbriggs/python-for-kids | /ch7/silly-age-joke.py | 243 | 3.734375 | 4 | import sys
def silly_age_joke():
print('How old are you?')
age = int(sys.stdin.readline())
if age >= 10 and age <= 13:
print('What is 13 + 49 + 84 + 155 + 97? A headache!')
else:
print('Huh?')
silly_age_joke() |
9da523e6173bf2b65f12e18e994f6b782ae64a67 | Dinosurr/nackademinlabb | /funcs/bubblesort2.py | 329 | 3.984375 | 4 | def bubblesort(myList):
for item in range(len(myList)):
for i in range(len(myList)-1):
if myList[i] > myList[i+1]:
myList[i], myList[i+1] = myList[i+1], myList[i]
numList = [1, 5, 6, 7, 8, 2, 3, 4, 5, 6, 1, 8,
9, 4, 243, 23, 12, 19, 54, 43]
bubblesort(numList)
print... |
1f1da13ecc052004707b6fd4eb9c80e11c3813ac | omkar-javadwar/CodeWars | /katas/kyu_6/What_century_is_it?.py | 696 | 4.09375 | 4 | # https://www.codewars.com/kata/52fb87703c1351ebd200081f/train/python
'''
Instructions :
Return the inputted numerical year in century format. The input will always be a 4 digit string. So there is no need for year string validation.
Examples:
"1999" --> "20th"
"2011" --> "21st"
"2154" --> "22nd"
"2259" -->... |
2a79f5ddd1f8e2066759afe2081d87494014da94 | Melifire/CS120 | /Projects/Short 9/Part 1/TestCases/tree_generator.py | 2,142 | 4.65625 | 5 | #! /usr/bin/python3
"""Generates a snippet of code, which represents a randomly-generated binary
tree. Note that this is *NOT* a BST; the arrangement of nodes is random.
However, the values in the tree are unique.
This will never generate a tree that is empty; if you want to test that,
write a testcase b... |
df0b2bcc3b11d7718707dd508ef06d3382c3ae86 | rookuu/AdventOfCode-2015 | /Day 5/Puzzle 1.py | 1,341 | 3.609375 | 4 | #!/usr/bin/env python
"""
Solution to Day 5 - Puzzle 1 of the Advent Of Code 2015 series of challenges.
--- Day 5: Doesn't He Have Intern-Elves For This? ---
Needs to apply sets of conditions to series of strings to determine whether they're valid or not.
-----------------------------------------------------
Autho... |
f25d29fe23ca284be847e4cfdfae80a4e90ec6a8 | hhsue-zz/leetcode | /RotateArray/mine2.py | 748 | 3.578125 | 4 | #!/usr/bin/python
#[0,1,2,3,4,5,6]
#[4,5,6,0,1,2,3]
class Solution:
# @param {integer[]} nums
# @param {integer} k
# @return {void} Do not return anything, modify nums in-place instead.
def rotate(self, nums, k):
mod = k % len(nums)
d = {} #{index:value}
for i in range(0,len(n... |
545289f41e7a6165308cbbf488c6d5d852d5b3ea | Drunk-Mozart/card | /DL_09_while sum.py | 329 | 3.734375 | 4 | i = 0
summary = 0
while 100 >= i:
summary += i
i += 1
print(summary, i)
i = 0
summary = 0
while 100 >= i:
summary += i
i += 2
if i == 2:
break
print(i)
print(summary, i)
i = 0
result = 0
while i <= 100:
i += 1
if i % 2 == 1:
continue
print(i)
result += i
print(r... |
c74d086a397a11968b3a17e31dc6db6ec87efcad | emma-rose22/practice_problems | /test_scratch.py | 5,668 | 4 | 4 | '''
Given a string s consisting of small English letters, find and return the first instance of a non-repeating character in it. If there is no such character, return '_'.
Example
For s = "abacabad", the output should be
first_not_repeating_character(s) = 'c'.
There are 2 non-repeating characters in the string: 'c' ... |
9f3e2d3e174e86a1258b44c2210140fa96f2aaac | vup999/test | /test2.py | 830 | 4.125 | 4 | # Numbers
# str()
# num1=28
# print (str(num1))
# print(str(num1) + ' days in FEB')
# print('------------------')
# int() & float()
# f_num='5'
# l_num='6'
#
# print (int(f_num) + float(l_num))
# print (int(f_num) + int(l_num))
# datetime
from datetime import datetime, timedelta
today=datetime.now()
print(... |
f5e09e5a5bb643433eb3b2667dab357784da3764 | ikki2530/holberton-system_engineering-devops | /0x16-api_advanced/1-top_ten.py | 627 | 3.53125 | 4 | #!/usr/bin/python3
"""
queries the Reddit API and prints the titles of the first 10 hot posts
listed for a given subreddit.
"""
import requests
def top_ten(subreddit):
"""top ten subreddits titles"""
if subreddit:
try:
heads = {'User-agent': 'dagomez2530'}
url = "https://www.re... |
cc7605a35008024a7e9fd950660344ba733f4956 | mesrop1665/My_works | /index.py | 177 | 3.671875 | 4 | def square_digits(num):
r = ""
for i in range(len(str(num))):
i = str(num)[i]
r += str(int(i)*int(i))
return int(r)
square_digits(1222) |
e83973796de3bb19f60be9d5572f4c1b6fe91c94 | adichamoli/LeetCodeProblems | /013 - Insert Interval/Solution3.py | 657 | 3.53125 | 4 | '''156 / 156 test cases passed. Status: Accepted
Runtime: 68 ms Memory Usage: 17.5 MB'''
class Solution:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
if not intervals:
return [newInterva... |
dead4328b7352e2b6899022301a27b1ed97beb1e | TorpidCoder/Python | /W3School/StringPractice/10.py | 186 | 3.828125 | 4 | word_1 = input("enter word 1 : ")
word_2 = input("enter word 2 : ")
word3 = word_1.replace(word_1[0] , word_2[0])
word4 = word_2.replace(word_2[0],word_1[0])
print(word3)
print(word4)
|
91a3327e2c6054571efd3d5957de8e28f4094d3f | kevapostol/holbertonschool-higher_level_programming | /0x0B-python-input_output/1-number_of_lines.py | 326 | 3.65625 | 4 | #!/usr/bin/python3
'''
The 1-number_of_lines module
'''
def number_of_lines(filename=""):
'''A function that returns the number of lines of a text file'''
count = 0
with open(filename, encoding='UTF-8') as a_file:
'''Opens a file'''
for line in a_file:
count += 1
return ... |
aa1453f8b9e83bc1895880b001605278feeaf13c | cp1372/Project-Euler-Solutions | /problem 203.py | 798 | 3.609375 | 4 | import math
def primes(n):
""" Returns a list of primes < n """
sieve = [True] * n
for i in xrange(3,int(n**0.5)+1,2):
if sieve[i]:
sieve[i*i::2*i]=[False]*((n-i*i-1)/(2*i)+1)
return [2] + [i for i in xrange(3,n,2) if sieve[i]]
def choose(n, r):
result = math.factorial... |
b91729900536a787a5b71f947a98891d7d61c45f | Jhonierk/holbertonschool-low_level_programming | /0x1C-makefiles/5-island_perimeter.py | 1,602 | 4.15625 | 4 | #!/usr/bin/python3
"""defines island_perimeter module"""
def island_perimeter(grid):
"""Returns perimeter of island"""
perimeter = 0
for row in range(len(grid)):
# print(row) # 0, 1, 2, 3
for column in range(len(grid[row])):
# print(grid[row][column]) #actual values
... |
e25dbffe213cfa3b3affb2747f45ac5154431d8a | cristinarivera/python | /130.py | 1,023 | 3.71875 | 4 | print 'MAXIMO COMUN DIVISOR'
a = int(raw_input('ingrese primer nro: '))
b = int(raw_input('ingrese segundo nro: '))
c = int(raw_input('ingrese tercer nro: '))
mcd = 0
if c < a > b:
if b < c:
for i in range(1, b+1):
if a % i ==0 and b % i ==0 and c % i ==0:
mcd = i
print 'mcd:', m... |
2c807876754d385787da7ad9036bc550dc6f807a | techyphob/python | /Leap Year/main (1).py | 544 | 4.0625 | 4 | def isYearLeap(year):
if year % 4 == 0:
if year % 100 == 0 and not year % 400 == 0: leap = False
else: leap = True
else: leap = False
return leap
def daysInMonth(year, month):
months30 = [4,6,9,11]
if month == 2:
if isYearLeap(year): return 29
else: return 28
... |
3e926e32c664603be1eb57cb868a90777fb1af3d | ji-eun-k/crawler | /7_example.py | 230 | 3.5 | 4 | f = open("예외처리연습.txt", "r", encoding="utf-8")
txt = f.readlines()
try:
n = int(input())
for i in range(n):
print(txt[i])
except IndexError:
print('모든 행이 출력완료 되었습니다') |
69e57f3485777a5f5c1fa605045aea3834a7940e | Piropoo/alura-jogos-python | /forca/forca_lib.py | 4,400 | 3.796875 | 4 | import random
from os import read, stat_result
# Definindo funções
def abertura():
print('\n' + '\033[34m=\033[m'*20, 'Forca', '\033[34m=\033[m'*20)
print('Bem vindo ao jogo da forca!\n')
def lendo_arquivo_palavras() -> list:
arquivo_palavras = open('palavras.txt', 'r', encoding='UTF-8')
palavras ... |
2b25fba87e4fd78db5fb6e7276db52a9237def03 | YuriiKhomych/ITEA-advanced | /Yurii_Khomych/1_functions/hw/comprehensions.py | 241 | 3.953125 | 4 | print({x for x in range(-9, 10)})
print({x: x ** 3 for x in range(5)})
input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7]
list_using_comp = [var for var in input_list if var % 2 == 0]
print("Output List using list comprehensions:", list_using_comp) |
ccf6d5e41fe04d1779cdcae5d5a52a77b6e8f4ed | savorywatt/testing | /perceptron.py | 6,357 | 3.5625 | 4 | from random import random
from random import shuffle
MAX_EPOCHS = 10
class Perceptron(object):
def __init__(self, weight_keys):
self.weights = {weight_key: random()
for weight_key in weight_keys}
self.threshold = random()
self.learning_rate = random()
sel... |
db9ce863e4b5ea19e7387936f01835df22910ef5 | SashoStoichkovArchive/HB_TASKS | /projects/week10/08_05_2019/BCC/business_card.py | 3,426 | 4.03125 | 4 | import sqlite3, sys, os, pprint
def print_menu():
c = str(input(">>> Enter command: "))
if c == 'help':
print(
"""
#############
###Options###
#############
1. `add` - insert new business card
2. `list` - list all business cards
3. `get` - display full information for a certain business card (`ID` is... |
bda474719a7aab99cd2dced41bb8771e14476ae5 | swaathe/py | /pdt.py | 146 | 3.671875 | 4 | total = 1
n=[int(n) for n in input("enter the elements with whitespaces:").split()]
for i in range(0, len(n)):
total *= n[i]
print (total) |
2c8b33aaa502030497341bb22e90d57dc814f93d | yongyaoli/pystudy | /sample/c13.py | 1,139 | 3.59375 | 4 | #! /usr/bin/env python3
# -*- coding:utf-8 -*-
'''
BIF 函数 filter
filter:接收一个函数和序列,把传入的函数依次作用于每个序列元素,根据返回值说True还是False决定是否保留该元素
BIF 函数 sorted
排序: sorted函数可以对list进行排序
返回函数: 函数作为返回值
匿名函数:
list(map(lambda x: x * x, [1, 2, 3, 4, 5]))
关键词lambda 表示匿名函数,冒号前的x 表示函数参数
匿名函数只能是一个表达式,不用return
'''
# 保留奇数
def is_odd(n):
''... |
a0ebbca376a7d0709406c2af53ff9768b7206509 | ericgarig/daily-coding-problem | /021-min-classrooms.py | 813 | 3.859375 | 4 | """
Daily Coding Problem - 2018-10-28.
Given an array of time intervals (start, end) for classroom lectures
(possibly overlapping), find the minimum number of rooms required.
For example, given [(30, 75), (0, 50), (60, 150)], you should return 2.
"""
def min_classrooms(interval_list):
"""Given a list of time in... |
a42fed93c707d7473fb77c4fdcf811db24799241 | selvendiranj-zz/python-bchain | /transactions.py | 1,600 | 3.9375 | 4 | """
validate transactions and update balance(state) functions
"""
def updateState(txn, state):
"""
We will take the first k transactions from the transaction buffer, and turn them into a block
"""
# Inputs: txn, state: dictionaries keyed with account names,
# holding numeric values for transfer amo... |
bdcd0a4b0fe6a8b20396666d6204bd4bccdd8fdc | itadh/python_scripts | /count_things2.py | 86 | 3.625 | 4 | #!/usr/bin/python3
satz = input('Bitte geben Sie einen Satz ein: ')
print(len(satz))
|
54a7374c2e3ee73e5bb9fde51bbd628aa68a6bff | ufp1000/Python | /Graphs/Bachelor_Graph.py | 365 | 3.5625 | 4 | #import bokeh for plotting graph
from bokeh.plotting import figure
from bokeh.io import output_file,show
import pandas
#prepare some test data
df=pandas.read_csv("bachelors.csv")
x=df["Year"]
y=df["Engineering"]
#prepare the output file
output_file("Line from Bachelors.html")
print(df)
#create a figure object
f=fig... |
759a0c8825caeeed2c61825efc9d3f59d8f17a99 | narhumo/Short-joke-bot | /main.py | 2,508 | 3.59375 | 4 | import time
import random
while True:
Q = input(">").rstrip().lower()
jokes = []
jokes.append(['What did the skeleton say when he got spooked?', 'He was chilled to the bone!'])
jokes.append(["Why do archeologists keep dinosuar bones on their car?", "Because they're fossil fuels!"])
jokes.append(["Why d... |
0f5d283dae3af23815d2404abb3bb8da1c93a8b6 | bhattaraijay05/prg | /area_of_circle.py | 422 | 4.40625 | 4 | # from math import pi
# radius_of_circle=int(input("Enter the area of the circle "))
# area_of_circle=pi*radius_of_circle**2
# print("The area of the circle with radius: %.2f"%area_of_circle)
from math import pi
radius_of_circle = int(input("Enter the area of the circle "))
area_of_circle = pi * radius_of_circle ** ... |
14b93f99b82243e6e2344086e529e084bc1f9534 | nymous-experiments/python-memory-game-forma-git-2021 | /outro.py | 656 | 3.609375 | 4 | from tkinter import *
from tkinter.font import Font
def show_victory(old_root):
old_root.destroy()
victory_screen = Tk()
victory_screen.title("Règles")
victory_screen.geometry("+300+100")
victory_screen.resizable(0, 0)
victory_screen.bind("<Escape>", lambda event: exit())
victory_screen.bi... |
6c4d38f9bf65685d9bbae420787da7cd31cc45e2 | Bouananhich/Ebec-Paris-Saclay | /user_interface/package/API/queries.py | 1,949 | 3.5625 | 4 | """Queries used with API."""
def query_city(
rad: float,
latitude: float,
longitude: float,
) -> str:
"""Create an overpass query to find the nearest city from the point.
:param rad: Initial search radius.
:param latitude: Latitude of the point.
:param longitude: Longitude of ... |
e856b1f96d08d75ebc73145f541f7f33908b7be1 | lucioeduardo/cc-ufal | /APC/Listas/06 - Recursão/q2.py | 408 | 3.921875 | 4 | """
Implemente uma função recursiva que, dados dois
números inteiros x e n, calcule o valor de x^n
"""
#O(n) - Solução óbvia
def exp(x, n):
if(n == 0):
return 1
return x*exp(x,n-1)
#O(log n) - Exponenciação rápida
def fast_exp(x, n):
if(n == 0):
return 1
if(n % 2):
return x*fa... |
5c49826b3547a26819a594531f242e84c6071741 | Boellis/ObjectDetection | /scripts/renameFile.py | 669 | 4.125 | 4 | import os
path = input("Enter the path or folder name: ") #This is the path relative to the directory this script is stored on (use / instead of \)
updatedFilename = input("Enter the updated name: ")
files = os.listdir(path)
print("Are sure you want to rename the following files?")
print(files)
awns = input("(y/n)... |
8c0ac6916ccb5209f031450a3c5ac51080f3071d | SarvagyaShastri/Algorithms | /Longest Increasing subsequence.py | 836 | 3.703125 | 4 | #LIS IN O(NLOGN)
def findIndex(sequence,value):
middle=0
beg=0
end=len(sequence)
while end-beg>1:
middle=beg+(end-beg)/2
if sequence[middle]>value:
end=middle
else:
beg=middle
return end
#
def find_lis(elements):
sequence=[]
sequence.append(elements[0])
for i in xrange(1,len(elements)):
if ... |
c2e8c30f998ffa148bc673ffacb926b49e890a83 | therealdavidbrown/Sprint-12062020---Dice-Simulator | /DB Sprint 12062020.py | 1,743 | 4.25 | 4 | import random
line = "_______________________________________________________________________________\n"
print("Welcome to\n \nDICE ROLL SIM 11\nThese go up to eleven.\n"+line)
print("This game is your one-size-fits-all for random number generationin games. You can generate random numbers for any polyhedral die, and it... |
d8dd6f51ee707aa26fc0db0354fe390d92f21c48 | xeon2007/machine-learning | /justin-python-ml/homeworks/hw1.py | 3,083 | 3.71875 | 4 | import numpy as np
import random
from pprint import pprint
import matplotlib.pyplot as plt
class Perceptron:
def __init__(self, training_set=None, testing_set=None, weights=None):
# Default weights to [0, 0, 0]
if weights == None:
self.weights = [0., 0., 0.]
else:
se... |
e039d4ef81bd553ec67eb5b516d7d986e5cfeced | lemonnader/LeetCode-Solution-Well-Formed | /greedy/Python/0435-non-overlapping-intervals(按起始点排序).py | 936 | 3.78125 | 4 | from typing import List
class Solution:
# 按照起点排序:选择结尾最早的,后面才有可能接上更多的区间
# 那么要删除的就是:与之前的区间有重叠的,并且结尾还比当前结尾长的
# 关键:如果两个区间有重叠,应该保留那个结尾短的
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
size = len(intervals)
if size <= 1:
return 0
intervals.sort(key=... |
12758d56534c5864e6c69b2e82bfa2891b8a6983 | jackhscompbook/VeryBadGraphingCalculator | /calc.py | 3,322 | 3.546875 | 4 |
import math
class calc:
def __init__(self):
self.coordinates = {}
self.tmp_x = 0
self.tmp_y = 0
self.x_max = 10
self.x_min = 1
self.y_max = 10
self.y_min = 1
self.x_step = (self.x_max - self.x_min)/10
self.y_step = (self.y_max - self.y_min)/10
def drange(self, start, stop, ste... |
1a9e141a9dacb746293a0bddc7ad9b3a1947b8e9 | maxpipoka/cursofullstack | /03_Tercera_clase/ejercicio_04.py | 937 | 3.6875 | 4 | # Enunciado
# Dada una lista (lista1 = [12, 15, 32, 42, 55, 75, 122, 132, 150, 180, 200]),
# iterarla y mostrar números divisibles por cinco, y si encuentra un
# número mayor que 150, detenga la iteración del bucle
import os
import sys
#################################################################################... |
1436dd0ea54a70520ad6ab3885853ca0f4f792a6 | nagagopi19/Python-programms | /weekbyacceptinganumber.py | 437 | 4.21875 | 4 | """
To display day of the week by accepting a number.
Author: K Naga Gopi
Version: v1.0
Company: Google Inc
Project: abc1234
Code:34_45
"""
n = int(input('Enter a number(1-7): '))
if n==1:
print('Sunday')
elif n==2:
print('Monday')
elif n==3:
print('Tuesday')
elif n==4:
print('Wednesday')
elif n==5:
... |
e7b5fe4016707db95e1cccaa5e78907ec9d41565 | sotiriskalogiros/python | /ασκηση 7.py | 270 | 3.796875 | 4 | from datetime import datetime
# Get a datetime object
now = datetime.now()
# General functions
print "Year: %d" % now.year
print "Month: %d" % now.month
print "Day: %d" % now.day
print "Weekday: %d" % now.weekday() # Day of week Monday = 0, Sunday = 6
|
b593a0038755848a41323b3e2379ca7aecb0fa0a | PaigeThePain/Fizz-Buzz | /fizz.py | 354 | 4.09375 | 4 | print("Welcome to Fizz Buzz\n")
number = int(input("Please enter a number to count up to."))
counter = 1
while counter <= number:
if counter % 3 == 0 and counter % 5 == 0:
print ("Fizz Buzz")
elif counter % 3 == 0:
print("Fizz")
elif counter % 5 == 0:
print("Buzz")
else:
... |
dd1fef5a62e98becb9e859b5ad3edd626537a4c2 | AhmedEssamIsmail/Virtual-Whiteboard | /Board.py | 358 | 3.53125 | 4 | import cv2 as cv
import numpy as np
def draw(board, first_point, second_point, color, thickness, inwardDist):
dist = np.sqrt(pow((first_point[0] - second_point[0]), 2) + pow((first_point[1] - second_point[1]), 2))
if dist < inwardDist:
cv.line(board, first_point, second_point, color, thickness)
c... |
cccca544fb364071e42ec8991e150a888160f48b | zhaolijian/suanfa | /huawei/6.py | 733 | 3.859375 | 4 | # 功能:输入一个正整数,按照从小到大的顺序输出它的所有质因子(重复的也要列举)(如180的质因子为2 2 3 3 5 )
# 最后一个数后面也要有空格
# 方法1
x = int(input())
flag = False
for i in range(2, x // 2 + 1):
while x % i == 0:
flag = True
print(i, end=' ')
x = x // i
if not flag:
print(x, end=' ')
# 方法2
x = int(input())
flag = False
for i in range... |
3bf4a8ac01f61d7e33f97821ad524444e95ffba9 | hihumi/renote | /sub.py | 630 | 4 | 4 | #!/usr/bin/env python3
"""renote: re sub module
"""
import re
def my_sub(word):
"""renote: re sub function
"""
pattern = re.compile(r'p')
res = pattern.sub('P', word)
if res:
print('{}'.format(res))
print('OK')
else:
print('NG')
if __name__ == '__main__':
pri... |
2c5873651cd6b9d0e8762f1490b944be6056651a | dlevylambert/project2-pd6 | /Group7/utils.py | 3,211 | 3.515625 | 4 | import urllib2
import json
from operator import itemgetter
def utils(url):
return json.loads(urllib2.urlopen(url).read())
def currentYear(item,year,dInd):
"""
item: Event data
year: last 2 digits of year (i.e. "12" or "13")
dInd: index of the time criteria to parse through (i.e. 12 = 'StartEvent... |
598f30422edb5efa30431dc3f24fecfcbe42ae6a | kayartaya-vinod/2017_08_PHILIPS_PYTHON | /Examples/userexceptions.py | 588 | 3.625 | 4 | # this and every file with .py is known as a module
# A module may comprise: variables, functions, classes, or some executable code
# variables, functions and classes from this module can be used in other modules
class InvalidAgeException(Exception):
def __init__(self, message = "Invalid age. Must be a number between... |
b8c5a0d5c26d9749b8b2b0dc79b07068c63914f8 | swayamsudha/python-programs | /per_sq.py | 258 | 4.15625 | 4 | ##WAP TO CHECK A NUMBER IF A PERFECT SQUARE OR NOT
num=int(input("Enter the number: "))
root=(num**0.5)
#print("root =",root)
n=int(root+0)**2
#print("n=",n)
if n ==num:
print(num,"is a perfect square:")
else:
print(num,"is not a perfect square:")
|
7bfa4459f593f06921d1bf516d86b1ada8422c09 | korniloff75/TestPython | /21/__init__.py | 1,211 | 3.8125 | 4 | # koloda = range(6,11) * 10
koloda = [6,7,8,9,10,2,3,4,11] * 10
import random
random.shuffle(koloda)
print('Поиграем в очко?')
userCount = 0
bankCount = 0
while True:
choice = input('Будете брать карту? y/n\n')
if (choice == 'y') or (choice == 'н'):
current = koloda.pop()
bankStep = koloda.pop()
print('Вам п... |
22c78d3a5f29d31b38fe9bde2128ffbb6e58ab10 | ManMMD/Manyu | /homework_day_5/1.py | 454 | 3.6875 | 4 | class Rectangle:
def __init__(self,width=1,height=2):
self.width=width
self.height=height
print('Width:'+str(self.width))
print('Height:'+str(self.height))
def getArea(self):
print('Area:'+str(self.width*self.height))
def getPerimeter(self):
print('Perimeter:'... |
c576dc419a8ce0b15b8e1de768c48f9ca0501274 | Sanjay-Nithish-KS/Text-Editor-using-PyQT | /FileDisplay.py | 1,407 | 3.515625 | 4 | """
FileDisplay Class
The Class FileDisplay is used to display the file content in the
text editor's text area.
The FileDisplay class can display both text files and image files.
Usage:
import FileDisplay
FileDisplay.FileDisplay(file_path,TextEditor object)
"""
import re
from PyQt5.QtCore ... |
cda9c3f672cde4b3e3b92597656f43e7a0540fe4 | mmthatch12/Algo-rith | /lecture/fibonacci.py | 1,225 | 3.8125 | 4 | # fibonacci
# good practice is to do both of these inside another function
# don't really want cache to be global
# def fib(n):
# cache = {} #memorization
# def fibn(n):
# if n == 0:
# return 0
# elif n == 1:
# return 1
# if n not in cache:
# cache[n] ... |
270fe141ad3a3e5ba0edad692e7564eb92f9fa1b | bfridkis/CS325---Miscellaneous | /makingChange_RunningTimes_TimeAsFunctionOfnA.py | 1,491 | 3.546875 | 4 | #################################################################
## Program name: makingChange_RunningTimes_TimeAsAFunctionOfA.py
## Class name: CS325-400
## Author: Ben Fridkis
## Date: 4/19/2018
## Description: Program to time minimumChange for various sizes
## of array parameter "V" and various values for ... |
1ac6379a53680454aef975f5f3354b2a490e1f9c | galigaribaldi/Proyecto_Coneyotl | /DB/cargainfo.py | 417 | 3.8125 | 4 | # -*- coding: utf-8 -*-
import sqlite3
con = sqlite3.connect('baseConeyotl.db')
cursor = con.cursor()
carga = open("cargaCalifgrado.sql",'r') ##abrimos nuestro archivo en modo lectura
for i in carga:
print(i)
cursor.execute(i)
#linea = carga.readline()
#print(linea)
#cursor.execute('''INSERT INTO estudiante ... |
7999b7f181ce2fb6acc9eae46920e21c4a212d1a | spettigrew/cs2-fundamentals-practice | /mod2-Time_Space_Complexity/space_complexity.py | 1,054 | 4.5 | 4 | """
Use Big O notation to classify the space complexity of the function below.
Space complexity - anything additional the function is adding to memory.
"""
def fibonacci(n):
lst = [0, 1]
for i in range(2, n):
lst.append(lst[i-2] + lst[i-1])
return lst[n-1]
# appending is storing a value i... |
a600fc4768e060c89540ac958144d0ce5e42db64 | jaishiva/SudokuSolver | /SudokuSolver.py | 4,253 | 4.03125 | 4 | # contains board and method to display board
class sudoku:
def __init__(self,board):
self.board = board
def __str__(self):
visual = ""
for i in range(0,9):
for j in range(0,9):
visual += str(self.board[i][j].value) + ' '
if ((j+1) == 3) or ((j... |
847674385f9369f3afbd02665d64ebcbe3e40d42 | AmandaRH07/AulaEntra21_AmandaHass | /Prof01/Aula05/if_parte1/exercicio07.py | 327 | 4.125 | 4 | # Exercicio 7
# Faça um programa que peça 3 números inteiros e mostre o menor número.
n1 = int(input("Insira o n1: "))
n2 = int(input("Insira o n2: "))
n3 = int(input("Insira o n3: "))
if n1 < n2 and n1 < n3:
print("Menor: ", n1)
elif n2 < n1 and n2< n3:
print("Menor: ", n2)
else:
print("Menor: ", n3)
... |
462b4ab492182830a0a1a8b9dc37c4eeeaefc06f | tsaitiieva/Python | /Lesson5.py | 1,983 | 3.828125 | 4 | import functools
x=[1, -2, 3, -50, 40, -90]
result = filter(lambda x: x>0, x)
# возвести все положительные элементы последовательности в квадрат
def positive_in_square(el):
if el>0:
return el**2
else:
return el
print(list(map(positive_in_square, x)))
# map принимает 2 параметра: func и *it... |
41d0fed2dec6c4d9ab40c663e80105c7c7ba2278 | ravinaNG/python | /List/sa_re_ga_ma_pa_level.py | 6,075 | 3.6875 | 4 | sargam = ["sa", "re", "ga", "ma", "pa", "dh", "ni", "Sa"]
level = 0
while(level < len(sargam)):
rag = 0
while(rag < len(sargam)):
if (level == 0):
print (sargam[rag])
if (level == 1):
if (rag == 0):
print (sargam[0])
print (sargam[rag + 1])... |
5e1027ac5d2187084410dbe73e5ee0de5e55e675 | kh4r00n/SoulCodeLP | /sclp007.py | 368 | 3.671875 | 4 | '''Crie um programa quea leia o salario e despesas de uma pessoa e inform a porcentagem que a despesa representa de seu salário'''
salario = float(input('Iforme seu salário: '))
despesa = float(input('Informe suas despesas: '))
porc = (despesa * 100) / salario
print(f'Sua despesas de {despesa:.2f} equivale ... |
6f64e46011c1bceff817c683d45abdbcf6a132e3 | Andrescorreaf/Cursopython | /Diccionarios/Ejercicio_diccionarios.py | 5,825 | 3.59375 | 4 | # -*- coding: utf-8 -*-
# ---QUE SON LOS DICCIONARIOS EN PYTHON?.
# Son una estructura de datos que nos permite almacenar valores de diferente tipo
# (enteros, cadenas de textos, decimales) e incluso listas y otros diccionarios
#-----CARACTERISTICAS----------
# La principal característica de los diccionarios
# es q... |
e32225853129fa962df89632f15c14cf151ea4c2 | LamaHamadeh/Customer-Behaviour | /CB.py | 3,988 | 3.8125 | 4 |
"""
Created on Fri Dec 16 13:01:27 2016
Author: Lama Hamadeh
Software: I use Spyder (Python 2.7) to write the following code
The aim: Analyse the data and look for the behavioural differences between investors and non-investors
The Question:
We have attached a small subset of data from our front end events data... |
5c7f5df9fc98115e180380bb93bfbe95d6308824 | nowellclosser/dailycodingproblem | /2018-11-19-product-of-others.py | 1,034 | 4.21875 | 4 | # This problem was asked by Uber.
# Given an array of integers, return a new array such that each element at
# index i of the new array is the product of all the numbers in the original
# array except the one at i.
# For example, if our input was [1, 2, 3, 4, 5], the expected output would be
# [120, 60, 40, 30, 24]. ... |
3dd255b9299542032a379e29f2f514088908f9ce | nfarnan/cs001X_examples | /oo/TH/05_inheritance.py | 887 | 3.921875 | 4 | class Person:
def __init__(self, name, age=20):
self.name = name
self.age = age
def display(self):
print("Name:", self.name)
print("Age:", self.age)
def __str__(self):
return self.name + "!"
def __repr__(self):
rv = "Person("
rv += self.name
rv += ", "
rv += str(self.age)
rv += ")"
return ... |
bb5763bb59030646f04bf29c4036b74bc2ed16a4 | brianmr31/check-Py_basic | /2_while.py | 127 | 3.671875 | 4 | #!/usr/bin/env python
x = input('Masukan nilai Integer : ')
i = 0
while i < x :
print 'nilai ke ',i,' dengan x : ',x
i+=1
|
779cb5f01665b3dac9b85f14cb370160c1dcbe4f | jonasht/cursoIntesivoDePython | /exercisesDosCapitulos/06-dicionarios/6.10-numerosFavoritos.py | 251 | 3.796875 | 4 | pessoas = {
'ana': [1, 8, 4],
'pitona': [78, 5, 888],
'elen': [232, 7, 8, 6, 1, 2, 4]
}
for pessoa, i in pessoas.items():
print(f'\nos numeros favoritos de {pessoa} são:')
for n in pessoas[pessoa]:
print(f'{n}|', end='')
|
d1c270addb0ce48eaa4ca8e98ea7b5c01e922127 | MANA624/MiscRep | /Averager/Averager1.0/averager.pyw | 56,612 | 3.640625 | 4 | # Import TKinter
from tkinter import *
import tkinter.messagebox
from tkinter.filedialog import askopenfilename
import os
import shutil
# These are some variables used to determine if a window has been opened yet
root = Tk()
# I'm gonna write some code that involves checking for a text file, and reading a text file a... |
05985339a44c8762de7b54a5c087e385afac3e56 | GeertRoks/CSD2 | /CSD2a/AntwoordenExamples/03_randomTimeAntw.py | 1,455 | 3.703125 | 4 | import simpleaudio as sa
import time
import random
"""
An example project in which three wav files are played after eachother with a
break in between of a random duration.
Used durations are: 0.125, 0.25 and 0.5 seconds
------ HANDS-ON TIPS ------
- Alter the code:
Add a noteDurations list, with the numbers 0.25, 0... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.