blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
4fcfcd1ce5acdf209357bf23e361d3134a8355f8 | ishandutta2007/ProjectEuler-2 | /euler/calculus.py | 702 | 3.65625 | 4 | def gradient_descent(f, a, b):
'''Return local minimum of 'f' a <= x <= b'''
def f_derivative(x):
return (f(x + e) - f(x)) / e
e = 1e-10
gamma = 1e-6
x_old = 0
x_new = (a + b) / 2
while abs(x_new - x_old) > e:
x_old = x_new
x_new = x_old - f_derivative(x_old) *... |
c2f17e3d76485fab3ee15e40356ddc5932349e59 | zhangchizju2012/LeetCode | /202.py | 763 | 3.578125 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 7 17:24:42 2017
@author: zhangchi
"""
class Solution(object):
# 按照实际运行过程写一下代码就可以了
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
self.dic = {n:1}
temp = n
while True:
... |
6e91420faefa50d39e70c8999bf5dc67491b5d32 | KhizarSultan/Python | /Python Repo/chapter_6/prac.py | 2,078 | 4.78125 | 5 | #Tuples
# is a -data structure to store any kind of data but tuples are immutables
# they can not updated, can not change in original value
# no pop, no insert, no append , no remove
#tuples use when we know our data will not change and it is more faster than list
days = ('monday','tuesday','wednesday')
#method... |
6c5cf8927717ba8bbd14fbfb3624913a547e988f | Dyndyn/python | /lab5.2.py | 374 | 3.875 | 4 | #!/usr/bin/python
#-*- coding: utf-8 -*-
door = list(input("What's height and width of door (write using comma)? "))
door.sort()
arr = list(input("What's a, b, c (write using comma)? "))
arr.sort()
if arr[1] <= door[1] and arr[0] <= door[0]:
print("There is way to fit the box through the door.")
else:
print... |
fb89971ea0ea84e95f796dfe377dd81b71f4d7fa | Pradeep-Deepu/Deepu | /2.7.py | 165 | 3.90625 | 4 | import string
alphabet = set(string.ascii_lowercase)
c=str(input("Enter your string"))
print(alphabet)
print(set(c.lower()))
print(set(c.lower()) >= alphabet)
|
1d8b6f82435406a153db529d0a177a681559c0ca | muhammadhuzaifa023/All-data-files | /compresshions (2).py | 5,590 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""#=========================list comprission==============================
#=========================== Lambda function ===============================
list=[]
for i in range(1,11):
if i%2==0:
list.append(i)
print(list) ... |
8ced74677751f25581dfa29f57abec41f29d3b91 | Bharanij27/bharanirep | /PyplayS28.py | 77 | 3.640625 | 4 | n=list(input())
for i in range(len(n)):
if n[i]!=" ": print(n[i],end="")
|
f96b093a0d8b3d39141eb77429b1cb9a117b8dea | DiGMi/RowingBot | /boat.py | 337 | 3.609375 | 4 | class Boat(object):
def __init__(self,size):
self.rowers = [None]*size
def add_rower(self, pos, name):
self.rowers[pos-1] = name
def get_missing(self):
ret = []
i = 1
for x in self.rowers:
if x == None:
ret.append(i)
i += 1
... |
a3bdf3485a64f93beb09faab0ddd6907caeb3516 | tlin1130/Top-Scores-Problem | /TopScores.py | 1,140 | 3.96875 | 4 |
# Given a list of unsorted scores in range[0,highest_possible_scores],
# fastsort() sorts the list in O(n) time and space using a dictionary
def fastsort(highest_possible_score, unsorted_scores):
dictionary = {}
sorted_scores = [None] * len(unsorted_scores)
index = 0
for each_score in unsorted_scores:
if eac... |
f9ecbf8e59d6270c83338fb3d6c3b2e0c49a85b9 | DenilsonSilvaCode/Python3-CursoemVideo | /PythonExercicios/ex028.py | 743 | 4.1875 | 4 | '''Escreva um programa que faça o computador "pensar" em um número inteiro entre 0 e 5
e peça para o usuário tentar descobrir qual foi o número escolhido pelo computador.
O programa deverá escrever na tela se o usuário venceu ou perdeu.'''
from random import randint
from time import sleep
computador = randint(0,... |
bcd90fcb3f49c07f33acfe36e50a93c2a36ab6ad | Noor-Ansari/Algorithms | /count sort.py | 510 | 3.546875 | 4 | def count(a):
size = len(a)
maxi = max(a)+1
count = [0]*maxi
output = [0]*size
for i in range(0,size):
count[a[i]] +=1
for i in range(1,maxi):
count[i] += count[i-1]
i = size-1
while i >=0:
output[count[a[i]]-1] = a[i]
count[a[i]] -=1
i -=1
... |
8c2c3dcaade4c4ef079ea4080b3568c37c0706a9 | informatorio2020com07/actividades | /meza_cristian/008/Ahorcado_Game/src/juego.py | 3,698 | 3.640625 | 4 | from os import system
from random import choice
from time import sleep
def titulo():
tit="AHORCADO GAME!"
print(tit.center(50, "="))
def carga_palabras():
palabras=("AMOR","ROMA","PERRO","GATO","JUEGO","TELE","SILLON","HABITACION","CAMPERA","MOCHILA","CELULAR","PUERTA","COPA","BAÑERA","JARDIN")
re... |
0aec371f861123a4c19b71aa14df15e9a7f0e99e | Pixeluh/Animal-Shelter-Game | /AngryOldLady.py | 1,734 | 3.734375 | 4 | from FileReader import FileReader
class AngryOldLady(FileReader):
#reads the quiz information from a file and adds it to the object
def __init__(self, fileName):
super().__init__(fileName)
try:
self.quizFile = open(file_name, "r")
except IOError as e:
print("Unab... |
acbe25d47342388668d9ac3cff699410c4b6c431 | nancy20162113/python- | /matplotlib/7.动手试一试_立方.py | 332 | 3.9375 | 4 | #author='zhy'
import matplotlib.pyplot as plt
x_values=[1,2,3,4,5]
y_values=[x**3 for x in x_values]
#plt.scatter(x_values,y_values,c='red',s=100)
plt.scatter(x_values,y_values,c=y_values,cmap=plt.cm.Reds,s=100)
plt.title("Cubic",fontsize=14)
plt.xlabel("Value",fontsize=14)
plt.ylabel("Cubic of Value",fontsize=14)
... |
16b994a7ac9f4635c25d6bddac148e2c930d593b | mzhuang1/lintcode-by-python | /简单/112. 删除排序链表中的重复元素.py | 849 | 3.953125 | 4 | # -*- coding: utf-8 -*-
"""
给定一个排序链表,删除所有重复的元素每个元素只留下一个
样例
给出 1->1->2->null,返回 1->2->null
给出 1->1->2->3->3->null,返回 1->2->3->null
"""
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head... |
2824d16bb0d6d0715e0c355f275958fbc43d83ea | RyanD1996/FYP | /FYP/pong.py | 12,363 | 3.515625 | 4 | import pygame
import random
import numpy as np
import sys
FPS = 60
# Game window dimensions
WINDOW_WIDTH = 500
WINDOW_HEIGHT = 420
GAME_HEIGHT=400
# Size of the paddle
PADDLE_WIDTH = 15
PADDLE_HEIGHT = 60
PADDLE_BUFFER= 15
# Size of the ball
BALL_WIDTH = 20
BALL_HEIGHT = 20
MAX_SCORE = 11
# Spe... |
f90536e32ec1b4ac3ea1c84374022bb517ae57a2 | nipsn/EjerciciosPythonLP | /e6h1.py | 111 | 3.5625 | 4 | def escalera(n):
for x in range(1,n+1):
print("".join([str(y) for y in range(1,x+1)]))
escalera(5) |
fe3021ccb9a65a1d4e90f488c58f5d908640c8ee | jinger02/testcodes | /4-exercise1.py | 316 | 3.6875 | 4 | #import random
#for i in range(10):
# x = random.random()
# print(x)
#n = 5
#while n > 0:
# print(n)
# n=n-1
#print('Blastoff!')
#n = 10
#while True:
# print(n, end=' ')
# n = n-1
#print('Done!')
while True:
line = input('> ')
if line == 'done':
break
print(line)
|
0d0d81f28d1c39a0e13470f352406f46735459a4 | sumitkrm/lang-1 | /python/ds-algo/ds/graph/digraph-cycle-dfs.py | 1,127 | 3.59375 | 4 | from collections import defaultdict
class Graph:
def __init__(self, V):
self.V = V
self.graph = defaultdict(list)
def addEdge(self, u, v):
self.graph[u].append(v)
def isCycleUtilDfs(self, v, visited, recstack):
visited.add(v)
recstack.add(v)
if v not in se... |
fc5a41b2f7a256da788e1a0dbb1e7dade3907b47 | zhouwei713/Flasky | /app/api/date_time.py | 583 | 3.84375 | 4 | '''
Created on 20171208
@author: zhou
'''
'''
generate date list
'''
import datetime
def datelist(start, end):
start_date = datetime.date(*start)
end_date = datetime.date(*end)
result = []
curr_date = start_date
while curr_date != end_date:
result.append("%04d-%02d-%02d" % (curr_date.y... |
8c8d4b66b0b1044d2a090cdfda363589b7d20d28 | naoyasugiyama/chainer-tutorial | /Exercises/Step01.py | 3,141 | 3.96875 | 4 | # python chainer Tutorial
# url : https://tutorials.chainer.org/ja/Exercise_Step_01.html#
import math
# 問2.1 (組み込み関数)
def sample01():
a=[4, 8, 3, 4, 1]
print(len(a))
print(max(a))
print(min(a))
print(sum(a))
a.sort()
print(a)
# 問2.2 (演算)
def sample02():
#5 float
print( 1.2 + 3.8 ... |
697c71bfa3a707d89c489f0ef0917f62be9c6112 | connormoffatt/Baseball | /Analyzing Baseball Data With R/Book - First Edition/Chapter 5 - Value of Plays Using Run Expectancy/ch5_exercise1.py | 5,730 | 3.546875 | 4 | import pandas as pd
# Run Values of Hits
# In Section 5.8, we found the average run vaalue of a home run and a single
# (a)
# Use similar R code as described in Section 5.8 for the 2011 season data to
# find the mean run values for a double and for a triple
# read in 2011 play by play data
data2011 = pd.read_csv('a... |
7042356cedf8cd2ceb4b9c6f2755bfe905e94cc1 | ihthisham/Jetbrains | /Zookeeper/Problems/Sum/main.py | 112 | 3.546875 | 4 | # put your python code here
n1 = int(input())
n2 = int(input())
n3 = int(input())
Sum = n1 + n2 + n3
print(Sum)
|
25b51499c2d956b484168fc201981eb13f69f120 | an-lam/python-class | /functions/lab3.py | 205 | 3.71875 | 4 |
def checkIP(ipaddress)
# Code to check IP address
ipaddress = input("Please enter IP address")
while ipaddress != 'q'
valid = checkIP(ipaddress)
if valid == True
# ask for more info
|
5720948f10007c7a603c810c03746aab8c973f13 | Taher-Ali/exercises_from_py4e | /add_two.py | 148 | 3.890625 | 4 | a = input('Enter first number:')
b = input('Enter second number:')
def addtwo(a,b):
added = int(a)+int(b)
return added
x = addtwo(a,b)
print(x)
|
984d2e575b1a5747769f68309f3544954d64d76a | zllion/ProjectEuler | /p049.py | 2,177 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jul 4 18:56:03 2020
@author: zhixia liu
"""
"""
Project Euler 49: Prime permutations
The arithmetic sequence, 1487, 4817, 8147, in which each of the terms increases by 3330, is unusual in two ways: (i) each of the three terms are prime, and, (ii) each of the 4-digit numbers... |
a9a1e1dacde8dd8fe01f964da7c8b76dfdfbce4c | InnoFang/algo-set | /LeetCode/0703. Kth Largest Element in a Stream/solution.py | 617 | 3.625 | 4 | """
10 / 10 test cases passed.
Status: Accepted
Runtime: 88 ms
"""
class KthLargest:
def __init__(self, k: int, nums: List[int]):
self.k = k
self.min_heap = nums
heapq.heapify(self.min_heap)
while len(self.min_heap) > k:
heapq.heappop(self.min_heap)
def add(self... |
6eba03e891b9577633f9cc2952a76adfaeeb414b | LarsenClose/python-data-structures | /structures/binary_tree.py | 3,291 | 3.828125 | 4 | '''
Description: Binary Search Tree implementation
Author: Larsen Close
Version: Completed through A work, revisited to work on remove()
Outline and initial tests provided in class by Professor Dr. Beaty at
MSU Denver
'''
class BinaryTree():
"""Binary tree class"""
_empty = {}
def __init__(self, value=No... |
46f686ce625ffa844a521ceca2a0c2e42a1bed5f | erjan/coding_exercises | /freedom_trail.py | 2,609 | 3.921875 | 4 | '''
In the video game Fallout 4, the quest "Road to Freedom" requires players to reach a metal dial called the "Freedom Trail Ring" and use the dial to spell a specific keyword to open the door.
Given a string ring that represents the code engraved on the outer ring and another string key that represents the keyword t... |
718dab5ae9d416ccfac65658f795e881f41b19b0 | guymatz/edx | /mit_6.00.1x/laceRecur.py | 617 | 4.125 | 4 | #!/usr/bin/env python
def laceStrings(s1, s2):
"""
s1 and s2 are strings.
Returns a new str with elements of s1 and s2 interlaced,
beginning with s1. If strings are not of same length,
then the extra elements should appear at the end.
"""
# Your Code Here
s1_len = len(s1)
s2_len =... |
df1c91fa3ab0cd8d9e9438dec4b0a781003c7259 | MaaziAgwu/MaaziAgwu4 | /radius.py | 150 | 4.25 | 4 | pi = 3.142
def areaof():
radius = float(input("Enter the radius of a circle "))
areaof = pi * radius **2
print(areaof)
areaof() |
2b574c9ff80762c6a72104f02056ec8a9827a1fe | ilee38/practice-python | /coding_problems/CTCI_trees_graphs/build_order.py | 717 | 3.59375 | 4 | #!/usr/bin/env python3
""" Problem 4.7 on CtCI book
"""
def make_graph(proj_list, dep_list):
G = {}
for i in range(len(proj_list)):
G[proj_list[i]] = []
for j in range(len(dep_list)):
k,v = dep_list[j]
G[k].append(v)
return G
def order(G):
visited = []
for v in G:
if v not in visited:
DFS_visi... |
3d61e7b064ecf7d1a693264bafc2c683427e696d | Carolinegg/test-python | /JogodaVelha.py | 716 | 3.890625 | 4 | def greet():
enter = str(input('\nBem vindo ao jogo da velha! Vamos jogar? \nAbaixo escolha como player x ou o:'))
if enter not in "x" or "o":
print("Ocorreu um erro, escolha corretamente")
return greet()
def show_board():
board = [[0 for i in range (3)] for j in range (3)]
#mostrar q os ze... |
7e24470a1fb8defbcb18f173be94a3c046be726f | ivorobey/python_gl_tasks | /Practice session/Equilibrium.py | 2,947 | 4.0625 | 4 | # Equilibrium index of a list is such index that divides the list in two parts with the same total sum.
# Here the list is A of length N and Equilibrium index is E:
# A[0] + A[1] + ... + A[E−1] == A[E+1] + ... + A[N−2] + A[N−1].
# In other words: the SUM of everything PRIOR to E equals to the SUM of items AFTER.
# S... |
3a663170ca6baaa6c960c7838b448f354185d0bc | PipelineAI/pipeline | /stream/jvm/src/main/java/io/pipeline/tensorflow/consumer/src/data.py | 523 | 3.734375 | 4 | import os
def get_data(data_directory):
"""
Given a string directory path, returns a list of file paths to images
inside that directory.
Data must be in jpeg format.
Args:
data_directory (str): String directory location of input data
Returns:
:obj:`list` of :obj:`str`: list ... |
f1291e0f8e978d13779f2290fbcac3fe64e50e11 | dasbindus/LearnPython | /2_FuncTest/testFuc.py | 353 | 3.90625 | 4 | #! /usr/bin/env python
# -*- coding:utf-8 -*-
def age_test():
age = int(raw_input('your age is:'))
if age >= 18:
print 'You are a adult.\n'
elif age >= 12:
print 'You are a teenager.\n'
else:
print 'You are a kid.'
def fact(n):
if n == 1:
return 1
return n * fact(n - 1)
# ----------------------------... |
850964fe73efc5f55b71e420e5669015206d5449 | senapk/poo_2019_2 | /s01e01_intro/intro.py | 96 | 3.640625 | 4 | b = 3
c = 3.4
d = "banana"
print (b, c, d)
v = [3, 2.3, "1", 4]
for elem in v:
print(elem) |
b77e4b3818b9360e4e1b5c9633e0b74030e830a0 | vinilinux/python-mundo01 | /execicios/desafio010.py | 131 | 3.546875 | 4 | d = float(input('Quanto dinheiro você possui na carteira? R$ '))
us = d / 5.37
print(f'Você pode comprar US$ {us:0.2} dólares')
|
ca1d512b71f45134e7fdacc18e99dced20fac55f | stellel/web-caesar | /caesar.py | 616 | 3.9375 | 4 | import string
lower = string.ascii_lowercase
upper = string.ascii_uppercase
def rotate_character(char, rot):
rotated = ""
rot = int(rot)
if char in lower:
rotated = lower[(alphabet_position(char) + rot) % 26]
else:
rotated = upper[(alphabet_position(char) + rot) % 26]
return rotated
def alphabet_position... |
5ead552bc5c70f9896755440f7ec89d02ec4d058 | zonghui0228/rosalind-solutions | /code/rosalind_sort.py | 5,742 | 3.921875 | 4 | # ^_^ coding:utf-8 ^_^
"""
Sorting by Reversals
url: http://rosalind.info/problems/sort/
Given: Two permutations π and γ, each of length 10.
Return: The reversal distance drev(π,γ), followed by a collection of reversals sorting π into γ. If multiple collections of such reversals exist, you may return any one.
"""
im... |
23df01eed735e397844714af5f3383280ba5e3d3 | stefifm/Guia07 | /prueba_validacion.py | 297 | 3.953125 | 4 | print("Validación de datos")
nombre = input("Ingrese un nombre: ")
edad = -1
while edad < 0 or edad >= 120:
edad = int(input("Ingrese su edad: "))
if edad < 0 or edad >= 120:
print("Error. Se pidió que fuera > 0 y menor a 120")
print("Su nombre:",nombre)
print("Su edad:",edad) |
5d244d71930eab8eb80ff710840f0b8c32e3418a | rohanawale/E_tax_with_MySQL | /Completed Project/fully assembled software/fg.py | 1,374 | 3.53125 | 4 | from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.lang import Builder
Builder.load_string('''
<GridLayout>
canvas.before:
BorderImage:
# BorderImage behaves like the CSS BorderImage
border: 10, 10, 10, 10
source: '../examples/wid... |
caf475340f0ab67e77cce601e5f90b3f788c0510 | jyoon1421/py202002 | /Ch3_1.py | 129 | 3.65625 | 4 |
size = int( input() )
numbers = list ( input() )
result = 0
for i in range(size):
result += int( numbers[i] )
print (result)
|
d7aa917a00b2f582c7b15c8b40de0462ca274a66 | theelk801/pydev-psets | /pset_classes/fromagerie/p6.py | 1,200 | 4.125 | 4 | """
Fromagerie VI - Record Sales
"""
# Add an instance method called "record_sale" to the Cheese class. Hint: You will need to add instance attributes for profits_to_date and sales (i.e. number of items sold) to the __init__() method in your Cheese class definition BEFORE writing the instance method.
# The record_sa... |
8cfcc58e57e776fa2262748b1bcbc066c52527bc | pkulkar/Leetcode | /Python Solutions/1198. Find Smallest Common Element in All Rows.py | 1,461 | 3.984375 | 4 | """
Given a matrix mat where every row is sorted in increasing order, return the smallest common element in all rows.
If there is no common element, return -1.
Example 1:
Input: mat = [[1,2,3,4,5],[2,4,5,8,10],[3,5,7,9,11],[1,3,5,7,9]]
Output: 5
Constraints:
1 <= mat.length, mat[i].length <= 500
1 <= mat[i][j] <... |
5b333f32aaf7e59f41715f538e979ab4833843d4 | rohit4242/BasicsProject | /PythonBasicsproject/faultycalculator.py | 1,006 | 4.1875 | 4 |
# faulty calculator
while True:
operators = ['+', '-', '*', '/']
print(operators)
print('Enter your operators')
operators_input = input()
if operators_input in operators:
print('Enter your number:')
n1 = int(input())
n2 = int(input())
if opera... |
1f224c00bf9fe84b9d94fa793551339ba7fedec0 | meshack-mbuvi/slc-17 | /test.py | 555 | 3.65625 | 4 | import unittest
from loanAmount import get_Loan_amount
class calculator(unittest.TestCase):
#test that function works
def test_it_works(self):
self.assertEquals(get_Loan_amount(100000,12,12),112000)
#test for negative values
def test_months_not_greater_than_12(self):
self.assertTrue(get_Loan_amount(-1,12,14),ms... |
ec8b749eefeab224e3bf6378a360692ecbd77223 | SaishRedkar/HelloBoulder | /textprocessor.py | 443 | 3.734375 | 4 | import re
"""
A simple module with various Text Processing Capabilities
"""
class Processor:
"""
Class for Processing Strings
"""
def __init__(self, text):
self.text = text
def count_alpha(self):
"""
Count number of alphabetic characters in text
:return: Number ... |
f4d3cecb454199128b479cad3450e88e836a6acc | sayalimore8722/Python | /Program5.py | 671 | 4.0625 | 4 | def delivery(ftype,quantity,km):
costtillsix=9
cost=0
if ftype=='V' or 'v':
if km>6:
remain=km-6
partialcost=remain*6
cost=partialcost+costtillsix+(120*quantity)
elif km>3:
remain=km-3
partialcost=remain*3
cost=partialcost+(120*quantity)
elif ftype=='N' or 'n':
if km>6:
remain... |
bae7c9f0291394f9373cde80c508257fd5f8f499 | PapaGateau/Python_practicals | /093-Custom_list_class/custom_list.py | 852 | 3.796875 | 4 | class CustomListe():
"""Custom list class with two characteristics:
- Cannot append numbers
- Cannot contain doubles
"""
def __init__(self, *args):
self.valeurs = [v for v in list(args) if not isinstance(v, int)]
self.remove_duplicates()
def append(self, value):
if isinst... |
d833c7d3342c1f8f52f7952164a0bedd8091a8d3 | daniel-reich/ubiquitous-fiesta | /PLdJr4S9LoKHHjDJC_17.py | 376 | 3.5 | 4 |
def identify(*cube):
num_ls = [len(i) for i in cube]
if max(num_ls) != len(cube):
if sum(num_ls) == len(cube)*max(num_ls):
return "Non-Full"
else:
return "Missing {}".format(len(cube)*max(num_ls)-sum(num_ls))
else:
if sum(num_ls) == pow(len(cube),2):
return "Full"
else:
re... |
931832eb7a9a34f6a8107ee403c52344f9ebbd67 | Uthergogogo/LeetCode | /167_Two Sum II - Input array is sorted/167.py | 586 | 3.640625 | 4 | # One-pass Hash Table
def twoSum(numbers, target):
save = {}
for index, elem in enumerate(numbers):
need = target - elem
if need in save:
return [save[need], index + 1]
save[elem] = index + 1
# two pointers
def twoSum2(numbers, target):
left, right = 0, len(numbers)-1
... |
e2e7b0ab65bc3870553268c3cf88719eaf746ff9 | Manojna52/data-structures-with-python | /cll list.py | 2,439 | 3.671875 | 4 | class node:
def __init__(self,item):
self.item=item
self.next=None
class cll:
def __init__(self):
self.head=None
def append(self,item):
new_node=node(item)
if not self.head:
self.head=new_node
new_node.next=self.head
else:
c... |
d9d79e8910836623c831c337989f53a9ce4e5182 | AndreyPankov89/python-glo | /lesson21/my-tester.py | 5,559 | 3.578125 | 4 | import random
class QuestionStorage:
def __init__(self,questions_list):
self.questions_list = questions_list
def get_all(self):
return self.questions_list
def append(self,question, answer):
if (len(question) == 0):
raise Exception('Нельзя добавлять пустой вопрос')
... |
3371ae7fa4461def9176878228214f8a1b1f0984 | MatthewVaccaro/Coding-Challenges | /1-10-21/delete_nth.py | 251 | 3.703125 | 4 | def delete_nth(order, max_e):
result = []
for i in range(len(order)):
counted = result.count(order[i])
if counted != max_e:
result.append(order[i])
return result
print(delete_nth([20, 37, 20, 21], 1))
|
af9d05ca793623c109c4def9bfd9923bbf48cea9 | JustinSDK/Python35Tutorial | /samples-labs-exercises/samples/CH09/collection_advanced/counter.py | 306 | 3.78125 | 4 | from collections import defaultdict
from operator import itemgetter
def count(text):
counter = defaultdict(int)
for c in text:
counter[c] += 1
return counter.items()
text = 'Your right brain has nothing left.'
for c, n in sorted(count(text), key = itemgetter(0)):
print(c, ':', n) |
f72dd64b1ea02cdade4302d9743f1938d7c7cfb7 | whglamrock/leetcode_series | /leetcode261 Graph Valid Tree.py | 1,161 | 4.09375 | 4 |
# Typical union find solution. remember the find() and union() methods
class Solution(object):
def validTree(self, n, edges):
"""
:type n: int
:type edges: List[List[int]]
:rtype: bool
"""
if n == 0:
return False
if not edges:
return ... |
1bb7e86a0ebda1ee1cf2059d19ae92feb66fdeba | Jeffmanjones/python-for-everybody | /10_exercise_10_2.py | 854 | 4.09375 | 4 | """
Exercise 10.2
10.2 Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages. You can pull the hour out from the 'From ' line by finding the time and then splitting the string a second time using a colon.
From stephen.marquard@uct.ac.za Sat Jan ... |
0c8c7edd23550169cc9ff92e4a3e08c3ee24ff5a | PittBuzz/Python-code-snippets | /countValleys.py | 1,003 | 4.125 | 4 | import unittest
def countValleys(n, s):
"""
Given a set of steps, either up or down.
Count the number of mountains (start at 0, goes up, returns to 0)
and the number of valleys (start at 0, goes down, returns to 0).
Input:
n -- number of steps
s -- string describing the steps ('U... |
87923ddb2b5def05d3d32425339d11a3b53500ab | Sebkd/Algorythm | /task6.py | 720 | 4.15625 | 4 | """
Задание 6.
Пользователь вводит номер буквы в алфавите. Определить, какая это буква.
"""
if __name__ == '__main__':
try:
number_up = int(input ('Введите номер буквы в алфавите a до z '
'(A до Z) '))
if number_up > 26 or number_up < 0:
raise TypeErr... |
1dd3f665fdddd45557edb50ea28c0fa88ffcba47 | JosephLudena/python-base-08-2019 | /hw3_3.py | 777 | 4.03125 | 4 | print("circle")
def areaCircle(radio):
pi=3.1416
area = pi * radio ** 2
return area
radio = float(input())
if radio <= 0:
print('El radio es incorrecto (<=0)')
else:
print(areaCircle(radio))
print("rectangle")
def arearectangle(base, altura):
area= altura*base
return area
altura=floa... |
4fa44f1dba0a8d4866a9d10a3369af96ad9bd8d7 | Tsenghan/Python-study | /Class12/进制转换小程序.py | 426 | 3.75 | 4 | while 1:
number=input('请输入一个整数:')
if number == 'Q':
break
else:
numeric = int(number)
#十六进制
print('十进制-->十六进制:{0:}-->{1:#x}'.format(number,numeric))
#八进制
print('十进制-->八进制:{0:}-->{1:#o}'.format(number, numeric))
#二进制
print('十进制-->二进制:{0:}-->{1}'... |
d9d33900207d3d2336e8cffec45473b72f7d1b7b | 116pythonZS/YiBaiExample | /044.py | 967 | 3.984375 | 4 | #!/usr/bin/python
# -*- coding=utf8 -*-
# Created by carrot on 2017/8/28.
"""
两个 3 行 3 列的矩阵,实现其对应位置的数据相加,并返回一个新矩阵:
"""
import random
def create3Matrix():
matrix=[]
for i in range(0,3):
li= []
for j in range(0,3):
li.append(random.randint(1,1000))
matrix.append(li)
retu... |
351bb4027887e49775c3a1c43fb0e6554ca10d1e | 8563a236e65cede7b14220e65c70ad5718144a3/python3-standard-library-solutions | /Chapter03/0008_functools_lru_cache.py | 1,342 | 4.21875 | 4 | """
Listing 3.8
The lru_cache() decorator wraps a function in a "least recently used"
cache. Arguments to the function are used to build a hash key, which
is then mapped to the result. Subsequent calls with the same arguments
will fetch the value from the cache instead of calling the function. The
decorator also adds ... |
1a8d47a3a1f44665557418479cfd884da4e336be | hackeziah/PythonSample | /Warehouse2.py | 454 | 3.671875 | 4 | from tkinter import *
win = Tk()
win.title("Ware House")
toolbar = Frame(win, bg = "cyan")
insertButt=Button(toolbar,text="Insert Image", command=doNothing)
insertButt.pack(side = LEFT,padx=3,pady=3)
printButt=Button(toolbar,text="Print", command=doNothing)
printButt.pack(side = LEFT,padx=3,pady=3)
toolbar.pack(side=T... |
e8dbd7145eb1e8e8e62b617437da7a1c1cab53d0 | emmanguyen102/CS100 | /Week6/rot13.py | 1,211 | 4.375 | 4 | def encrypt(char):
"""
Encrypts its parameter using ROT13 encryption technology.
:param char: str, a character to be encrypted
:return: str, <char> parameter encrypted using ROT13
"""
regular_chars = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
"l", "m", "n", "o... |
730f62c2b28742f31e0c23c5c2aa0682b3286bc7 | xrustle/GB_Algorithms | /01_Algorithms/HomeWork1/Alg_les1_task5.py | 713 | 4.09375 | 4 | # Пользователь вводит две буквы.
# Определить, на каких местах алфавита они стоят, и сколько между ними находится букв.
char1 = input('Введите любую букву от a до z: ')
char2 = input('Введите вторую любую букву от а до z: ')
pos1 = ord(char1) - ord('a') + 1
pos2 = ord(char2) - ord('a') + 1
length = abs(pos1 - pos2) ... |
15107186e824b8d92739f0d62628f3dd1a923717 | Kuryashka/itstep | /lesson4/fizzerbuzzer.py | 535 | 3.8125 | 4 | al = [x for x in range(101) if x % 3 == 0]
bl = [x for x in range(101) if x % 5 == 0]
while True:
try:
a = int(input("Enter a number in range (1, 100): "))
if a <= 0 or a > 100:
print('You entered a wrong number')
continue
else:
break
except ... |
2409baf5850cd9c66f37f8f3970931b921bae873 | Wizmann/ACM-ICPC | /Codeforces/Educational Codeforces Round 39/B.py | 337 | 3.5 | 4 | def solve(a, b):
while a and b:
if a >= 2 * b:
a %= 2 * b
elif b >= 2 * a:
b %= 2 * a
else:
break
return (a, b)
assert solve(12, 5) == (0, 1)
assert solve(31, 12) == (7, 12)
if __name__ == '__main__':
(a, b) = solve(*map(int, raw_input().split())... |
7dc9b155ecbf75c0f5342fe3293a7afa510bb42f | Ntalemarvin/python | /logical.py | 689 | 4.0625 | 4 | #write a code for that
'''
if applicant has high income AND/OR good credit
Eligible for a loan
'''
has_high_income = False
has_good_credit = True
#and operator
if has_high_income and has_good_credit:
print('Eligible for a loan')
#or aoperator
if has_high_income or has_good_credit:
print('Eligible for a loan... |
5a9937d76f04cfb8e284cededed72236457daebc | OmarSadigli/crossing-game | /scoreboard.py | 645 | 3.71875 | 4 | from turtle import Turtle
FONT = ("Courier", 20, "normal")
class Scoreboard:
def __init__(self):
self.level = 1
def game_over(self):
game_over = Turtle()
game_over.color("black")
game_over.penup()
game_over.hideturtle()
game_over.write("Game Over", align="cent... |
7ceec1b01e4434f4e249bc5bf7e2026729f79a9d | ymsk-sky/atcoder | /abc141/b.py | 67 | 3.515625 | 4 | s=input()
print('No'if 'R' in s[1::2] or 'L' in s[::2] else 'Yes')
|
1105cd1226012eb2d53713771e0da15ae8daaa41 | arnabs542/Leetcode-38 | /Python/ladder92.py | 1,138 | 3.59375 | 4 | class Solution:
"""
@param m: An integer m denotes the size of a backpack
@param A: Given n items with size A[i]
@return: The maximum size
"""
def backPack(self, m, A):
# 背包问题一定用最大总承重当成其中一维
n = len(A)
f = [[False] * (m + 1) for _ in range (n + 1)]
f[0][0]... |
a13328e9385c9d0ef74875d6ba55670fbf07b6a7 | maduoma/Python | /100DaysOfPythonCoding/ControlFlowAndLogicalOperators/IfStatement.py | 4,463 | 4.28125 | 4 | #########################################
# If statement
#########################################
print("Welcome to rollercoaster!")
height = int(input("what is your height? "))
if height >= 120:
print("You can ride coaster")
else:
print("You will have to grow taller to be able to ride.")
print("\n")
########... |
b71813b151e26c86e4c33d9199151c72431ed34d | csundara/CSE107 | /inclass/car.py | 354 | 4.09375 | 4 | car_speed = int(input('Please enter the speed: '))
if car_speed > 55:
print("The police are here")
print("You get a ticket ^_^")
elif car_speed > 45:
print("The police are here")
print("You get a warning. Do not over speed again`")
else:
print("You are safe this timeself.")
print("I'm still wat... |
2dcbe08250fd9e217e11912cf355412b912eb314 | Ranjana151/python_programming_pratice | /elementsquare.py | 299 | 3.953125 | 4 | #list of first and last 5 element and values are square of number between(1,30)
lis=input("Enter the numbers sepeated by space")
lis1=list(map(int,lis.split()))
number=[]
for i in range(1,31):
x=i*i
number.append(x)
print("Numbers are",number[0:5])
print("Numbers are",number[-5:-1]) |
fe8fd816527fc24638b9e3cd5c99620dd9e797b0 | gouwangrigou/Python-Machine-Learning-and-Practice-Kaggle- | /Python Machine Learning and Practice(Kaggle)/chapter_2/code_29.py | 2,902 | 4.125 | 4 | # coding=utf-8
# 决策树分类-预测泰坦尼克号乘客生还情况
# 导入pandas用于数据分析。
import pandas as pd
# 利用pandas的read_csv模块直接从互联网收集泰坦尼克号乘客数据。
titanic = pd.read_csv('http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic.txt')
# 观察一下前几行数据,可以发现,数据种类各异,数值型、类别型,甚至还有缺失数据。
print(titanic.head())
# 使用pandas,数据都转入pandas独有的datafra... |
bd471ae1e9968d8055a3c6486f2ba1d2e51ad717 | panda002/Python-Beginner | /MesoJarvis/Pallindrome.py | 404 | 4.09375 | 4 | num = str(input('enter a number : '))
print('the number entered is - ', num)
# print (len(num))
j = len(num)
# a= (list(range(j-1,-1,-1)))
# print (a)
for i in (list(range(j - 1, -1, -1))):
num2 = num[i]
print(num2)
for a in (list(range(0, j))):
num3 = num[a]
print("reverse is : ", num[a])
if num3 == nu... |
e0685e8a8e9a5a3ab957ddad365d0e9c43cfa772 | pmukwende/Final-Project | /Project.py | 1,619 | 3.625 | 4 | import csv
import matplotlib.pyplot as plt
import pandas as pd
def processdatafiles():
filename = 'bostoncrime2021_7000_sample.csv'
with open(filename) as f:
reader = csv.reader(f)
incidentlist=list(reader)
f.close()
filename = 'BostonPoliceDistricts.csv'
with open(filename) as f:
... |
87a497f19c5ae0a7e727ed568ba6e8cf0a79f6dc | aswinrprasad/Python-Code | /CODED.py/TypeCasting.py | 222 | 4.25 | 4 | #Program to read an integer and a character representing an integer and to print their sum.
x=int(input("Enter an integer number :"))
ys=str(input("Enter a number as string :"))
print "The sum of the two is :",x+int(ys)
|
a9373a59f6efc0ff055274757582665483b9c618 | patelpriyank/LearnPythonHardWay | /LearnPythonHardWay/Exercise9_PrintingPrintingPrinting.py | 422 | 3.75 | 4 | days = "mon tues wed thrs fri sat sun"
months = "jan\nfeb\nmar\napr\nmay\njun\njuly\naug\nsep\noct\nnov\ndec"
print("here are the days:", days)
print("here are the months:", months)
print("""
there is something going on here.
with three double quotes,
we will be able to type as much as we like
even 4 lines if we wa... |
16f52c355a9721d5ea2cd82e984e8dfa8c75c635 | Saquib472/Innomatics-Tasks | /Task 3(Python Maths)/02_FindAngle_MBC.py | 374 | 4.03125 | 4 | # Task_3 Q_2:
# You are given the lengths AB and BC.
# Your task is to find THE ANGLE OF MBC in degrees.
# Input Format
# The first line contains the length of side AB.
# The second line contains the length of side BC.
import math
a = int(input())
b = int(input())
M = math.sqrt(a**2+b**2)
theta = math.acos(b/M )
prin... |
0a197b166e48b432ae951a8d21eacf65c0acbf1a | shchukinde/basic_python | /lesson_3/task3.3.py | 633 | 4.21875 | 4 | # Реализовать функцию my_func(), которая принимает три позиционных аргумента, и
# возвращает сумму наибольших двух аргументов.
def my_func(x, y, z):
my_list = [x, y, z]
my_list.sort()
return my_list[1]+my_list[2]
number_x = int(input('Введите первое число:'))
number_y = int(input('Введите второе число:'))... |
d954c4a82d03bb04604e78b48e43504363c6d5d6 | XyK0907/for_work | /LeetCode/Array/283_move_zeros.py | 1,563 | 3.8125 | 4 | class Solution(object):
def moveZeroes(self, nums):
"""
time O(n)
space O(1)
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
slow = 0
while slow < len(nums) and nums[slow] != 0:
slow += 1
... |
52591c237c33188ea405274a6e67d1a3da43e973 | timlyo/Year2_programming | /W1_isSubString.py | 600 | 3.625 | 4 | """Pseudocode
for i in string1
if (string1[i] == string2[0])
for j string2
if (string1[iPos + jPos] != string2[j])
break
else
return True
return False
"""
class Week1:
@staticmethod
def isSubStringEasyVersion(string1, string2):
"""sane version"""
return string2 in string1
@staticmethod
... |
6bf48f8627cf0649babd66bd33f33821e666971c | GarrettMatthews/Personal_Projects | /DND/items.py | 3,377 | 3.5625 | 4 | """
Returns a randomly generated item that can be magical and/or cursed
Garrett Matthews
"""
import random as rdm
class Item:
def __init__(self, magical = None, cursed = None):
self.adjective = ''
self.item_type = ''
self.value = ''
self.magical = magical
self.cursed =... |
7906f9cc6a27bb9605b3a1e2b2c516024709379a | YingjingLu/Cai-Ji | /451/2dp_graph.py | 2,963 | 4 | 4 | """
Represent graph as 2d adjacency matrix
for n vertex
n x n adjacency matrix with weight, edge has non-negative weights
"""
INT_MAX = 2**31 - 1
"""
Dijkstra’s Algorithm
Given a graph and a source vertex in the graph,
find shortest paths from source to all vertices in the given graph.
Starting from one of the v... |
6695ed57e186401c1b8b182e37471d6115fb43b1 | a7r3/CollegeStuffs | /OSTL/monthByNumber.py | 1,026 | 4.34375 | 4 | # Creating a dictionary of Months
# Key - Month name
# Value - The Month sequence number
# String containing three-lettered months, splitted by space
monthStr = "jan feb mar apr may jun jul aug sep oct nov dec"
# Breaking down the string into multiple strings (list), with the
# specified breaking point (delimiter the... |
7a2f16af5e4ae88b5c4eebf19118de499197554e | PriscylaSantos/estudosPython | /TutorialPoint/03 - Decision Making/2 - IF..ELIF..ELSEStatements.py | 898 | 4.21875 | 4 | #!/usr/bin/python3
#An if statement can be followed by an optional else statement, which executes when the boolean expression is FALSE.
# if expression:
# statement(s)
# else:
# statement(s)
#
amount = int(input("Enter amount: ")) #Ex: 466
if amount < 1000:
discount = amount * 0.05
print("Discount", d... |
baa2c2ee7ef5e10e8c83034de6fb6faea29fd778 | rmoore2738/CS313e | /strings.py | 2,439 | 4.28125 | 4 | # File: strings.py
# Description: Implements three functions that use
# and manipulate strings.
# Assignment Number: 8
#
# Name: Rebecca Moore
# EID: rrm2738
# Email: rebeccamoore32@utexas.edu
# Grader: Skyler
#
# On my honor, Rebecca Moore, this programming assignment is my own work
# and I have not provided this code... |
83e809c8500adce0f37fa93af8e7cb697c967641 | arcaputo3/algorithms | /simulations/quant_sims.py | 1,918 | 3.6875 | 4 | """ Simulating various expectations. """
import numpy as np
def throw(iters=10000):
""" Calculating expected number of die throws such that each side has shown up at least once. """
count = 0
for _ in range(iters):
seen = set()
while len(seen) < 6:
count += 1
seen.a... |
da2a73208a291eaf5daf5573468aaaf9deecce8d | jpmolden/python3-deep-dive-udemy | /section9_ModulesPackagesNamespaces/_129_modules.py | 3,142 | 4.09375 | 4 | # What is a module
def func():
a = 10
return a
print(func)
# Fun is found in the namespace
print(globals())
print(locals())
# In the global scope is the local and global scope the same
print(f'\tIs the local == gloabl : {locals() == globals()}')
print(globals()['func'])
f = globals()['func']
print(f is func)
... |
0913258895e7bf47438078579e9adaaa193ed854 | Rohit-dev-coder/MyPythonCodes | /upperorlowerletter1.py | 203 | 4.21875 | 4 | ch = ord(input("Enter A character: "))
if ch>=65 and ch<=90 :
print("uppercase")
elif ch>=97 and ch<=122 :
print("Lowercase")
elif ch>=48 and ch<=57 :
print("Number")
else:
print("Special character") |
00b871ac236b8cf37bc3f877a79ecbfed0135e29 | jillnguyen/Python-Stack | /Fundamentals/compare-list.py | 645 | 3.953125 | 4 | def compare_list(list1, list2):
if len(list1) != len(list2):
print(list1, list2, "Two list are not the same")
else:
my_comparison = True
idx = len(list1)
for i in range (0, idx):
if not list1[i] == list2[i]:
my_comparison = False
if my_comparis... |
8f1d004e08192779dc1eb996cd12f251bbbe0887 | daanyaalkapadia/basic-college-management-with-python | /removeCollege.py | 627 | 3.96875 | 4 | import csv
def remove():
lines = list()
flag = False
rmCollegeId= input("Please enter a College Id to be deleted:")
with open('colleges.csv', 'r') as readFile:
reader = csv.reader(readFile)
for row in reader:
lines.append(row)
for field in row:
if field == rmCollegeId:
lines.remove(row... |
2eccca1fbad0a290da226313231b8d0ef671604e | PrashantRaghav8920/GUVI_PROGRAM | /SET9/iso.py | 212 | 3.53125 | 4 | l=[]
s=input()
l.append(s)
while s!="":
s=input()
if s!="":
l.append(s)
for i in l:
s=set(i)
if len(s)<len(i):
print("No")
if len(s)==len(i):
print("Yes")
|
99588420df65f613d3e7564792302b6734026766 | EngCheeChing/Portfolio | /Data Analyst Nanodegree/Data Wrangling with Python - Open Street Maps/audit_street_types.py | 2,452 | 3.765625 | 4 | """
Your task in this exercise has two steps:
- audit the OSMFILE and change the variable 'mapping' to reflect the changes needed to fix
the unexpected street types to the appropriate ones in the expected list.
You have to add mappings only for the actual problems you find in this OSMFILE,
not a generaliz... |
38e063dafb381eb1f3428d09ee5fc84186ebe3ea | SOURADEEP-DONNY/WORKING-WITH-PYTHON | /Dictionary Comprehensions/1.py | 157 | 3.96875 | 4 | dict1={}
for i in range(11):
dict1[i]=i**2
print(dict1)
# the code using dictionary comprehension
dict2={n:n*n for n in range(11)}
print(dict2)
|
bbdbd3072a1c054b6333421a0b85df2127693e5a | sam-evans/Python-Projects | /Chaos game version 1.py | 3,315 | 3.515625 | 4 | ##################################################################################################################################################
#Name:Sam Evans
#Date:3/28/20
#Description:Chaos Game (Sierpinski Triangle)
#########################################################################################... |
65f9c08ac828a130db42ed202b63884d1755de1f | swang2000/DP | /Knapsack.py | 2,488 | 3.984375 | 4 | '''
Dynamic Programming | Set 10 ( 0-1 Knapsack Problem)
3.3
Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack.
In other words, given two integer arrays val[0..n-1] and wt[0..n-1] which represent values and weights associated with n
items res... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.