blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
00b37011b528823dafdd2f6a54b9d4390efb1785 | sakshisangwan/Python-101 | /Problem Set /Triangle.py | 359 | 4.34375 | 4 | # This program will check if the given sides are of an isosceles, scalene or equilateral triangle
a = input ("Enter value of side 1 ")
b = input ("Enter value of side 2 ")
c = input ("Enter value of side 3 ")
if a == b and b == c:
print("Equilateral Triangle")
elif a == b or b == c or c == a:
print("Isosceles Tria... |
ff0938ed36763eedefe2776c27809dada7922771 | PhilipWoulfe/PythonProjectWinter2017 | /StockYear.py | 2,022 | 3.8125 | 4 | from AbstractStockPeriod import AbstractStockPeriod
class StockYear(AbstractStockPeriod):
def __init__(self, stock):
"""
Overrides the default implementation
Create a new Stock year object with the year of the stock object passed to the constructor
:param stock: Used to determine ... |
d3ec417464c66d60b24ede6c16c0ac392eaa8df5 | ceb10n/design-patterns-with-python | /patterns/adapter/adapter_1.py | 639 | 3.8125 | 4 | import abc
class Target(abc.ABC):
@abc.abstractmethod
def do_something(self):
pass
class Adapter(Target):
def __init__(self, adaptee):
self.adaptee = adaptee
def do_something(self):
self.adaptee.do_something_else()
class Adaptee:
def do_something_else(self):
... |
d168fd211b399cf616e851ab14ec8c73503c47bd | paulofreitasnobrega/coursera-introducao-a-ciencia-da-computacao-com-python-parte-2 | /week6/fatorial_recursivo.py | 389 | 4.03125 | 4 | """Week 6 - Exercícios adicionais (opcionais)."""
"""
Implemente a função fatorial(x), que recebe como parâmetro um número inteiro
e devolve um número inteiro correspondente ao fatorial de x.
Sua solução deve ser implementada utilizando recursão.
"""
def fatorial(n: int) -> int:
"""Fatorial utilizando chamadas ... |
52a91806d687f877e95aa9e7598699fa9e976a33 | AltumSpatium/Labs | /7 semester/MoIP/Lab4/lab4.py | 2,062 | 3.546875 | 4 | import os
import json
import rsa
def main():
while True:
option = get_chosen_option()
if option == '0':
return
if option in ('1', '2', '3'):
break
else:
print('Wrong input, try again...')
print()
if option == '3':
generate_keys()... |
b91a22b4cf22b1f1a95f915ff5a95c46632e6bfa | techbees-consulting/datascience-dec18 | /functions/recursive functions.py | 312 | 3.875 | 4 | #fact 4*3*2*1 1-1
#fibonocci
def fact(n):
if n==0:
result =1
else:
result = n*fact(n-1)
return result
#5*fact(4)->4*fact(3)->1
# print(fact(5))
def fib(n):
if n==0:
return 0
elif n==1:
return 1
else:
return fib(n-1)+fib(n-2)
print(fib(10))
|
c691d6883a1c307489f009db159747925b41d6bf | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/countCompleteTreeNodes.py | 1,750 | 4.09375 | 4 | """
Given a complete binary tree, count the number of nodes.
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
"""
If you draw the tree out with at least 4 levels (the root is considered a level... |
4828856a181fd55c18f0a873452bfc031983acf5 | kmanwar89/ISAT252 | /Labs/Lab 6 and Lecture Exercises/circle_1.py | 677 | 4.3125 | 4 | # Compute area of a circle
# Programmer: Kadar Anwar
# Language: Python 3.4
# circle.py
# 3/4/2015 - ISAT 252
#create and initialize global variables and constants
radius = 0.0
area = 0.0
PI = 3.14
#input - get the radius of the circle
radius = float(input("Enter the radius of the circle: "))
#input v... |
2742d497c990457e9b5c356766a143cec7472d74 | Kristijan-Kitevski/Python_Semos | /final_project_semos/Fake_clients_accounts_for_testing.py | 2,380 | 4.03125 | 4 |
import sqlite3
from sqlite3 import Error
# NOTE!!
# run main program to create the db
# run this script after you run main program
try:
connection = sqlite3.connect('Banc_Client_DB.db')
except Error as e:
print(e)
cursor = connection.cursor()
# cursor.execute("drop table if exists client")
# cursor.execut... |
eb444d3aa62dc3274208d04e4c6023dfb5512225 | juan81mg/python2020 | /ejercicios_Excepciones/01.py | 1,908 | 4.09375 | 4 | """
1. Indique si ingresando los siguientes par de números el código se ejecuta siempre, si no es así
cómo modificaría el código para que se ejecute en todos los casos.
100, 2
10, 0
15, 3
"""
# rta: se produce una excepcion cuando se divide por 0 (10, 0), ZeroDivisionError, y deja ejecutar el try,
# poniendo el bloque ... |
5d4ce54b6bc65c67a5f46edfe283b3cfd833a6ee | RepoCorp/boston_housing | /boston_housing.py | 7,620 | 4.09375 | 4 | # Importing a few necessary libraries
import numpy as np
import matplotlib.pyplot as pl
from sklearn import datasets
from sklearn.tree import DecisionTreeRegressor
# Create our client's feature set for which we will be predicting a selling price
CLIENT_FEATURES = [[11.95, 0.00, 18.100, 0, 0.6590, 5.6090, 90.00, 1.385... |
7cc0c4188ca37edbcd1a6102f082cdc8e0854535 | mjimenez421/QuantLabEx | /build/lib/src/outputBuilder.py | 4,893 | 4 | 4 | import csv
import os
# Throughout class, "row" is used to denote data from the output file
# e.g, "new_row" is data to be written to the output file
class OutputBuilder:
#class attributes to represent fields of the csv file
__iTime = 0
__iSymbol = 1
__iQuant = 2
__iPrice = 3
__oSymbo... |
0d0c27f5fada406cdd6942de8fbc35c1e746220b | shuaiwang88/Final-Year-Project | /Rough scripts/thompson d zero approach.py | 15,643 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Feb 24 04:39:06 2019
@author: Samuel
In this script, I try to use the data generating mechanism as a start point,
instead of using it to generate prior data.
Applied to children's dataset.
Set d=0 approach.
Each iteration, set d = 0 for products with no more inventory.
""... |
bc716875ccca03ed1a27ca46b901e398de79d734 | adityawr/mic-machine-learning | /py-code/finding_for_charity.py | 6,024 | 3.5625 | 4 |
from IPython import get_ipython
import numpy as np
import pandas as pd
from time import time
from IPython.display import display
import visuals as vs
get_ipython().run_line_magic('matplotlib', 'inline')
data = pd.read_csv("census.csv")
display(data.head(n=1))
n_records = len(data)
n_greater_50k = len(data[da... |
38f166e885d1d2140da5a891f2a55641363c0866 | spencerli82/lc1 | /maze.py | 852 | 4 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def walk(maze, x, y):
passed = False
if (x >= 0 and x < len(maze) and y >= 0 and y < len(maze[0]) and maze[x][y] == 1):
maze[x][y] = 2
if x == len(maze) - 1 and y == len(maze[0]) - 1:
passed = True
else:
passed = walk(... |
d0ca788de3e0c49c8bf22b3773f51837691e1ff3 | pramodghadge/Python-Data-Structure | /algorithms/CareerCup/01/bracket_balancing.py | 656 | 3.96875 | 4 | def bracket_balancing(myStr):
aList = []
for v in myStr:
if v in ['(', '{', '[']:
aList.append(v)
elif v in [')', '}', ']']:
if len(aList) > 0:
last = aList.pop()
if v == ')' and last != '(':
return False
... |
43954e74586ec2c3fb57cd0843d2c6ec751fcf44 | Yu-python/python3-algorithms | /5. LeetCode/112.path-sum/4.py | 1,632 | 3.78125 | 4 | """
方法四:回溯
找出从根节点到叶子节点的「所有完整路径」,只要有任意一条路径的和等于 sum,就表示找到了
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def hasPathSum(self, root: TreeNode, targetS... |
8ee292e3275f87a4a3a189c9b515e6094244508f | aiifabbf/leetcode-memo | /1233-5231.py | 1,680 | 3.6875 | 4 | """
删掉所有的子目录
如果一个目录是另一个目录的子目录,就删掉它。
暴力做法就可以了。先把所有的目录从
::
"/a/b/c/d"
的形式转换成
::
("a", "b", "c", "d")
这种形式。然后再按字典序从小到大排序。这样就可以形成树状结构,子目录永远会出现在这个子目录所属的主目录的后面。
::
a
a, b
c, d
c, d
c, d, e
c, f
对于每个目录,看这个目录的前缀是否已经见过,如果见过了,说明这个目录是一个子目录;如果没有见过,说明这个目录是一个主目录。
"""
from typing import *
... |
07789b88654f8234c1d71392a736ee5cb050f0a5 | Dis-count/Python_practice | /Practice/code_class/Crossin-practices/python_sicp/cs61-2-9.py | 1,450 | 3.71875 | 4 |
class Link:
empty = ()
def __init__(self,first,rest=empty):
assert rest is Link.empty or isinstance(rest,Link)
self.first = first
self.rest = rest
def __getitem__(self,i):
if i == 0:
return self.first
else:
return self.rest[i-1]
def __le... |
3ff697ae8e662a93e29ae52adb108234aaece0ad | ksprashu/project-show_me_data_structures | /problem_3.py | 5,190 | 3.90625 | 4 | """Generate the Huffman encoding and decoding for the provided data.
"""
import sys
from typing import Dict
from problem_3_lib import HuffmannTree, MinTreeNodeHeap
def _get_char_frequency(data) -> Dict:
"""Returns a dictionary with the frequency of each character in the input.
"""
freq_map = {}
for ... |
a67616f939c3ced94b199c0ebab24cbef7b8f9ec | satheeshkumars/my_chapter_8_solution_gaddis_book_python | /name_display.py | 313 | 4.09375 | 4 | def main():
first_name = input('Please enter your first name: ')
last_name = input('Please enter your last name: ')
print(first_name[0].upper() + '.' + last_name[0].upper() + '.')
print(first_name.capitalize(), last_name.upper())
print(first_name[0].lower() + last_name.lower())
main() |
d649b9efee46961d156e9cc9bd3f59423a0d24c8 | Kayboku5000/Python_Practice_Scripts | /in_operator.py | 304 | 3.59375 | 4 | import time
x = 0
y = 0
a = 0
z = 0
b = 0
while x < 10 :
print(x, y, z, a, b)
#print(y)
#print(z)
#print(a)
x = (x + 1)
#y = (y + 1)
z *= x
#b += z
#a += b + z
time.sleep(1)
print(z)
#x = (a * b) + c
#y = (x + 1) * x
#x = (b + 1) **2
#print(x)
#print(y)
|
3e9b25e5096f84f82eaf3744eaf64c6714c16a66 | ravikartar/Hacktoberfest2021 | /interest_calc.py | 2,554 | 3.921875 | 4 | import math
import sys
#Financial Maths
i = 0.00
def compound_interest():
print ' '
P = input(' The starting value: ')
i = input(' Interest rate: ')
r = input(' Compounded: 1: Monthly\n 2: Yearly\n => ')
if r in (1,2):
n = input(' Number of years:... |
f7ba8a63c6a7e32f3ebb94bc353a57c6563848cc | priva80/Python-Essential-Pedro-RIvadeneira | /Directorio del curso/uso del try y el except en un rango de numeros.py | 566 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 1 20:11:29 2021
@author: Envy-W10
"""
def readint(prompt, min, max):
while (True):
try:
print("Ingrese un valor entre", min, "y", max)
x=int (input(prompt))
assert x>= min and x<=max
return x
... |
b466cfb2680860dd75b5a641a5b651f0ce7f8ee1 | pgayane/jobprep | /recursion/step_count.py | 226 | 3.765625 | 4 |
def count(n):
if n < 3:
return n
elif n == 3:
return 4
else:
return count(n-1) + count(n-2) + count(n-3)
if __name__ == '__main__':
for i in range(0, 16):
print i, count(i)
|
9c1cf8c65ab01e19a9e7d89fc7b9644fdee6cc45 | valleyceo/code_journal | /1. Problems/i. Recursion & Backtrack/b. Backtrack - Path - Number of Dice Rolls With Target Sum.py | 1,502 | 3.6875 | 4 | # LC 1155. Number of Dice Rolls With Target Sum
'''
You have n dice and each die has k faces numbered from 1 to k.
Given three integers n, k, and target, return the number of possible ways (out of the kn total ways) to roll the dice so the sum of the face-up numbers equals target. Since the answer may be too large, r... |
3348ac50548bb09abbbb6b72ff719bd520ec1d3b | lsjhome/algorithm-for-everybody-python | /ch02_recursion/04.factorial/e04-1-sum-jin.py | 312 | 3.640625 | 4 | # 연속한 숫자의 합을 구하는 알고리즘
# 입력: n
# 출력: 1부터 n까지 연속한 숫자를 더한 값
def sum_n(n):
if n == 0:
return 0
# else 부분 없이 바로
return sum_n(n-1) + n
if __name__ == '__main__':
print (sum_n(10))
print (sum_n(100))
|
4c68326d22876a659d6afffc3e934f958f36ba6d | MAVENSDC/PyTplot | /pytplot/AncillaryPlots/position_mars_2d.py | 5,398 | 4 | 4 | import pyqtgraph as pg
import pytplot
def position_mars_2d(temp=None):
'''
This is a simple plot that shows spacecraft position relative to Mars in MSO coordinates
'''
# Set Mars Diameter constant
MARS_DIAMETER = 3389.5 * 2
# Set up the 2D interactive plot
window = pytplot.tplot_utilitie... |
6c2229f917896c4cfe540cc50c816b2861054696 | abhinav0606/Machine-Learning-algorithms | /Logistic Regression/logistic regression.py | 1,696 | 3.8125 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# data preprocessing
dataset=pd.read_csv("/home/abhinav/Documents/Machine Learning/Machine Learning A-Z (Codes and Datasets)/Part 3 - Classification/Section 15 - K-Nearest Neighbors (K-NN)/Python/Social_Network_Ads.csv")
X=dataset.iloc[:,:2].values
... |
7f7fe3881315c3cdba36dafd83ade32ad00b52ff | xamlegrub/hangman | /PythonPractice/Movies.py | 428 | 3.734375 | 4 | class Movie(object):
def __init__(self, source, name, year, rating, description):
self.source = source
self.name = name
self.year = year
self.rating = rating
self.description = description
def addMovie(self, name):
test = name
def deleteMovie(self, name):
... |
df8c01a8e799f083ce05029554728c66d50f7272 | Lib3Rt9/pp2021 | /2.student.mark.oop.py | 5,400 | 3.875 | 4 | student = []
course = []
mark = []
print("--------------------------------")
print()
class Std_Info():
def __init__(self, s_ID, s_Name, s_DoB):
self.s_ID = s_ID
self.s_Name = s_Name
self.s_DoB = s_DoB
def set_s_ID(self, s_ID):
self.s_ID = s_ID
def get_... |
d4ae96aa705be28e1a5f59cafa68e15d4dd0a0d5 | artuguen28/Python_bible_intermediates | /Recursion/rec1.py | 405 | 3.890625 | 4 | # Recursion
#This concept refers to a function calling itself.
def function():
function()
#function()
# When we run a function we allocate stack memory space and if there is no space left, this is called Stack Overflow.
# Factorial calculation
def factorial(n):
if n < 1:
return 1
el... |
e13d076a0f785a97b48430d18167d74f327bc879 | claudinemahoro/Password-locker | /user.py | 373 | 3.84375 | 4 | class User:
'''
Class to create user account for this app and save the details
'''
def __init__(self,first_name,last_name,password):
self.first_name = first_name
self.last_name = last_name
self.password = password
users_list = []
def save_user(self):
'''
Method to save the created user's account i... |
da28f43785c4f5f51ebe3634343f9833005090b5 | xiaotuzixuedaima/PythonProgramDucat | /PythonPrograms/python_program/Oops_init_inhertence_sample.py | 432 | 3.953125 | 4 | # OOps using init _ sample using class ...????
class ABCD:
def add(self):
self.a = int(input("Enter First Number: "))
self.b = int(input("Enter Second Number: "))
def display(self):
print('sum : ',self.a+self.b)
obj=ABCD()
obj1=ABCD()
obj.add()
obj1.add()
obj.display()
obj1.display()
'''
output ===
Ente... |
8df2fb9c4b0956df50b054185df0f32fbb83626c | brunolomba/exercicios_logica | /Estrutura condicional/temperatura.py | 328 | 3.9375 | 4 | unidade = input('Digite em qual escala vc quer transformar: "c" para Celsius ou "F" para Farenheit')
if unidade == 'f':
f = int(input('Digite a temperatura'))
c = 5 / 9 * (f - 32)
print(f' {c} Graus Celsius')
else:
c = int(input('Digite a temperatura'))
f = 9 * c / 5 + 32
print(f' {f} Graus Far... |
cef3696b3017c9fa704c648ba94796c3366209f7 | vivhou/Python-coursework-files | /exercises/readcsv.py | 184 | 3.875 | 4 | import csv
with open('example.csv', 'rb') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
print(row)
print("Name is %s" % (row[0]))
for item in row:
print(item) |
0304fbe78c533d9af4faf18a8c56c0bde9219929 | tmnik/Python_study | /ex_med.py | 775 | 4.125 | 4 | #генерируем случайный список и находим медиану
import random #для случайных чисел
import statistics #для нахождения медианы
numbers = []
numbers_size = random.randint(10,15)
for _ in range(numbers_size):
numbers.append(random.randint(10,20))
print("Список:"numbers)
numbers.sort()
print("Отсор... |
1d6b87c68f1fe3d327a5d67876bb8f3fd2ef1f3a | SuperAllenYao/pythonCode | /class_info/example.py | 1,752 | 3.75 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Student(object):
"""学生类"""
def __init__(self, study_num, student_name, course=None):
"""构造方法"""
self.study_num = study_num
self.student_name = student_name
self.__course = course
@property
def course_detail(self):
... |
78b6c68b8d640a531c3c7fe088aef58aa73efc56 | HitraNOfficial/PythonYoutube | /writing the simplest program in complicate way/job_secured_main.py | 2,075 | 4.09375 | 4 | """
Use built-in abc to implement Abstract classes and methods
used for the Command Pattern
"""
from abc import ABC
""" Class Dedicated to Command"""
class Command(ABC):
"""constructor method"""
def __init__(self, receiver):
self.receiver = receiver
"""process method"""
def proces... |
eccf965d071a71a15462e519e173a5d37b752296 | burkharz9279/cti110 | /M2HW1_DistanceTraveled_Burkhardt.py | 447 | 4.125 | 4 | #CTI-110
#M2HW1 - Distance Traveled
#Zachary Burkhardt
#9/10/17
print("Distance = Speed * Time")
print("A car travels at 70 mph for 6, 10, and 15 hours")
speed = 70
time = 6
distance = speed * time
print("6 hour distance is", distance)
speed = 70
time = 10
distance_after6 = speed * time
print("10 hour ... |
98b166241fe443eef5f03b8a05424d79665ed3e5 | Milan9870/5WWIPython | /07b-whilelus/harshadgetallen.py | 244 | 3.625 | 4 | harshad = str(input('een getal: '))
deeltal = int(harshad)
som = 0
for cijfer in harshad:
som += int(cijfer)
if deeltal % som == 0:
print(str(deeltal) + ' is een Harshadgetal')
else:
print(str(deeltal) + ' is geen Harshadgetal')
|
0e7621a01879b5d66cb0204ea32b9b46d0b8d856 | philipsdoctor/tech_review_questions | /problem2.py | 651 | 3.921875 | 4 | # Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
#
#1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
#
# By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
... |
bd3c06e532504c644e86d6af3db80bea5c3813dc | broilo/python | /jokenpo_rev.py | 1,078 | 3.78125 | 4 | from random import randint
from time import sleep
itens = ('pedra', 'papel', 'tesoura')
comp = randint(0, 2)
print(itens[comp])
print('''Tuas opções:
[0] pedra
[1] papel
[2] tesoura ''')
jogador = int(input('Qual é a tua jogada? '))
print('JO')
sleep(1)
print('KEN')
sleep(1)
print('PO!!!')
print('-=-' * 8)
print('Compu... |
3966befdeea8390b779c0cd779fcfbd78bfca357 | nodamu/apache-beam-studies | /structure_of_beam_apps/test.py | 2,731 | 3.5 | 4 | from tkinter import *
import pygame
import os
class MusicPlayer():
def __init__ (self, Player):
self.Player = Player
self.Player.title("themaytrix Player")
pygame.init()
pygame.mixer.init()
self.Player.geometry("500x150+10+10")
trackframe = LabelFrame(self.P... |
75ef9a59bc5a0736c4ff815fa472892a20e310ee | ghowland/gomh | /movement.py | 7,439 | 3.53125 | 4 | """
Movement
"""
import pygame
import constants
def TestCollisionByPixelStep(start_pos, end_pos, step, scene, scene_obstacle_color=(255,255,255), log=False):
"""Test for a collision against the scene, starting at start_pos, ending at end_pos, using step to increment.
NOTE: This function assumes that the boun... |
0951e8fa248777ca0d6a339616f55af50028e343 | kevinmolina-io/leetcode | /Dyanmic Programming/1143_LongestCommonSubsequence.py | 1,676 | 3.515625 | 4 | class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
"""
HIGH LEVEL:
I remember this problem from my algorithms class, and it requires a dynamic programming strategy.
Create a matrix based on the lengths of each input string + 1 and default the values... |
54a925d5dffdf378bf8db1cb31627e85d09dac24 | Nextdoor/gradon | /gradon/tools.py | 211 | 3.875 | 4 | import itertools
def tee_count(iter):
""" Returns the a tuple of total entries plus a copy of the original iterator """
countable, copy = itertools.tee(iter)
return sum(1 for _ in countable), copy
|
a2f074d6a26d7f52aaee70467009223c1dcfa094 | AllieChen02/LeetcodeExercise | /String/P1264LargestSubstringBetweenTwoEqualCharacters/LargestSubstringBetweenTwoEqualCharacters.py | 652 | 3.734375 | 4 | import unittest
class Solution:
def maxLengthBetweenEqualCharacters(self, s: str) -> int:
dict,res = {}, -1
for i in range(len(s)):
if s[i] not in dict:
dict[s[i]] = []
dict[s[i]].append(i)
for key, value in dict.items():
print(value)
... |
07fc77c706b50557f9d1c29af7fbed49be0a8c01 | tomatophobia/tetris-python | /tetris.py | 3,267 | 3.609375 | 4 | from draw import draw_board, draw_star
import time
import curses
import keyboard
from block import draw_block
import random
width = 10
height = 10
speed = 0.75
y_start = width // 2
x_start = 1
draw_board(width, height) # draw a board
time.sleep(1) # wait a second
star_y = y_start
star_x = x_start
revolve = 1
# patte... |
1c67060b899fccdbb8ad8d0436983fc116818ea0 | dedededede/demo | /1200. 最小绝对差.py | 780 | 3.546875 | 4 | class Solution(object):
def minimumAbsDifference(self, arr):
"""
:type arr: List[int]
:rtype: List[List[int]]
"""
result = []
min = 0
arr.sort()
for indexi in range(len(arr) - 1):
i, j = arr[indexi], arr[indexi + 1]
temp_min = a... |
7ea4202d76e97850a15f6955f8d640ffa4a5b908 | wojtasfi/Coffee_Machine | /Kawomat/src/Kawomat.py | 4,029 | 3.828125 | 4 |
class Kawa():
def __init__(self,nazwa,woda,mleko,cukier,kawa,cena):
self.nazwa = nazwa
self.woda = woda
self.mleko = mleko
self.cukier = cukier
self.cena = cena
self.kawa = kawa
class Kawomat():
def __init__(self, kawy,wo... |
bef05668c6d1c35f32124e9b52e823c62b94d1da | stav95/Cracking-the-Coding-Interview | /chapter_1/q6.py | 387 | 3.5625 | 4 | def string_compression(s: str) -> str:
new_string = ""
c = s[0]
counter = 0
for i in range(len(s)):
if c == s[i]:
counter += 1
else:
new_string += f'{c}{counter}'
counter = 1
c = s[i]
new_string += f'{c}{counter}'
if len(s) > len... |
bb7f64d6c2c2bf604b8bb6b21da250a86713f18e | nachocrc/ProyectosTareaUsach | /Ejercicio 7.2.py | 515 | 3.90625 | 4 | print("tomaremos los primos dentro del parametro [numero1,numero2]")
num1=int(input("digite su primer numero: "))
num2=int(input("digite su segundo numero: "))
div=2
while num1<=(num2 -1):
num1+=1
div=2
while num1>=div :
if num1%div==0:
if num1==2:
print("2 es primo")
... |
9ee3dc3853c94ed8d5f06b7722bfcd1587ef10aa | rinisha0112/remote_demo | /Day1/Q5.py | 349 | 3.703125 | 4 |
unsortedList = ['Aaaa', 'bb', 'cccccccc', 'zzzzzzzzzzzz']
sortedList=sorted(unsortedList, key=len)
print(sortedList)
"""
length_list=[]
for i in range(len(unsortedList)):
length_list.append(len(unsortedList[i]))
sortedList=[]
for i in range(len(unsortedList)):
g=length_list.argmin()
sortedList.appe... |
a5a68e24f5d2fe516b0485de1889132fed302395 | vasetousa/Python-Advanced | /Sets and Tuples/Battle of Names.py | 676 | 3.921875 | 4 | n = int(input())
odd_set = set()
even_set = set()
for _ in range(1, n+1):
names = input()
names_len = len(names)
sum_value = 0
for l in names:
value = ord(l)
sum_value += value
sum_value //= _
if sum_value % 2 == 0:
even_set.add(sum_value)
else:
odd_set.add(su... |
6d5e142c5efbc04d3cafb9983ab02d6e035a8ab8 | victorers1/anotacoes_curso_python | /excript/aulas/aula54_atribuicao.py | 120 | 3.984375 | 4 | x = 1
print(x)
x = x+1
print(x)
x = 1
x += (x+1) #x = x + (x+1)
print(x)
x=2
for i in range(10):
x*=2
print(x) |
80ab0e994cb5ffd86984b15e3a02ffbbf271ea52 | MichaelOgunsanmi/dailyCodingChallenge | /August 2019/10th August 2019/symmetricTree.py | 1,241 | 4.28125 | 4 | # Source: https://leetcode.com/problems/symmetric-tree/
# Level: Easy
#
# Date: 10th August 2019
"""
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following... |
328088012a480a4773be6708591c3724f3bfdd25 | KenjaminButton/runestone_thinkcspy | /16_recursion/exercises/16.8.11.exercise.py | 621 | 3.6875 | 4 | '''
Write a program that solves the following problem: Three missionaries and
three cannibals come to a river and find a boat that holds two people.
Everyone must get across the river to continue on the journey. However,
if the cannibals ever outnumber the missionaries on either bank, the
missionaries will be eaten. Fi... |
8f833704549b554d2500608f93d91f45de6906ba | Ash515/Data-Structures-and-Algorithms | /Python/DataStructures/Stack/stack.py | 595 | 4.03125 | 4 |
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def push(self, item):
self.items.insert(0,item)
def pop(self):
return self.items.pop(0)
def peek(self):
return self.items[0]
def size(self):
return l... |
0c5f84afec9aa8d1322ea2e4c8fac9f90faa8152 | CNFrancois/Assignment.4b | /Inclass grade finder.py | 299 | 4.15625 | 4 | print('This is to figure out your final grade')
print('Enter your grade 0-100')
x=int(input())
if x>100 or x<0:
print('This does not fall within grading guidelines')
elif x>=90:
print('A')
elif x>=80:
print('B')
elif x>=70:
print('C')
elif x>=60:
print('D')
else:
print('F')
|
73c0518a4351f5798e4d3a41e051616e770d9fcf | rupali23-singh/task_question | /bill.py | 172 | 3.78125 | 4 | amt=0
num=int(input("enter the number"))
if num<=100:
amt=0
if num>100 and num<=200:
amt=(num-200)*5
if num>200:
amt=500+(num-200)*10
print("amount to pay",amt) |
60467de4a2940c96178ef388dbb85c24ce4d3458 | gar-kai/com404 | /TCA/Question_3/Q3.1/bot.py | 197 | 3.9375 | 4 | print("How many zones must I cross?")
user=int(input())
print("Crossing zones...")
while user>0:
print("... crossed zone " + str(user))
user = user-1
print("Crossed all zones. Jumanji!") |
50cf95a10c76c73b6b1517d7d32a231ba179be93 | ibrahimhalilbayat/Python-Course-Home-Works | /3_2_ATM.py | 1,114 | 4.15625 | 4 | """
Python Homework for Online Python Course
by
Ibrahim Halil Bayat, PhD
Department of Electronics and Communication Engineering
Istanbul Technical University
Istanbul, Turkey
"""
print("""
******************
Welcome to the ATM Machine.
Options:
1) Check the amount.
2) Put money into the bank account.
3) ... |
3091965e79ee854d85670e8c850490530dee8189 | christyycchen/Interview-Cake | /apple_stocks.py | 1,088 | 3.9375 | 4 | def my_function(arg):
# write the body of your function here
max_value = None
for n in range(len(arg)):
for i in range(1, len(arg)-n):
if arg[i+n]-arg[n] > max_value or max_value is None:
max_value = arg[i+n]-arg[n]
return max_value
# run your function through some ... |
1e02965ee6b555bc99d9b6869fd44c0179dcad39 | greedtn/EEIC-Algorithms2021 | /第3回/b.py | 1,564 | 3.546875 | 4 | # 最大ヒープを実装する
class MyHeap:
def __init__(self, size):
self.inf = -10 ** 9
self.size = size + 1
self.array = [self.inf] * self.size
self.last = 0
def add(self, value: int):
self.last += 1
self.array[self.last] = value
return self.check_after_add(self.la... |
b9f10c2556f90bed679f14e79d9c240eeb9eb403 | CodingClubGECB/practice-questions | /Python/Week-3/04_power.py | 197 | 4.34375 | 4 | #4.Write a program to find the power of a number using recursion
def power(x, n):
if n == 0:
return 1
else:
return x * power(x, n - 1)
x = int(input())
n = int(input())
print(power(x, n))
|
39c400de33b23f6a623e2395b77e80fc4e8f8e2f | lily-liang12/Delan-Huang-Employee_Scheduler | /Employee_Project/Monthly_Calendar.py | 2,201 | 4.21875 | 4 | import datetime
import calendar
def create_current_monthly_calendar():
"""Creates a monthly calendar separated by weeks/days"""
# Grab current month calendar, separate by weeks, and remove weekends
today = str(datetime.date.today())
year = today.split('-')[0]
month = today.split('-')[1]... |
5a81ce928e133ac618224af4349d354367228d55 | BhumikaReddy/3GRM | /Programming/Python/oddAndEven.py | 150 | 3.6875 | 4 | #seperate add and even using filter
l=[1,2,3,4,5,6,7,8,9]
print(list(filter(lambda x:x%2==0,a)), "even")
print(list(filter(lambda x:x%2!=0,a)),"odd")
|
0e5dbbe916c648c33774320cb438b4ed46d5f8c7 | hank7468/c_to_f | /ftoctransfer.py | 220 | 4 | 4 | # Fahrenheit to Celsius transaction
celsius = input('please input celsius temperature: ')
fahrenheit = float(celsius) * 9 / 5 + 32
# +-*/算符與數字間有空格較佳
print('fahrenheit is as following: ', fahrenheit) |
213306135f554892a6e0fddd022148ab8fdfad2e | bussierem/new52 | /Q1/07_proc_generation/src/procGen.py | 1,896 | 4.03125 | 4 | """
NOTES:
Basic Binary-Space Partition Algorithm:
DEFINITIONS:
Zone: Rooms and Halls - represents a section of the grid
Origin (x,y coords of top-left unit)
Width (in units)
Height (in units)
Min Width/Height for a Room: minW, minH
Room: A zone of at least 4x4 units size
Hall: ... |
1945a2fa5b300a921bfc8d989e7cdaa502cd4c5c | nervig/Starting_Out_With_Python | /Chapter_3_programming_tasks/task_5.py | 299 | 4.0625 | 4 | # weight in H = weight in kg * 9.8
user_weight_in_kg = float(input("Enter your weight in kg: "))
user_weight_in_H = user_weight_in_kg * 9.8
print(round(user_weight_in_H))
if user_weight_in_H > 500:
print("Your body is too heavy!")
if user_weight_in_H < 100:
print("Your body is too light!")
|
1976a17ccc45958a0ffe98e5d0424f402caed829 | shreetiranjit/LabWork | /Lab3/eight.py | 903 | 4.1875 | 4 | '''
Write a Python function that takes a number as a parameter and check the number is prime or not.
Note : A prime number (or a prime) is a natural number greater than 1 and that has no positive divisors
other than 1 and itself.
'''
def primenumber(num) :
not_prime = 0
for i in range (2,num) :
if num %... |
5af17065d86d9957ab7ef1398ccb6f56fce6c10c | g0dgamerz/workshop | /assignment1/f17.py | 192 | 4.1875 | 4 | # Write a Python program to find if a given string starts with a given character
# using Lambda.
def starts_with(x): return True if x.startswith('J') else False
print(starts_with('jidesh'))
|
f4cc839420c369d5d3ec27c2cc2e1f12cdce33a8 | manoelsouzas/DesafioProg | /palindromo.py | 353 | 4 | 4 | numeroinicial = int(input("insira o primeiro número:"))
numerofinal = int(input("insira o primeiro número:"))
palindromos = []
for numerotestado in range(numeroinicial, numerofinal):
if str(numerotestado) == str(numerotestado)[::-1]:
palindromos.append(str(numerotestado))
print('São Palindromos: {}'.f... |
e9fabba31426eae757fcf92cf1b807663c7f1ef9 | arazzguliyef/Araz-python | /IELTS_Listening_score.py | 813 | 3.609375 | 4 | from pasword import security
security()
print("……….IELTS ACADEMIC LISTENING SCORE………")
note=float(input('……..notunuzu girin lutfen:'))
def listening():
if note>=39:
print(9)
elif note>=37:
print(8.5)
elif note>=35:
print(8)
elif note>=32:
print(7.5)
elif... |
ac6b393864bf9bfaafbdbc0e1668af238031ac06 | amalshehu/exercism-python | /leap/leap.py | 191 | 4.09375 | 4 | # Leap year python
def leap(year):
if (year % 400) == 0 or (year % 4) == 0 and (year % 100) != 0:
return "leap Year"
else:
return "not a leap year"
|
66242fb520455255c52be016669c4d3778bd8d83 | Rainmonth/PythonLearning | /fileops/test.py | 2,569 | 3.9375 | 4 | # #!/usr/bin/python
# # -*- coding: UTF-8 -*-
#
# x = "a"
# y = "b"
# # 换行输出
# print(x)
# print(y)
#
# print('---------')
# # 不换行输出
# print(x),
# print(y),
#
# tuple1 = ('runoob', 786, 2.23, 'john', 70.2)
# tinytuple = (123, 'john')
#
# print(tuple1) # 输出完整元组
# print(tuple1[0]) # 输出元组的第一个元素
# print(tuple1[1:3]) # 输出... |
58399b06fcec170c0b0b93af806a1e146f80fe08 | Zer0xPoint/NowCoder_OJ | /1.29.py | 706 | 3.78125 | 4 | # 题目描述
# 假设你正在玩跳格子(所有格子排成一个纵列)游戏。需要 跳完n 个格子你才能抵达终点。
# 每次你可以跳 1 或 2 个格子。你有多少种不同的方法可以到达终点呢?
# 注意:给定 n 是一个正整数。
# 输入描述:
# 格子数n
# 输出描述:
# 跳完n个格子到达终点的方法
# 示例1
# 输入
#
# 2
# 输出
#
# 2
# 阶乘
def factorial(x):
f = 1
for i in range(1, x + 1):
f *= i
return f
elements = int(input())
quotient = elements // 2
n ... |
e7070b75ec80d1bde2a01a3fd3f33e7a466568b5 | EspioRain/python-practicas | /excepciones.py | 276 | 3.921875 | 4 |
paises = {
"ar": "Argentina",
"es": "España",
"us": "Estados Unidos",
"fr": "Francia"
}
while True:
try:
codigo = input('Ingrese codigo del pais: ')
print(paises[codigo])
break
except Exception:
print('Ese codigo de pais no existe.') |
121ebfb1454499442435975b1d64d6fa1f2a84c0 | Demi0619/Alien-Invasion-Game | /bullets.py | 664 | 3.640625 | 4 | import pygame
from pygame.sprite import Sprite
class Bullets(Sprite):
''' a class to manage bullet fired from ship'''
def __init__(self, ai_game):
super().__init__()
self.screen = ai_game.screen
self.settings=ai_game.setting1
self.color=self.settings.bullet_color
self.r... |
629d7b11b9533aacd35749493c860e13b0f1528b | lxconfig/BlockChainDemo | /Python_Workspace/final/final.py | 5,940 | 3.6875 | 4 | #!/usr/bin/python
#-*-coding:utf-8 -*-
import csv
from Person import Person
from Combination import Combination
import sys
def read_csv():
persons = []
with open('data.csv', 'r') as f:
reader = csv.reader(f)
raw_persons = list(reader)
for p in raw_persons[1:]: # first line are the names
... |
9f8f3064edcff4c1de6bfe3bfc8c107c7d2a4f3c | pertain99/guttag_python_2e | /chapter05/FunctionsAsObjects.py | 530 | 3.921875 | 4 | def applyToEach(L, f):
"""Assume L is a list, f is a function
mutates L by replacing each element, e, of L by f(e)"""
for i in range(len(L)):
L[i] = f(L[i])
L = [1, -2, 3.3]
print("L =", L)
print("Apply abs to each element of", L)
applyToEach(L, abs)
print('L =', L)
print("Apply int to each e... |
2c96805c2e8f3bb81b5aef3c74cde6fe22e3d705 | chrisgangbarber/schoolwork | /Gan/Moving_Cloud/Moving_Cloud.pyde | 691 | 3.59375 | 4 | x = 0
def setup():
size(640,480)
def draw():
global x
print (x)
if x >= 640:
x = 0
x += 10
background(135, 206, 235) # sky blue
#clouds
fill(255)
ellipse (x, height/6 + 10, 50, 50)
ellipse (x, height/6 - 12, 50, 50)
ellipse (x - 33, height/6, 50, 50)
ellipse (x... |
a6b9ea3fc8373617ee86d5b1aeedf95955178586 | MarcosDGFilho/100daysofcode | /Day 4 - Rock, Paper and Scissors.py | 3,006 | 3.75 | 4 | # %%
import random
#tryAgain = True
while True:
playerMove = 0 ##Rock = +1, Paper = +2, Scissor = +3
computerMove = 0 ##the result of the match is determined by playerMove - computerMove
print("\nWelcome to Janken\n")
playerMove = int(input('''
.-----------------------.
|Please select yo... |
76771b9b87e70fcb27e78d09391a54c9632c00dc | akimi-yano/algorithm-practice | /lc/1856.MaximumSubarrayMin-Product.py | 1,941 | 3.890625 | 4 | # 1856. Maximum Subarray Min-Product
# Medium
# 184
# 7
# Add to List
# Share
# The min-product of an array is equal to the minimum value in the array multiplied by the array's sum.
# For example, the array [3,2,5] (minimum value is 2) has a min-product of 2 * (3+2+5) = 2 * 10 = 20.
# Given an array of integers nu... |
ad400ebc5cec0e0fb23f3f91b915f8b83b52b10f | programmicon/teknowledge | /curriculum/03_functions_01_adventure/03_01_01_review_challenge.py | 732 | 3.984375 | 4 | # review challenge
oldUser = 'Alex' # variable, 1 equals sign
newUser = input("What is your name? --> ") # returns a string
if oldUser == newUser: # testing equality, 2 equal signs
print() # what do you think this does
print("Welcome back Alex!")
else:
print()
print("Welcome " + newUser + ... |
8d8a29507da51f2a1cca445af7a0bd7ee401e636 | amadeusantos/Mundo_1 | /desafio08019.py | 306 | 3.65625 | 4 | from random import choice
a1 = str(input('Qual o nome do primeiro aluno: '))
a2 = str(input('Qual o nome do segundo aluno: '))
a3 = str(input('Qual o nome do terceiro aluno: '))
a4 = str(input('Qual o nome do quarto aluno: '))
aluno = choice((a1, a2, a3, a4))
print(f'O aluno(a) sortado(a) foi {aluno}.')
|
f4ee092254c10cd8f9e67f391f6f5b7d32756410 | TyroneWilkinson/Python_Practice | /climb_leaderboard2.py | 852 | 4.0625 | 4 | # https://www.hackerrank.com/challenges/climbing-the-leaderboard/problem
# Not fast enough.
def climbingLeaderboard(l, p):
"""
Determine a player's ranking after each game played given his scores
and the leaderboard scores.
Note: The game uses dense ranking.
Parameters:
l (list): An integer li... |
c69dd3a631ac93b58bfba3d1de1e615f89cbced5 | arsenijevicn/Python_HeadFirst | /chapter3/vowels3.py | 343 | 3.59375 | 4 | found = {}
print(found)
found['a'] = 0
found['e'] = 0
found['i'] = 0
found['o'] = 0
found['u'] = 0
print(found)
found['e'] = found['e'] + 1
print(found)
found['e'] += 1
print(found)
for k in sorted(found):
print(k, 'was found', found[k], 'time(s).')
print()
for k, v in sorted(found.items()):
print(k, 'was ... |
03b8090d6b27e8d73027908cacdedb10002a08cc | sry19/python5001 | /hw07/team_manager_starter/team.py | 1,885 | 4.15625 | 4 | from player import Player
class Team:
"""A class representing a dodgeball team"""
def __init__(self):
'''contruct a team which has name and player list'''
self.name = "Anonymous Team"
self.players = []
def set_team_name(self, name):
'''set the team name'''
self.nam... |
b28007b8434b75d7b5f6433c52e75758c9ee1f18 | Menighin/Studies-Tests | /Python/Python for Zombies/Exercises/Exercise 1/exercicio01_joaomenighin_07.py | 115 | 3.875 | 4 | celsius = float(input('Temperature in celsius: '))
print('%.1fºC is %.1fºF' %(celsius, (9 * (celsius/5) + 32)))
|
a7fab8be910a14c97ddb10efca373b7cb04bcb8b | astrodextro/hackerrank_30_days_coding_challenge | /python3/d10_binary.py | 549 | 3.6875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
from itertools import groupby
def convertToBinary(n):
binary = bin(n)
binList = list(binary)
repeats = list()
del(binList[0])
del(binList[0])
bi = [len(list(g)) for k, g in groupby(binList, key=lambda x: x == "1") if k]
... |
57646ac5d8c05d1725e8203b0b620a57f4c4fc50 | patrickcoyle427/PythonPractice | /edXMITIntroToCS1/listFlattener.py | 895 | 4.28125 | 4 | #!/usr/bin/python3
'''
Takes a list containing lists/tuples and creates a new list that contains no lists/tuples, but with the values of those lists/tuples intact.
'''
def listFlattener(L):
flattenedList = []
tempList = []
for i in L:
if type(i) is list or type(i) is tuple:
... |
5e33e6552dd8b16defb3aa9264b3fa939dbde54f | droconnel22/QuestionSet_Python | /HackerRank/BusStops/test/bus_stops_test_fixture.py | 1,163 | 3.84375 | 4 | from main.bus_stops import BusStop
import unittest
class TestBusStopMethods(unittest.TestCase):
def test_split(self):
s = 'hello world'
self.assertEqual(s.split(), ['hello', 'world'])
# check that s.split fails when the separator is not a string
with self.assertRais... |
611f1c7fd44392d0ac343448224c57d2a1d5a9e1 | matthowe/Hangman | /hangman simplified.py | 2,227 | 4.1875 | 4 | import random
def getWord():
"""Get a word from the dictionary text file - done once. Words are held in list for all later games"""
f = open("wordsEn.txt")
words = []
for word in f:
if len(word) > 2: #only add words of 3 characters or more
words.append(word.rstrip('\n')) #strip the ... |
6088569e182725e4d68663b8098b5410e7bc0c8b | naffi192123/Python_Programming_CDAC | /Day3/10-find.py | 197 | 4.34375 | 4 | #program to search an element in a tuple
n = int(input("Enter the element to search: "))
tupl =(1,2,3,4,5)
for i in tupl:
if n == i:
print("Found")
break
else:
print("not found")
continue |
86e09ac9e40bf4d6eb9f639ace3d1b1dc79d3a5c | M4ndU/study | /Calculator_quadratic.py | 1,031 | 3.796875 | 4 | #이차함수의 해를 구해주는 파이썬 프로그램
#2018.03.23
#
#
from math import sqrt #루트사용을 위한 모듈
def main():
try :
#이차함수의 각 항의 계수를 입력받는다.
a = float(input("첫번째 계수:"))
b = float(input("두번째 계수:"))
c = float(input("세번째 계수:"))
#판별식 계산
d = b * b - 4 * a * c
#판별... |
c4d18e3d176c3388bd6bbf079f1667f96217c353 | EricSzcz/Learning-python | /range_Class13.py | 466 | 4.03125 | 4 |
# coding: utf-8
# In[7]:
range(10)
# In[8]:
x = range(0,10)
# In[9]:
x
# In[10]:
type(x)
# In[12]:
start = 5
stop = 20
range(start, stop)
# In[13]:
start = 0
stop = 20
range(start, stop)
# In[14]:
start = 0
stop = 20
range(start, stop,2)
# In[15]:
l = [1,2,3,4,5]
# In[17]:
for num in... |
c3b443ccb7edeca453ebd239eb0ecc5b5a3093ee | f18-os/python-intro-alira33 | /wordCount.py | 1,343 | 3.90625 | 4 | #! /usr/bin/env python3
import sys # command line arguments
import re # regular expression tools
import os
# set input and output files
if len(sys.argv) is not 3:
print("Correct usage: wordCount.py <input text file> <output file>")
exit()
input = sys.argv[1]
output = sys.argv[2]
def regex(key, text_strin... |
dca40875fb545355bf67a17b5d4db3bc29bd3dcf | leochinherera/Mars-Rover-challenge | /Rover_tests_class/Correct_test_Rover_Position.py | 2,938 | 3.703125 | 4 | """
Module to test rover position library used in the
MarsRover Challenge program.
We make use of unittest from Python.
"""
# We import the math module to make use of Pi
import math as mt
# Import unittest for testing
import unittest
# We import sys Pyhton library to be sure ...
# import class to be tested
fro... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.