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 |
|---|---|---|---|---|---|---|
9a9f0d284905b3a59f88d8d88e960b8a0d64adc5 | balocik/Simple-Python-Games | /Pet.py | 2,023 | 4.125 | 4 | #---------------------------
# 12/10/2017
# created by Wojciech Kuczer
#---------------------------
class Pet(object):
"""virtual pet"""
def __init__(self,name, hunger = 0, boredom =0):
self.name = name
self.hunger = hunger
self.boredom = boredom
def __pass_time(self):
... |
14239b7ebfe8443561adb26054827fee9cea0268 | joebigjoe/Hadoop | /Spark快速大数据分析/第 3 章 RDD 编程/Python OOP Basic/classTest8.py | 389 | 3.90625 | 4 | class User:
def __init__(self, name, email, gender):
self.name = name
self.email = email
self.gender = gender
# this is like the toString() method of C#
def __repr__(self):
return self.name + " " + self.gender + " " + self.email
joey = User("Joey", "412371201@163.com",... |
6d7f2d6cdeded267a654d962ce7fcb50fde1be62 | ishritam/python-Programming--The-hard-way-Exercises | /ex21.py | 749 | 3.828125 | 4 | def add(a,b):
return a + b
def sub(a,b):
return a - b
def mult(a,b):
return a * b
def div(a,b):
return a / b
addition = add(10, 10)
substract= sub(10,10)
multiplication = mult(10, 10)
division = div(10,10)
puzzel = add(addition,sub(substract,mult(multiplication,div(division,1))))
#puzzel = add(add(10,10),su... |
a64d8d6ee3f15bf1c0a5c58b34073103a16eeb0b | hooyao/Coding-Py3 | /LeetCode/Problems/36_valid_sudoku.py | 2,757 | 3.578125 | 4 | import sys
class Solution:
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
if len(board) != 9 or len(board[0]) != 9:
raise Exception()
# test block
for i in range(3):
for j in range(3):
... |
cf7eae842bbbb7aa0f95204b291f06cea21e74a5 | isongjosiah/team_pasteur | /Priyanka.py | 701 | 3.59375 | 4 | #!/usr/bin/python3
name = 'Priyanka Pandit'
email = 'priyupandit99@gmail.com'
slack_username = '@PriyankaPandit'
biostack = 'Drug Development'
twitter_handle = '@PiiiyuuuPandit'
def h_d(string1, string2):
# Start with a distance of zero, and count up
distance = 0
# Loop over the indices of the... |
24ebea06a0190a4d771d02761924be048062e6aa | andart7777/haudiho1 | /temp.py | 1,616 | 3.78125 | 4 |
file = open("newfile.txt", "a")
file.write("Всего с наценкой: " + str(c) + "р" + " --- " + "Прибыль с одной штуки: " + str(w) + "р" + "\n")
file.write("Итого за все: " + str(f) + "р" + " --- " + "Прибыль за все :" + ee + "р")
file.close()
# def mem_add():
#
# file = open("newfile.txt", "a")
# file.write("Всего... |
f3c4cc748d2b054371102414efa7df108fb357df | ineed-coffee/PS_source_code | /HackerRank/Non-Divisible Subset(Medium).py | 917 | 3.8125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'nonDivisibleSubset' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER k
# 2. INTEGER_ARRAY s
#
def nonDivisibleSubset(k, s):
s_dict={i:0 for i in ... |
3cf1c86b6856d708be97e25d4541adfd49c9eb79 | odlt98/css301 | /m3problem3.py | 444 | 3.8125 | 4 | #Omar De La Torre
#4/23/2019
import turtle
def tree(branchLen,t):
if branchLen>5:
t.forward(branchLen)
t.right(20)
tree(branchLen-15,t)
t.left(40)
tree(branchLen-15,t)
t.right(20)
t.backward(branchLen)
def main():
t=turtle.Turtle()
... |
00ad3e568e039e773e86ff9c28f18bb309221c1e | macluiggy/Python-Crash-Course-2nd-edition-Chapter-1-11-solutions | /CHAPTER 10/10-10. Common Words.py | 401 | 4.15625 | 4 | # Choice a file and show how many times a specific word appears
# in the file.
filename = 'potions.txt'
try:
with open(filename, encoding='utf-8') as f:
contents = f.read()
except UnicodeDecodeError:
pass
except FileNotFoundError:
print(f"Sorry, I couldn't find that file")
else:
word_count = contents.lower().... |
fa44fe7023bddf235ae9ad8beea6e2074d206148 | mfbalder/Skills1 | /test_skills1.py | 1,724 | 3.515625 | 4 | import unittest
from skills1 import *
class TestSkills(unittest.TestCase):
def setUp(self):
self.words = ["hello", "my", "name", "is", "Michaela", "and", "I", "am", "a", "lady"]
self.numbers = [1, 2, 7, 12, 15, -2, 3, -17, 100, -2]
def test_1_A_all_odd(self):
self.assertEqual(all_odd(self.numbers), [1, 7, ... |
13196f8d1bcfc7400b54a0217710214e21d68642 | sakir66/Python_Kitap | /BOLUM_10/KTP_Uygulama10_2.py | 254 | 3.625 | 4 | #!C:\Python38\python.exe
yas=input('Yaşınızı Giriniz: ')
try:
yas=int(yas)
print("Üç yıl sonra %d yaşında olacaksınız" % (yas+3))
except:
print('Sayı değer girseydiniz üç yıl sonra hangi yaşta olacağınızı söyleyecektim') |
3a227a09c89cf391655b574bdccda1ef77a44912 | DiogoCastro/prototype_get_data | /app.py | 1,665 | 3.53125 | 4 | #!/usr/bin/env python
"""Allows to dynamically manipulate a file in a given link and stores its content in a formatted way."""
from flask import Flask, jsonify
import io
import requests
import pandas as pd
import ast
app = Flask(__name__)
@app.route('/get-all-data')
def get_data_csv():
"""Get data from a specific... |
b12a4228ef2950a524f1b7754f7fff6d77f772a2 | VishalJoshi21/Python_Program | /prg8.py | 201 | 4.125 | 4 | num=int(input("Enter number :"));
no=num;
res=0;
while num>0:
temp=num%10;
res=(res*10)+temp;
num=int(num/10);
if(no==res):
print("Number is Palindrome");
else:
print("Number is not Palindrome"); |
159bec87265ee9c3ffa81efa3e4656c2873c2b40 | keg51051/PythonProjects | /PythonProject/A4THU-Week11.py | 680 | 4.28125 | 4 | # Dictionaries
Countries = {"CA": "Canada",
"US": "United States",
"UK": "United Kingdom",
"MX": "Mexico"}
# Prompt user to enter a country code
# if the country_code is exist
# remove it, otherwise display error
key = input("Enter a country code: ")
if Countries.get(key):
Co... |
664a65d139256d64fca2a97d4c30c86c691a4534 | 404-sdok/python-application | /kpjhg0124/app.py | 516 | 3.53125 | 4 | account = {
'naver' : {
'id' : 'kpjhg0124',
'pw' : 'hello'
},
'facebook' : {
'id' : 'me@ho9.me',
'pw' : 'facebook_password'
}
}
while(1): # 계속 반복
print('naver, facebook?', end = '') # 질문
result = input() # result 변수에 질문 답변 저장
if result in ['naver', 'facebook'... |
0f43cc9e80b8ed4b15fd0f30571c9629a3b17b53 | wilsonify/euler | /src/euler_python_package/euler_python/easiest/p007.py | 805 | 3.828125 | 4 | import itertools
from euler_python.utils import eulerlib
def problem007():
"""
Computers are fast, so we can implement this solution by testing each number
individually for primeness, instead of using the more efficient sieve of Eratosthenes.
The algorithm starts with an infinite stream of incrementi... |
40cc1f5613666a47c4c55edd2cc66d15b16f340e | pratikv06/python-tkinter | /Radio2.py | 719 | 3.828125 | 4 | from tkinter import *
root = Tk()
root.title("Radio")
def clicked(value):
result = Label(frame, text=value)
result.pack()
# Radiobutton(root, text='Option 1', variable=r, value=1).pack()
# Radiobutton(root, text='Option 2', variable=r, value=2).pack()
TOPPINGS = [
("Pepperoni", "Pepperoni"),
... |
a78ad9053d51f535cd1f65fc5d4dc167b32d8b0b | mridhosaputraad/DocumentationPython | /p9. while loop/latihan2.py | 588 | 3.609375 | 4 | # Contoh 3 : else, continue, pass
angka = 0
while angka < 10:
if angka == 5:
# print('checkpoint 1')
# break
# jadi akan langsung keluar dari looping
# Solusinya
# angka += 1
# continue
# Dia tidak error, tapi akan stack di angka 5 jadinya posisinya infinit... |
8ac1fdb4fa0da1ba5ecbfa48dd2816ec8fe79e76 | yangdissy/TDClass01 | /Lesson-3-初步认识Python/homework/01002-杨帅/Guess the number you entered.py | 184 | 3.765625 | 4 | import random
a = int(raw_input("Please enter a number(0-100):"))
b = random.randint(0,100)
while b != a:
if b > a:
b -= 1
else:
b += 1
print "Thenumber you entered is:%d" % b |
6120845bd8b12fbf5b4f0de25f26c9dfd7d7d89e | ferryleaf/GitPythonPrgms | /numbers/total_count_of_number_with_even_number_of_digits.py | 1,244 | 4.40625 | 4 | '''
Given an array nums of integers, return how many of them contain an even number of digits.
Example 1:
Input: nums = [12,345,2,6,7896]
Output: 2
Explanation:
12 contains 2 digits (even number of digits).
345 contains 3 digits (odd number of digits).
2 contains 1 digit (odd number of digits).
6 contains 1 digit (odd... |
4614af1dd882e7d0cbb96c764f990a96509e88a4 | eblade/articulate | /articulate/scope.py | 3,204 | 3.609375 | 4 | """
A scope is a local set of variables and functions.
"""
from .parser import Pattern
class Scope(dict):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.functions = {}
self.return_value = None
self.returning = False
self._exposed = []
def d... |
75e6bc4ce6edea44ba79ff9815d45d04052a9d88 | changeworld/nlp100 | /python/01/09.py | 1,054 | 3.890625 | 4 | # -*- coding: utf-8 -*-
# 09. Typoglycemia
# スペースで区切られた単語列に対して,各単語の先頭と末尾の文字は残し,それ以外の文字の順序をランダムに並び替えるプログラムを作成せよ.ただし,長さが4以下の単語は並び替えないこととする.適当な英語の文(例えば"I couldn't believe that I could actually understand what I was reading : the phenomenal power of the human mind .")を与え,その実行結果を確認せよ.
import random
def typoglycemia(str):
... |
f037a2b79c4a555e17e6c03c6a994ab40e89894c | Homap/data_science | /09.07.2019/python_problemSolve/fasta_to_dict.py | 574 | 3.796875 | 4 | #!/usr/bin/python
import sys
#********************************
# Written by Homa Papoli
# Version 1. 16 July 2019
#********************************
# Exercise 2: Store the fasta file into a dictionary.
#********************************
# Run: python fasta_to_dict.py fasta_exercise_goodheader.fa
#*********************... |
c657579877af6e139f66d620cb1c210db091c520 | chriszimmerman/python_month | /sudoku/square.py | 432 | 3.640625 | 4 | class Square(object):
def __init__(self, number, row, column, block):
self.number = number
self.row = row
self.column = column
self.block = block
def __eq__(self, other):
return (isinstance(other, self.__class__)
and self.__dict__ == other.__dict__)
... |
87d0f2ebb59cd41510cb9f2a863077c1c758aeef | MikkelPaulson/advent-of-code-2020 | /day23/__init__.py | 2,685 | 4.03125 | 4 | """https://adventofcode.com/2020/day/23"""
import io
def part1(stdin: io.TextIOWrapper, stderr: io.TextIOWrapper) -> int:
"""
Using your labeling, simulate 100 moves. What are the labels on the cups
after cup 1?
"""
cups = parse(stdin)
play(cups, 100)
stderr.write(f"End of game: {cups}... |
f45523f038a67ca782530a15ad1532392dc55ee7 | nicocavalcanti/processing_py | /Food.py | 1,105 | 3.875 | 4 | # The "Food" class
class Food():
def __init__(self, x, y, vel):
self.acceleration = PVector(0, 0)
self.velocity = vel
self.position = PVector(x, y)
self.r = 12
self.color = color(127)
# Method to update food location
def update(self, x, y):
newPos = PVe... |
3846fa8ac28f483ce33f86978ce318aaa1da2eed | zulhaziq86/GroupProject_client | /modify2.py | 1,810 | 3.546875 | 4 | import socket
import math
ClientSocket = socket.socket()
host = '192.168.0.161'
port = 8888
print('Waiting for connection')
try:
ClientSocket.connect((host, port))
print('Connected!!')
except socket.error as ex:
print(str(ex))
Response = ClientSocket.recv(1024).decode()
print(Response)
while True:
p... |
0730a9c43c7717baf032a183f288739bd0bd4a1b | poojasingh1995/MOREEXERCISE | /ques_4.py | 379 | 4.21875 | 4 | # num1=int(input("enter the num"))
# num2=int(input("enter the num"))
# num3=int(input("enter the num"))
# if num1>num2>num3 or num3>num2>num1:
# print(num2,"second greatest num")
# elif num2>num1>num3 or num3>num1>num2:
# print(num1,"second gretest num")
# elif num2>num3>num1 or num1>num3>num2:
# print(num... |
b5f13df49f0c56e009e764fa55863c598c52c3c4 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2514/60846/277965.py | 163 | 3.90625 | 4 | def func(substr,str):
for ch in substr:
if ch not in str: return False
return True
if func(input(),input()): print("True")
else: print("False") |
a0aa912e46a15faed7aa11dade1eda1ddcf62e08 | xuedagong/hello | /leetcode/python/Largest Number.py | 822 | 4.3125 | 4 | #coding=utf-8
'''
Given a list of non negative integers, arrange them such that they form the largest number.
For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.
Note: The result may be very large, so you need to return a string instead of an integer.
Credits:
Special thanks to @ts for adding... |
ca8498b5e3ac8cb64c99242c7990326d3f1a2e95 | CaiqueAmancio/ExercPython | /exerc_8.py | 674 | 4.09375 | 4 | """
faça um programa que leia 2 notas de um aluno, verifique se as notas são válidas e
exiba na tela a média das notas. Uma nota válida deve ser, obrigatoriamente, um valor entre
0.0 e 10.0, onde caso a nota não possua um valor válido, este fato deve ser informado ao
usuário e o programa termina.
"""
print(f'Olá, insi... |
3843da4195c791ac669cfbaf80d8ad08e9488759 | econgrowth/econgrowth.github.io-src | /content/notebooks/RandomWalk.py | 748 | 3.71875 | 4 | #!/usr/bin/env python
# coding=utf-8
'''
My First script in Python
Author: Me
E-mail: me@me.com
Website: http://me.com
GitHub: https://github.com/me
Date: Today
This code computes Random Walks and graphs them
'''
import numpy as np
import matplotlib.pyplot as plt
# The function
def randomwalk(x0, T, mu, sigma, see... |
8c8e6035c761cd403ab8c6960586af4a2956e0d6 | HWALIMLEE/study | /keras/keras17_mlp_test.py | 2,693 | 3.734375 | 4 | # multi layer perceptron
#1. 데이터(x, y값 준비)
import numpy as np
#시작지점은 1, 뒤에서 -1빼기 range여러개 나열하면 오류가 나옴--->리스트로 만들면 된다.
#3행 100열로 나오게 된다. >>>100행 3열로 바꿔야 함
#바꾸려면....?
x=np.array([range(1,101),range(311,411),range(100)]) #--->x=np.transpose(x)로 바꾸자
y=np.array(range(711,811))
#리스트-다 모아져 있는 것, [ ]쓰지 않으면 출력이 안 된다.
x=np.tr... |
f40f4e35b419fa143fbc2e0fb0ab92719e613aa5 | minkyeong081004/MK-S-fishgame | /play2.py | 2,188 | 3.8125 | 4 | import turtle as t
import random as r
#shark
shark=t.Turtle()
shark.shape("triangle")
shark.color("salmon")
shark.speed(0)
shark.penup()
shark.goto(r.randint(-200,200),r.randint(-200,200))
#plain
plain=t.Turtle()
plain.shape("circle")
plain.color("teal")
plain.speed(0)
plain.penup()
plain.goto(r.randint(-200,200),r.r... |
cced27da5edc8ae83030e57694137f09a33026cb | JimVargas5/Numerical_Analysis | /Numerical_Calculus/HW/HW2/2_2_p3_supp.py | 402 | 3.625 | 4 | # Jim Vargas
import math
r=math.pi/2.0
def f(x):
return (math.cos(x))**2.0
def f_prime(x):
return -2*math.sin(x)*math.cos(x)
def Newton(x,f,f_prime):
return x-f(x)/f_prime(x)
def Newton1(x):
return (math.cos(x) + 2*x*math.sin(x))/(2*math.sin(x))
x0=1
x=x0
n=0
while abs(x-r)!=0:
t1=abs(x-r)
x=... |
b9bc654c7d5db43dd9d521343d0a98f7a6b76eff | SirAeroWN/randomPython | /Euler Problems/Euler3.py | 2,520 | 3.90625 | 4 | # This program solves Eulers problem 3
# What is the largest prime factor for the number 600851475143
# this requires finding some primes, which I've done some work in previously:
#########################
###### EXPLENATION ######
#########################
# This is known as a sieve.
# the way it works is you... |
e968eb9e5e60730b4e2b1cd04fa292ef1e3b7191 | bpPrg/Tips | /Softwares/geany/some_notes/simple_plot.py | 217 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
This is a simple plot script.
"""
from matplotlib import pyplot as plt
x = [5,8,10]
y = [12,16,6]
plt.plot(x,y)
plt.title('Title')
plt.ylabel('Y axis')
plt.xlabel('X axis')
plt.show()
|
f18d95d811c0df9376adf5ee25a4fb93cb660189 | charan2108/Pythondirectories | /PythonIntroduction/FlowControl/IF/ifweight.py | 189 | 3.84375 | 4 | weight = float(input("ENter the weight ig kg: "))
if weight > 60:
print("if weight exceeds the 60kg limit the additional amount has to be paid")
if weight < 60:
print(" Thank you") |
4865022139d5f3ec6835ce21dd6b9e6612491dcb | AshmitaRakshit/Class98 | /function.py | 343 | 3.671875 | 4 | def my_function():
print("Hello from a function")
my_function()
#-----------------------
def my_function(name):
print("welcome ",name)
#calling a function
my_function("Ashmita")
my_function("XH")
#--------------------------
def my_function(fname, lname):
print(fname + " " + lname)
my_function("A... |
9b171484fbd231bf01d1fb2ada2a325f47ad3220 | withhong/python | /basic/12_if.py | 971 | 4.09375 | 4 | # 1. 조건문 (단일 if, if~else, 다중 if, 중첩 if, 3항 연산자)
# 조건문 수행시 코드는 ':'와 indent 를 통해 구분
# 단일 if 문
print("A")
if 1:
print("B")
print("C")
print("#"+"-"*20+"#")
# if~else 문
print("A")
if 1:
print("B")
else:
print("C")
print("#"+"-"*20+"#")
# 다중 if 문
# 입력을 받으면 문자열이다.
# 문자열 -> 정수 : i... |
4569649fc7f70f53e1ee3f78be583f36a2e7a8c7 | GDGGranada/python_django_dic13 | /examples/tabulacionComentada.py | 681 | 3.828125 | 4 | def malTabulado():
#Todo lo que tenga una tabulacion pertenece a esta funcion
print "Yo estoy bien tabulado"
print "Yo la estoy liando parda"
print"Yo estoy bien tabulado"
malTabulado()
''' Por qu este programa no funciona?, veamoslo tranquilamente
En primer logar tenemos la definicion de una fun... |
39ab624465e2be9e425796a45fd281b2540c3cc4 | harikumar-sivakumar/ticketBooking | /ticketBooking.py | 4,081 | 3.578125 | 4 | class ShowList:
shows = []
def createShow(self):
name = input("\nEnter the show name: ").strip()
if len([1 for show in self.shows if show.name == name]) == 0:
self.shows.append(Show(name))
else:
print("Show already exists.")
def soldDetails(self):
if... |
6821aef819e5e5cc46f75e58119a710c760186b8 | stefifm/Guia02 | /temperatura.py | 297 | 3.8125 | 4 | print("Temperaturas en deposito quimico")
#datos
T1=int(input("Cargue Temperatura 1: "))
T2=int(input("Cargue Temperatura 2: "))
T3=int(input("Cargue Temperatura 3: "))
#proceso
prom1=(T1+T2+T3)/3
prom2=(T1+T2+T3)//3
#resultados
print("Promedio decimal: ",prom1)
print("Promedio entero: ",prom2)
|
552f8637c1f336084b4abd16b419d9d74a698013 | janellecueto/HackerRank | /Security/EncryptionScheme.py | 125 | 3.734375 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import math
n = int(input())
print(math.factorial(n))
|
5568f63d737cceb6186b129765f819fac2becd94 | gfcharles/euler | /python/euler024.py | 1,877 | 3.9375 | 4 | """
A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4.
If all the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic
permutations of 0, 1 and 2 are:
012 021 102 120 201 210
What ... |
f1332a18ae7a5e0934727c1b683f76d335d1198c | rvrheenen/OpenKattis | /Python/gamerank/gamerank.py | 736 | 3.828125 | 4 | def stars_for_rank(rank):
if rank >= 21:
return 2
if rank >= 16:
return 3
if rank >= 11:
return 4
return 5
rank = 25
stars = 0
streak = 0
record = list(input())
for game in record:
if rank == 0:
break
if game == "W":
streak += 1
stars += (2 if str... |
3a679b66696f92234009fa4d3a3cc2c3b869ab84 | jgartsu12/my_python_learning | /python_methods_functions/combine_args.py | 864 | 3.96875 | 4 | # How to Combine All Argument Types in a Single Python Function
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def greeting(time_of_day, *args, **kwargs): # args will be username
print(f"Hi {' '.join(args)}, I hope you are having a great {time_of_day}")
if kwargs:
print('Your tasks for day are:')
f... |
3f8c47d55905dcc5fb9daef459eec9cae06bedac | tonyxuxuxu/tonyxuxuxu.github.io | /leetcode_practice/shell_sort.py | 388 | 3.59375 | 4 | def shell_sort(collection):
length = len(collection)
gap = int(length/2)
while gap > 0:
for i in range(gap, length):
j = i
while j >= gap and collection[j-gap] > collection[j]:
collection[j-gap], collection[j] = collection[j], collection[j-gap]
j ... |
b30be76613b6becd86a21d67faa13c44687fcba2 | DayChan/lc | /Pythoncode/42.接雨水.py | 785 | 3.5625 | 4 | class Solution(object):
"""
https://leetcode-cn.com/problems/trapping-rain-water/solution/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-by-w-8/
"""
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
left_max = {}
right_max = {}
... |
3d0102fef6868a1e1726eb52fb6478eb287a044f | Mela2014/lc_punch | /lc22_bk.py | 900 | 3.671875 | 4 | class Solution:
def generateParenthesis(self, n: int) -> List[str]:
rslt, m = [], 2*n
def backtracking(curr, left, right):
if left+right == m:
rslt.append(curr)
else:
if left < m -left:
backtracking(curr+"(", left + 1, right... |
63de744a3a03848e29b39a36033a8ad807578bb2 | arulkumarkandasamy/PythonNotes | /Programs/fibonacci.py | 402 | 4.03125 | 4 | def userInput():
number = int(input('Please enter the number between 1 - 40 to find out the fibonacci :'))
return number
def findFibonacci(number):
if number == 0:
return 0
elif number == 1:
return 1
else:
return findFibonacci(number - 1) + findFibonacci (number - 2)
def m... |
d8a6cec93b4a54bfe32b83237120b4cc6cc9f65e | ftonato/python-para-zumbis | /list-02/class-02-resolved-ftonato-ademilson-flores-tonato.py | 608 | 4.0625 | 4 | # -*- coding: UTF-8 -*-
# 2) Determine se um ano é bissexto.
# Tente dividir o ano por 4. Se o resto for diferente de 0, ou seja, se for indivisível por 4, ele não é bissexto.
# Se for divisível por 4, é preciso verificar se o ano acaba em 00 (zero duplo). Em caso negativo, o ano é bissexto.
# Se terminar em 00, é pre... |
2480e6bcb17f4507a535ad94979117ec0345977e | Kunal352000/python_adv | /arithemeticOperation.py | 225 | 3.78125 | 4 | print("hiii")
x=10
y="siva"
def add(a,b):
c=a+b
print(c)
add(4,5)
class test:
def sub(self,a,b):
self.a=a
self.b=b
print(self.a-self.b)
t1=test()
t1.sub(5,2)
print(__name__)
|
91f25aadb02705770ec7a093426b97888b56fb86 | juthikashetye/PythonProgrammingForBeginners | /Numbers/NumOperators.py | 653 | 3.90625 | 4 | sum = 1+2
difference = 100-1
product = 3*4
quotient = 8/2
power = 2**4
remainder = 3%2
print ('Sum: {}'.format(sum))
print ('Difference: {}'.format(difference))
print ('Product: {}'.format(product))
print ('Quotient: {}'.format(quotient))
print ('Power: {}'.format(power))
print ('Remainder: {}'.format(remainder))
print... |
ce92408de4bd565e57e0b5beb072e1a836062d3d | ProxiDoz/shoblabot | /devka_handler.py | 807 | 3.875 | 4 | # Function return true if all letters in message is 'a'
def is_message_has_only_a_char(message_text):
# print("check '" + message_text + "' for all A symbols") # debug log
if (len(message_text) == 0):
return False
for char in message_text.lower():
# latin and cyrillic chars
if char ... |
3c501d44f4743fc373a9ca1db4a80455799fd932 | Govindvr/Tic-Tac-Toe | /tictactoe.py | 4,797 | 3.8125 | 4 | value = [' 'for i in range(9)] #List in which the input from both human and computer is stored
markp = "" #Stores the mark of the player
markc = "" #Stores the mark of the computer
def instructions(): #To display intruction a... |
4de450b190ac90e31082bbe6940f07d96bcc60a7 | SACHSTech/ics2o-livehack1-practice-Kyle-Lue | /windchill.py | 368 | 4.40625 | 4 | temperature = float(input("Enter the temperature in celcius: "))
windspeed = float(input("Enter the windspeed (km/h): "))
# compute windchill
windchill = 13.12 + (0.6215*temperature) - (11.37 * windspeed**0.16) + (0.3965 * temperature* windspeed**0.16)
# output windchill
print("With the windchill factor, it feels lik... |
a160d20df88278f4a2ec5b81add76d8a3d71dbed | Jackielo/DT211C-Cloud-Computing | /lab3/lab2II.py | 145 | 4 | 4 | word_input = input('Enter the word: ')
word_input = word_input.lower()
if(word_input == word_input[::-1]):
print("True")
else:
print("False") |
461b50240450c851a8e8dbd42f086a7fc7060fc8 | thamudi/maqsam | /Task 1/sudoku.py | 4,260 | 3.71875 | 4 | board = [
[7,8,0,4,0,0,1,2,0],
[6,0,0,0,7,5,0,0,9],
[0,0,0,6,0,1,0,7,8],
[0,0,7,0,4,0,2,6,0],
[0,0,1,0,5,0,9,3,0],
[9,0,4,0,6,0,0,0,5],
[0,7,0,3,0,0,0,1,2],
[1,2,0,0,0,7,4,0,0],
[0,4,9,2,0,6,0,0,7]
]
board_two = [
[3,0,6,5,0,8,4,0,0],
[5,2,0,0,0,0,0,0,0],
... |
870dbf0d2c19675ac1bb5ae7c63afba0f3046231 | Polin-Tsenova/Python-Fundamentals | /Palindrome_strings.py | 306 | 4.03125 | 4 | words = input().split()
palindrome = input()
def is_palindrome(word):
return word == word[::-1]
palindrome_words = [word for word in words if is_palindrome(word)]
print(palindrome_words)
palindrome_count =palindrome_words.count(palindrome)
print(f"Found palindrome {palindrome_count} times") |
a3ed4afb738a02d139f2c15f2a1f5868518110be | bgriffen/heteromotility | /heteromotility/hmtools.py | 9,644 | 3.53125 | 4 | '''
Tools for manipulating data structures.
TODO : refactor and replace with standard `pandas` implementations.
'''
from __future__ import print_function, division
import numpy as np
def dict2array(d):
'''
Merges a dict of lists into a list of lists with the same order.
Parameters
----------
d : d... |
3fe2b90f4b3cc87b4ba4a7948544d3bf63bf7706 | bitromortac/lnregtest | /lnregtest/lib/graph_testing.py | 3,077 | 3.546875 | 4 | """
Module can be used to check if graphs are defined in the correct convention.
"""
from typing import Dict
def graph_test(nodes):
"""
Tests if a graph was defined in a certain convention.
:param nodes: nodes definition
:type nodes: dict
"""
channel_numbers = sorted(get_channel_numbers(node... |
75c78bfec3aa3f2925c3ea95d0ecbeb64394e6c1 | endreujhelyi/endreujhelyi | /week-04/day-3/11b.py | 303 | 3.765625 | 4 | from tkinter import *
top = Tk()
size = 300
canvas = Canvas(top, bg="#1ce", height=size, width=size)
def square_drawer(a, b, color):
canvas.create_rectangle(a, a, a+b, a+b, fill=color)
j = 10
for i in range(10, 61, 10):
square_drawer(j, i, 'purple')
j += i
canvas.pack()
top.mainloop()
|
e14dc733a61f4654b8781e98d57e00a177e65bbb | vanshikasanghi/dv.pset | /0086 Binomial Expansion/binomialEx.py | 886 | 3.71875 | 4 | #getting the expanion
elements = [1]
n = int(input("Input : "))
for x in range(0,n) :
tripattern = []
tripattern.append(1) #starting term
for i in range(0,len(elements)-1) :
tripattern.append(elements[i]+elements[i+1])
tripattern.append(1) #ending term
elements = tripattern #storing the value of the sequenc... |
ea97e6e173fcf6e36d9467a7ea042dd3c3647e54 | joshsizer/free_code_camp | /algorithms/pairwise/pairwise.py | 2,260 | 4.1875 | 4 | """
Created on Mon May 3 2021
Copyright (c) 2021 - Joshua Sizer
This code is licensed under MIT license (see
LICENSE for details)
"""
def pairwise(arr, arg):
"""Get the sum of all index pairs, where
the values at the index pairs add up to arg.
For example, pairwise([1, 4, 2, 3, 0, 5], 7)
finds the in... |
2ccb674a1c3794bf954b043eaad6549595bd2041 | Rwothoromo/hashcode | /2020/slice_practice/slice2.py | 1,565 | 3.625 | 4 | import sys
def knapsack(items, capacity):
selected_pizzas = []
possible_count = 0
for (index, item) in enumerate(items):
if not selected_pizzas:
possible_count += item
selected_pizzas.append((index, item))
elif item != selected_pizzas[-1]:
possible_cou... |
60295b7d437d3a45209ac121d33568891e345d33 | fqingyu/Leetcode | /Q10.py | 992 | 3.65625 | 4 | class Solution:
def isMatch(self, s: str, p: str) -> bool:
print("str:{}, pattern:{}".format(s, p))
if not p:
return not s
elif p:
if len(p) >= 2 and p[1] == '*':
# if not self.isMatch(s, p[2:]):
# if s[1:] and s[1] == s[0]:
... |
a04438ba3ee180ee1c9b7065c39ed460f4f58644 | shalakatakale/Python_leetcode | /Leet_Code/1TwoSum.py | 1,109 | 3.71875 | 4 | '''1. Two Sum - Array, Hash table (dictionary) '''
class Solution():
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
store = {} # this dictionary contains complement value of numbers in ... |
8b8bba10fee596e1c84fba15de610f3f3317e1c5 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/224/users/4351/codes/1811_2563.py | 262 | 3.609375 | 4 | from numpy import*
mf=array(eval(input("vetor de notas finais: ")))
while (size(mf)>1):
i=0
apr=0
for v in mf:
if (mf[i]>=5 and mf[i]<7):
apr= apr + 1
i= i + 1
else:
i = i + 1
print(apr)
mf=array(eval(input("vetor de notas finais: ")))
|
7a76aba9b677523c886be2f3b79173299fe91fbf | Planet-KIM/planet_teams | /except/raise1.py | 450 | 3.734375 | 4 | def raisetest():
try:
integer = int(input('2의 배수를 입력하세요 : '))
if (integer % 2) != 0:
raise Exception('2의 배수가 아닙니다.')
print(integer)
except Exception as e:
print('raisetest 함수에서 예외가 발생했습니다.', e)
raise
try:
raisetest()
except Exception as e:
... |
37c52333ae70d752b926a939fc018b1d4e49e5e4 | gorilik324/ctax | /src/ColumnReader.py | 3,975 | 3.515625 | 4 | import csv
import re
from src.Error import Error
class column_reader:
"""
Returns an iterable reader for the specified file.
:param: section configuration section with information about the file such as delimiter, column infos, etc.
"""
def __init__(self, configuration, filename):
self._... |
90a87d4777d3d737afa64056e527cc9d86d2e8e9 | ramyasutraye/Python-Programming-3 | /begginners/oddoreven.py | 117 | 3.625 | 4 | a=int(input())
if(a>=1 and a<=100000):
if(a%2==0):
print 'even'
else:
print 'odd'
else:
print 'invalid value'
|
34912d7e4a2af598a8ef549dcfd6cac7a8bf4180 | mikey-manma/mikey-manma | /1-8d.py | 296 | 3.609375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[2]:
s=input()
p=input()
s+=s
ans="No"
for i in range(len(s)//2):
if(s[i]==p[0]):
for j in range(len(p)):
if(s[i+j]!=p[j]):
break
if(j==len(p)-1):
ans="Yes"
print(ans)
# In[ ]:
|
14c64a73dcf9f628d5a0ef3340fc0caeb264dbc6 | Goku-kun/1000-ways-to-print-hello-world-in-python | /using-binary.py | 66 | 3.5 | 4 | str = "hello world"
print(" ".join(f"{ord(i):08b}" for i in str))
|
4281824d2033ab8aed92f1faaed4a70fa4e82d09 | hyang012/leetcode-algorithms-questions | /014. Longest Common Prefix/Longest_Common_Prefix.py | 1,183 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Leetcode 14. Longest Common Prefix
Write a function to find the longest common prefix string amongst
an array of strings.
If there is no common prefix, return an empty string "".
Note:
All given inputs are in lowercase letters a-z.
"""
# Horizontal scanning
def lon... |
e94cf2cce5b6c19ebc79715b587d1e4edf8739aa | IzLeandro/Tarea-Programada-N1-Zoo | /function.py | 3,761 | 3.734375 | 4 | #Elaborado por: Leandro Camacho Aguilar y Celina Madrigal Murillo
#Fecha de Creación: 31/10/2020 2:40pm
#Fecha de última Modificación: XX/XX/XX X:XXpm
#Versión: 3.9.0
#Importaciones
from IntegrationWikipedia import getInfo
import random
import time
import re
#Definición de funciones
def cargarInfoWiki(animales):
... |
b7ea5a26f902bfa58db4b2015ba7db3b686e807d | zmlabe/IceVarFigs | /Scripts/SeaIce/read_SeaIceThick_PIOMAS.py | 2,924 | 3.921875 | 4 | """
Script reads PIOMAS binary files stored on remote server through
present year. Second function calculates climatological average over
a given period.
Notes
-----
Source : http://psc.apl.washington.edu/zhang/IDAO/data_piomas.html
Author : Zachary Labe
Date : 7 September 2016
Usage
-----
re... |
b7ff3fb95adb33ee351861d6e7a61f0200ee3e39 | robertopedroso/euler | /python/problem5.py | 421 | 3.78125 | 4 | from itertools import count
def evenlydivisible(n):
"""Returns whether n is divisible by [1, 20]"""
drange = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20] # don't call xrange every time
for i in drange:
if n % i != 0: return False
return True
if __name__ == "__main__":
for i in count(20, 20): ... |
4705d6a0c9fb4122e944c25911d083ed78942c64 | rksaxena/leetcode_solutions | /ones_and_zeros.py | 1,419 | 3.78125 | 4 |
__author__ = Rohit Kamal Saxena
__email__ = rohit_kamal2003@yahoo.com
"""
In the computer world, use restricted resource you have to generate maximum benefit is what we always want to pursue.
For now, suppose you are a dominator of m 0s and n 1s respectively. On the other hand, there is an array with strings consis... |
7ed8dc438342f221c688a2311e08b81f9c13ae44 | andrewhere/MazeGame | /aStar.py | 2,758 | 3.609375 | 4 | # aStar.py
# Implementation of the A* search algorithm using
# Manhatten distance as heuristc fucntion
from utility import *
import time
def a_star_search(maze, start, goal):
neighbors = [(0, 1), (0, -1), (1, 0), (-1, 0)]
"(1, 1), (1, -1), (-1, 1), (-1, -1)] " # quick neighbors fiding offset
close_list... |
c8e2b4950bcb06b24202b488c6ff52a373c53684 | evan886/python | /allpynotes4turtle/eg/ri.py | 159 | 3.859375 | 4 | #-*- coding:utf-8 -*-
file_name = input('输入打开的文件名:')
f = open(file_name)
print('文件的内容是:')
for each_line in f:
print(each_line)
|
b45bd68232cae3bc393fffdc5ae9b72a165461ac | nkmashaev/declared_env | /declared_env/_prefixable.py | 264 | 3.53125 | 4 | """Abstract class with prefix attribute."""
from abc import ABCMeta, abstractmethod
class Prefixable(metaclass=ABCMeta):
"""Abstract class with prefix attribute."""
@property
@abstractmethod
def prefix(self) -> str:
"""Prefix string."""
|
226e06879416c5c58d42fc2d1574a5bdabd06ace | dong-c-git/WSGIServer | /template/programe_celue.py | 867 | 3.65625 | 4 | #coding:utf-8
from abc import ABC,abstractmethod
class Strategy(ABC):
@abstractmethod
def algorithm_interface(self,context):
pass
class ConcreteStrategyA():
def algorithm_interface(self,context):
print("ConcreteStrategyA")
class ConcreteStrategyB(Strategy):
def algorithm_interface(sel... |
dba97bad9c2359dcaadb611e9b00bf3227494a96 | MrHamdulay/csc3-capstone | /examples/data/Assignment_8/nxmgoo002/question1.py | 730 | 4.0625 | 4 | '''this programm checks the palindrome
Nxumalo Goodman
09 May 2014'''
#this function reverses the string
def rev(w):
#base case
if w == '':
return w #returns nothing if there is nothing in the string
#recursive step
else:
return rev(w[1:]) + w[0]
#this function checks if... |
458003d33ed54e5ce951e7fa29920a2958f715b5 | dgpshiva/PythonScripts | /Matrix_BFS.py | 1,648 | 3.609375 | 4 | def findPath(grid, rows, cols):
queue = []
visited = [[0 for x in range(0, cols)] for y in range(0, rows)]
start = (0, 0, 0)
queue.append(start)
visited[0][0] = 1
while queue:
current = queue.pop()
if grid[current[0]][current[1]] == 9:
return current[2]
els... |
fe2ba6fee0be809ba576eb07e75cd6aeefe19fb2 | rags/playground | /py/exp/common/nodes.py | 640 | 3.5625 | 4 | class Operator:
def __init__(self,lhs,rhs):
self.lhs = lhs
self.rhs = rhs
class AddOperator(Operator):
def visit(self,visitor):
visitor.visitAddOperator(self)
class SubstractOperator(Operator):
def visit(self,visitor):
visitor.visitSubstractOperator(self)
class MultiplyOperator(Operator):... |
41d652aa5a9f6266fa412374375f84e27d3ecb83 | FrankMwesigwa/lessons | /python/add.py | 352 | 3.953125 | 4 |
while 1:
print('Enter a number:')
s = input()
s = int(s)
print ("hello")
if s in range(1, 7):
if s == 1:
print ('Go to ...1')
elif s == 2:
print ('Go to ...2')
elif s == 3:
print ('Go to ...3')
else:
print('party time'... |
bc15206e42dafa502d3d71182900133a11639791 | thehimel/data-structures-and-algorithms-udacity | /m03c02-sorting-algorithms/i15e00_sort_012.py | 2,155 | 4.03125 | 4 | """
Problem Statement
Write a function that takes an input array (or Python list) consisting of
only 0s, 1s, and 2s, and sorts that array in a single traversal.
Input: [0, 0, 2, 2, 2, 1, 1, 1, 2, 0, 2]
Output: [0, 0, 0, 1, 1, 1, 2, 2, 2, 2, 2]
Note: If we can get the function to put the 0s and 2s in the correct posit... |
ea686d384a87e932b95e5289bb8d38cb5044bcdb | rbryan21/ParallelComputing | /Module4/example.py | 333 | 3.859375 | 4 | # Monte Carlo Calculation of Pi
from random import *
from math import sqrt
def main():
"Monte Carlo Calculation of Pi"
inside=0
n=1000
for i in range(0, n):
x=random()
y=random()
if sqrt(x*x+y*y)<=1:
inside+=1
pi=4*inside/n
print(pi)
if __name__ == "__main__":
print(main.__doc_... |
992c691839cfb3fe2867637db0aba4e21eaee88b | coolsnake/JupyterNotebook | /new_algs/Number+theoretic+algorithms/Euclidean+algorithm/euklides.py | 650 | 3.8125 | 4 | """
Algorytm Euklidesa
___ _ _ _ _
| __| _| |_| (_)__| |___ ___ _ __ _ _
| _| || | / / | / _` / -_|_-< _ | '_ \ || |
|___\_,_|_\_\_|_\__,_\___/__/ (_) | .__/\_, |
|_| |__/
Z dedykacja dla Pani Profesor Stajno :)
"""
a = int(r... |
fc78c8787652766fe6aedad0f9c14214b3865397 | atyndall/cits4211 | /tools/helper.py | 1,143 | 3.703125 | 4 | import collections
UNICODE = True # Unicode support is present in system
# The print_multi_board function prints out a representation of the [0..inf]
# 2D-array as a set of HEIGHT*WIDTH capital letters (or # if nothing is there).
def print_multi_board(a):
for row in a:
print(''.join(['#' if e == 0 else ch... |
054fdd5f28742f4b4534d04a9a30ae14d19ba418 | Silocean/Codewars | /7ku_excel_sheet_column_nubmers.py | 447 | 3.890625 | 4 | '''
Description:
Write a function
titleToNumber(title) or title_to_number(title) or titleToNb title ...
(depending on the language)
that given a column title as it appears in an Excel sheet, returns its corresponding column number. All column titles will be uppercase.
'''
def title_to_number(title):
#your code ... |
2b449ecd449756a03745f4d6f3876702b01ff77b | mertzjl91/PythonProjects | /Guessthenumber.py | 601 | 4.125 | 4 | import random
n=random.randint(1,20)
guess = int(input("Enter a number 1 to 20:"))
while n != "guess":
print()
if guess < n:
print("Guess is too low, try again!")
guess = int(input("Enter a number 1 to 20, better get it right this time!"))
elif guess > n:
print("Guess is... |
01e9a37af23714762344273e91873693ccd157db | mehtajaghvi/ProjectEuler | /Programs/25_1000Fib.py | 596 | 3.59375 | 4 |
################################
#Project Euler
#Problem Statement 25
################################
import time
import math
#some big number
maxNumber=100000000
#max length of the 1000-digit number
maxLen=1000
def thou_FibNum():
secondLast=1
last=2
for n in range(1,maxNumber):
next=secondLast+last
se... |
33962b6bcc72e025dd1658c180e104d867d56ba5 | MohammadRezaG/Loop-Structure | /Loop Structure/Factorial.py | 73 | 3.734375 | 4 | i = int(input())
fact=1
for x in range(1,i+1):
fact= fact*x
print(fact)
|
c0581490e44dd2f82d87643719bdf1634bc3e9d2 | browncoder98/Python-Projects | /scratches/Selection Sort.py | 326 | 3.828125 | 4 | # Selection Sort:
def sort (nums):
for i in range(5):
minpos = i
for j in range (i,6):
if nums[j] < nums [minpos]:
minpos = j
temp = nums[i]
nums[i] = nums[minpos]
nums[minpos]= temp
print(nums)
nums = [2,9,6,8,7,10]
sort(nums)
print... |
1dda821f1342a290e60de30988a32358f2fb28c8 | wlinco/realpython | /dict.py | 345 | 4.1875 | 4 | my_dict = {"luke":"5/24/19","obiwan":"9/3/09","vader":"9/1/10"}
if "yoda" not in my_dict:
my_dict["yoda"] = "2/2/2"
if "vader" not in my_dict:
my_dict["vader"] = "3/3/3"
for name in my_dict:
print name + " " + my_dict[name]
del(my_dict["vader"])
print my_dict
other_dict = dict([("luke","1/1/1"), ("vader", "2/2... |
3f659e724de8713ab0f610c967d68364fcb27d6d | jasonmcalpin/worldgen | /template/dice.py | 1,002 | 3.921875 | 4 | import random
'''
usage:
import dice
roll = dice.roll(1,6,1,0)
roll_2d6 = dice.roll(1,6,2,0)
help(dice.roll)
help(dice.flux)
Notes:
Needs tests.
Can add shortcuts like dice.roll_2d6 or whatever.
'''
def roll(die_min=1, die_max=6, die_count=1, modifier=0):
'''
(int, int, int, int) -... |
63c91cd2ce45d0787004c72a13fa6fcb8d3bbc54 | marinasmonteiro/Subjet5 | /Exercice AND andOR.py | 630 | 4.0625 | 4 | a=input("Which language are you using?")
if a=="Phython" or a=="JavaScript":
print("It is a good course")
else:
print("take thinking and creating with Code courses :)")
b=input("which language are you using?")
if b=="Phython":
print("this is Thinking and Creating with Code courses!")
elif b=="JavaScript... |
95d32fa17849e83cf630ff2648104f55d5f9b991 | claraqqqq/l_e_e_t | /20_valid_parentheses.py | 657 | 4.03125 | 4 | # Valid Parentheses
'''
Given a string containing just the characters '(', ')','{',
'}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]
{}" are all valid but "(]" and "([)]" are not.
'''
class Solution:
# @param {string} s
# @return {boolean}... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.