blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
a496f5267998e3e4e12082da9268a2b7f3e3c6e8 | deepakorantak/Python | /Datacamp/DataAnalyst/Course3 - Python Fuctions/lambda.py | 1,227 | 4.40625 | 4 | # Define echo_word as a lambda function: echo_word
echo_word = (lambda x,y:x*y)
# Call echo_word: result
result = echo_word('hey',5)
# Print result
print(result)
# Create a list of strings: spells
spells = ["protego", "accio", "expecto patronum", "legilimens"]
# Use map() to apply a lambda function over spells: shout... |
434eb140d800d5442a0826556bbfc9ea17525ff2 | yuyifanyyf/pythonExercise | /CountofRangeSum.py | 1,395 | 3.609375 | 4 | class Solution:
def mergeSort(self, nums, helper, start, end, lower, upper):
res = 0
if end - start > 1:
mid = (end + start) // 2
res += self.mergeSort(helper, nums, start, mid, lower, upper)
res += self.mergeSort(helper, nums, mid, end, lower, upper)
... |
73dd139a979ddd75b62adb45b8ac513cc3261d45 | yuyifanyyf/pythonExercise | /Add.py | 351 | 3.90625 | 4 | # -*- coding:utf-8 -*-
class Solution:
def Add(self, num1, num2):
# write code here
while True:
Sum = num1 ^ num2
carry = num1 & num2
if not carry:
return Sum
num1 = Sum
num2 = carry
if __name__ == "__main__":
s = Soluti... |
1cc029c018a4a9f4693ccd14a77577a4e30cbb2b | pranaykhurana/Hackerrank | /Python/itertools_product.py | 333 | 3.546875 | 4 | from itertools import product
if __name__ == '__main__':
lst1 = input()
lst2 = input()
lst1 = lst1.split(" ")
lst2 = lst2.split(" ")
lst1 = ([int(item1) for item1 in lst1])
lst2 = ([int(item2) for item2 in lst2])
prodLst = list(product(lst1, lst2))
for x in prodLst:
prin... |
dc38c0d40de612514d5abf747d528ee4e9b48a80 | pranaykhurana/Hackerrank | /Python/Calendar Module.py | 224 | 4.125 | 4 | import calendar
if __name__ == '__main__':
date = input().split(" ")
day = calendar.weekday(int(date[2]), int(date[0]), int(date[1]))
day_name_list = list(calendar.day_name)
print(day_name_list[day].upper()) |
bf4404a5d2aa942b4798081a39d8ac1d49a8a526 | theideasmith/learn-dynamsys | /predator.py | 1,123 | 3.53125 | 4 | from numpy import *
from matplotlib.pyplot import *
from scipy.integrate import odeint
def LotkaVolterra(state,t):
x = state[0]
y = state[1]
alpha = 0.1
beta = 0.1
sigma = 0.1
gamma = 0.1
xd = x*(alpha - beta*y)
yd = -y*(gamma - sigma*x)
return [xd,yd]
t = arange(0,500,1)
state0 = [0.5,0.5]
state =... |
291fc19979065196d27157fde72c992ca2679898 | stefanicarol/delivery | /restaurante.py | 2,442 | 3.6875 | 4 | class Pessoa:
nome = ''
email = ''
class Cliente(Pessoa):
telefone = ''
endereco = ''
def salvarCliente(self):
arquivo = open('cliente.txt', 'a')
arquivo.write('Nome: {}, E-mail: {}, Telefone: {}, Endereco: {} '
'\n'.format(self.nome, self.email, self.telefon... |
ca59004ad2f57bb1fb8e12e54cffb1172af4fef2 | shahamish150294/LeetCode | /IntersectionTwoLL.py | 1,467 | 3.8125 | 4 | #https://leetcode.com/problems/intersection-of-two-linked-lists
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
getIntersectionNode ... |
7e825d7bfc17b630d7f42d97e2ab2a73d555961b | shahamish150294/LeetCode | /GOG_ReverseGroupLL.py | 1,166 | 4.0625 | 4 | #http://www.geeksforgeeks.org/reverse-a-list-in-groups-of-given-size/
class ListNode(object):
def __init__(self, val, n = None):
self.val = val
self.next = n
class LinkedList(object):
def __init__(self, root=None):
self.root = root
self.size = 0
def add(self, data):
... |
0605d26bc8d4ceac6ba30ce41faebe384f417e1a | shahamish150294/LeetCode | /BSTkthSmallest.py | 1,269 | 3.671875 | 4 | #https://leetcode.com/problems/kth-smallest-element-in-a-bst/
found = False
val = 0
rank = 0
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def addRight(self, node):
self.right = node
def addLeft(self, node):
self.l... |
75aa8b6970399cb3196b360e5930a7b9b952b677 | grepole121/Log | /createKey.py | 1,964 | 3.65625 | 4 | from PyQt5.QtWidgets import QDialog, \
QLineEdit, \
QPushButton, \
QVBoxLayout, \
QLabel, \
QMessageBox
from pass_key_gen import gen_key
import os.path
import config
from cryptography.fernet import Fernet
# This QDialog will open at launch if key.key doesn't exist and the user must create it
cla... |
a31c3990a1d5ab99205ce9aad21cb2bd803be4c9 | MaorEl/sendWhatsAppWithoutSavingNumber | /send_whatsapp_without_saving_number.py | 2,558 | 3.546875 | 4 | from tkinter import *
import webbrowser
url_prefix = 'https://web.whatsapp.com/send?phone=972'
chrome_path = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'
def change_format_of_phone(phone_number):
return ''.join(phone_number[1:].split('-'))
def open_chrome(phone_number, event=None):
phon... |
b91ef8f96da5324d41be40e26b19697d127df5ca | peguin40/cpy5p1 | /q6_find_ascii_char.py | 443 | 4.34375 | 4 | #q6_find_ascii_char.py
#displays character corresponding to ASCII value inputted
#input variable
ascii_value = int(input("Please enter an integer between 0 and 127:"))
#check validity
while ascii_value<0 or ascii_value>127:
ascii_value = int(input("ERROR: Integer not between 0 and 127 \n Please enter an integer... |
a5653904c098ebd308d82953fc446b31a4df9f5e | sanjeevkumar4574/pythonbootcamp | /blackjack/number_guess.py | 902 | 3.90625 | 4 | import random
from art import logo4
HARD_LEVEL_TURNS = 5
EASY_LEVEL_TURNS = 10
def check_guess(number,guess):
if number>guess:
print('Too low')
elif number<guess:
print('Too high')
else:
print(f'You have got correct {guess} number')
def difficultly():
level = input('choose deff... |
250d2332e11196d692b9bb40b14dcfb9d54af950 | Nonac/Python_practise | /Pawn Brotherhood.py | 717 | 3.828125 | 4 | def safe_pawns(pawns):
pawns_indexes = set()
for p in pawns:
row = int(p[1]) - 1
col = ord(p[0]) - 97
pawns_indexes.add((row, col))
count = 0
for row, col in pawns_indexes:
is_safe = ((row - 1, col - 1) in pawns_indexes) or ((row - 1, col + 1) in pawns_indexes)
... |
cf62b186bfdcf1c8effe838239cd8346c574ea26 | Nonac/Python_practise | /Number Base.py | 915 | 3.890625 | 4 | def checkio(str_number, radix):
text = str(str_number)
import re
patten = re.compile(r'[0-9A-Z]')
arry = patten.findall(text)
i = 0
res = 0
for each in range(len(arry)-1,-1,-1):
if arry[i].isalpha():
if ord(arry[i]) - 55 >= radix: return -1
res = (ord(arry[i])... |
76e33a0d0993e7fee76037cba619d1906c136dc2 | nikita-a-tk/youtube_downloader | /dowloader.py | 522 | 3.671875 | 4 | from pytube import YouTube
print("Welcome to YouTube Downloader app!")
#video_url = input("Which video you want to download?\n")
video_url = "https://www.youtube.com/watch?v=M0Ypzm7pVw4" # short video for testing
video = YouTube(video_url)
print(video.title)
streams = video.streams.all()
i = 1
for stream in streams:
p... |
985d11b7d2edecaa31769c0e19964788a5a45dee | hunthunt2010/CompilersGroup2 | /ToTheAST/hugetesttgen.py | 338 | 3.578125 | 4 | #!/usr/bin/env python3
import sys
if len(sys.argv) < 2:
print("Usage %s <NumberofRegisters>" % sys.argv[0])
exit(-1)
def expressiongen(num):
if num == 1:
return "(1+1)"
else:
return "(" + expressiongen(num-1) + "+" + expressiongen(num-1) + ")"
print("int z = " + expressiongen(int(sys... |
af9dd3b010818764da3d913ad7e7a1a65a8dda01 | MauroAquino/Python_Practica3 | /etl.py | 16,519 | 3.5625 | 4 | import csv
import time
from collections import Counter
class Etl:
@classmethod
def load_file(cls, file_name):
"""
Esta funcion crea un set con las peliculas a fin de eliminar
registros duplicados, luego carga el csv en una lista de diccionarios
:param file_na... |
dcf80cc3f157b2c727c5e9f0ca1b7a3dcf064028 | incrl/portfolio | /CS355 Python Curriculum/Lab4/Old/Shapes.py | 1,635 | 4.03125 | 4 |
class Point:
def __init__(self,x,y):
self.x = x
self.y = y
#Abstract Class
class Shape:
def pointInShape(self, pt, tolerance):
pass
def getWidth(self):
pass
def getHeight(self):
pass
def worldToObject(self, pt):
#To be implemented
return None
class Rect(Shape):
def __init__(self, co... |
e859798d72bfbc7653b2f70d01a6a2e5bfbc8a6d | devMEremenko/Coding-Challenges | /Python/LeetCode/!860. Lemonade Change.py | 624 | 3.625 | 4 | # https://leetcode.com/problems/lemonade-change/submissions/
class Solution:
def lemonadeChange(self, bills: [int]) -> bool:
# $5 -> no
# $10 -> 5
# $20 -> 5,10 (preferred) or 5,5,5
f = t = 0
for item in bills:
if item == 5:
f += 1
... |
0a427e257c79dabe8ead41c507391aee105a46c1 | devMEremenko/Coding-Challenges | /Python/LeetCode/20. Valid Parentheses.py | 1,240 | 3.515625 | 4 | # https://leetcode.com/problems/valid-parentheses/
class Solution:
# ---- In-place Solution
def isMatch(self, s1: str, s2: str) -> bool:
if s1 == "(" and s2 == ")": return True
if s1 == "[" and s2 == "]": return True
if s1 == "{" and s2 == "}": return True
return False
... |
7ac4fff82ea6a04ea0c7d375c8d423b18f1bb542 | devMEremenko/Coding-Challenges | /Python/LeetCode/876. Middle of the Linked List.py | 938 | 3.828125 | 4 | # https://leetcode.com/problems/middle-of-the-linked-list/
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def middleNode(self, head: ListNode) -> ListNode:
# return self.solve_using_fast... |
e06e2b9096299eb5cb720faeee7c6cac70fa0683 | devMEremenko/Coding-Challenges | /Python/LeetCode/58. Length of Last Word.py | 789 | 3.53125 | 4 | # https://leetcode.com/problems/length-of-last-word/submissions/
class Solution:
def lengthOfLastWord(self, s: str) -> int:
# return self.solution1(s)
return self.solution2(s)
def solution1(self, s):
res = 0
foundCharacter = False
for char in reversed(s):
... |
68d791c7782f9b890c7cbae130f977735052136c | siddhant230/Dynamic-Programming | /fibo_memoization.py | 154 | 3.609375 | 4 | fib={}
def fibo(n):
if n==1:
return 1
if n not in fib:
if n<=1:
fib[n]=n
else:
fib[n]=fibo(n-1)+fibo(n-2)
return (fib[n])
print(fibo(5))
|
e438b4d67143506ca7fec64222fa22b755f98dd5 | ramimanna/algorithmic-toolbox | /algorithms/bfs.py | 2,536 | 3.828125 | 4 | class Edge:
def __init__(self,node1,node2):
self.node1 = node1
self.node2 = node2
class Graph:
def __init__(self,vertices = set(),edges = set()):
self.vertices = vertices
self.edges = edges
def add_vertex(self,vertex):
return self.vertices.add(vertex)
def remove_... |
77f124f865004a8a8850fa2664dddfd80065bd6c | Mettas/DropToken | /src/lib/board_column.py | 1,441 | 3.546875 | 4 | from game_token import GameToken
from exception import InvalidMoveException
class BoardColumn:
"""Represents a single column in a DropTokenGame."""
def __init__(self, position, height):
"""Arguments:
position -- int column number where this BoardColumn is located on the board
height --... |
030d84a7f611c4581f27cb18d71a9e5a6b5fbb58 | alexantonio308/URI-Python-Iniciante | /1002.py | 71 | 3.5625 | 4 | raio=float(input())
n=3.14159
area=(n*raio**2)
print("A="+"%.4f"%area)
|
d850b8ebbf75e8a5d33ffd55e6d45bde852ea3cc | Genskill2/02-bootcamp-estimate-pi-nithinmanoj10 | /estimate.py | 2,337 | 3.703125 | 4 | import math
import unittest
import random
# function to calculate the Wallis product estimate of Pi
def wallis(n):
PI = 2.0;
leftProduct = 0.0;
rightProduct = 0.0;
for x in range(1,n):
leftProduct = (2.0 * x)/((2.0 * x)-1.0);
rightProduct = (2.0 * x)/((2.0 * x)+1.0);
PI *= (left... |
0e9fc1fa07025aeec9bc2cd7059ab95b30b07d9a | eyaylali/practice-problems | /primes-python.py | 250 | 4.125 | 4 | #Write a method, is_prime?, that takes a number num and returns true if it is prime and false otherwise.
def is_prime(n):
for num in range(2,n):
if n % num == 0:
return False
return True
print is_prime(4)
print is_prime(15)
print is_prime(7) |
475e6b6c3ec0bd3be6021b47aad42dab7a60354a | amaeva911/learn_python_14 | /week 1/lesson1_2_class_work/for2.py | 534 | 3.9375 | 4 | import random
"""
Классное задание №1
Цикл for
Создать список из десяти целых чисел.
Вывести на экран каждое число, увеличенное на 1.
"""
def random_list():
Start = 0
Stop = 99
limit = 10
random_list = [random.randint(Start, Stop) for item in range(limit)]
print(random_list)
ret... |
efdb75e8cf318e45de0d9dd7701d2dd979378d9f | amaeva911/learn_python_14 | /week 1/lesson1_2_home_work/if2.py | 1,889 | 4.125 | 4 | """
Домашнее задание №1
Условный оператор: Сравнение строк
* Написать функцию, которая принимает на вход две строки
* Проверить, является ли то, что передано функции, строками.
Если нет - вернуть 0
* Если строки одинаковые, вернуть 1
* Если строки разные и первая длиннее, вернуть 2
* Если строки разные и вторая с... |
ea54f2c55e81c2cd91f7fba076e626331738a3ed | amaeva911/learn_python_14 | /week 1/lesson1_1/hello.py | 144 | 3.671875 | 4 | print("Привет мир! \nПривет программист!")
a = 2 + 2
b = 10 / 3
print("2 + 2 = " + str(a))
print("10/3 = " + str(b))
|
0861b98317c4208e4647f3fa73b399b0296dda6c | FernandoMarcon/learning_notes | /finances/Algorithmic Trading/stock_trading_with_python.py | 1,556 | 3.65625 | 4 | '''
Stock Trading with Python
source: Algorithmic Trading and Finance Models with Python, R, and Stata Essential Training (LinkedIn Course)
'''
import pandas as pd
pd.core.common.is_list_like = pd.api.types.is_list_like
from pandas_datareader import data
#### --------------- Data Retrieval --------------- ####
#--- Ya... |
9f321ffe930989bcd72dc0600e4be69567349813 | nomadlife/project-euler | /p057.py | 166 | 3.765625 | 4 | # p057 Square root convergents
n=3;d=2;loop=0;count=0
while loop<1000:
if len(str(n)) > len(str(d)):
count+=1
n,d = n+2*d,n+d
loop+=1
print(count) |
a4618e68a723fa2e31e27fcf99f0ca8bea4ea296 | nomadlife/project-euler | /p010_1.py | 594 | 3.78125 | 4 | # q010
# Summation of primes
# add user input
import sys
import time
start_time = time.time()
def is_prime(num):
if num == 1:
return False
loop = num**0.5
i = 2
while i <= loop:
if num % i == 0:
return False
i += 1
return True
loop = 2000... |
ca016e5b22d273d194a157062427511e99621402 | nomadlife/project-euler | /p004.py | 339 | 3.75 | 4 | # Q004 Largest palindrome product
# largest palindrome made from the product of two 3-digit numbers.
maxValue = 0
for i in range(900, 1000):
for j in range(900, 1000):
product = i*j
if str(product) == str(product)[::-1]:
if product > maxValue:
maxValue = product... |
6fef2fce39274ed6fbab55e37e3babacec3fbe95 | nomadlife/project-euler | /p003.py | 635 | 3.90625 | 4 | # Q003 largest prime factor
# What is the largest prime factor of the number 600851475143 ?
def is_prime(num):
if num == 1:
return False
loop = num**0.5
i = 2
while i <= loop:
if num % i == 0:
return False
i += 1
return True
number = 6008514751... |
b21265c41f1004f1e293d3c5faa3a3e9bd274a22 | ShresthaRajat/Python-billing-system | /Check.py | 2,576 | 4.46875 | 4 | # Ths module contains functions which loops until a valid value is entered
def yes_customer():
"""function to return Boolen value if y,yes,n and no is given as input """
print("Add new customer?")
while True:
input_yes_no = input("Enter yes to add new customer or no to exit program (y/n):")
if input_ye... |
80547a9c9e0e5eae8b2b4f61a31a2aef7893ffb8 | mcnic/algorithms | /testOrderedList.py | 9,115 | 3.75 | 4 | import unittest
from orderedList import OrderedList
class TestOrderedList(unittest.TestCase):
def test_clean(self):
orderedList = OrderedList(True)
self.assertEqual(orderedList.len(), 0)
orderedList.add(1)
self.assertEqual(orderedList.len(), 1)
orderedList.add(2)
s... |
dc25f48ce5fc977ec98366ced37a0922f21f3d8d | mcnic/algorithms | /polyndrome.py | 408 | 3.65625 | 4 | #from deque import Deque
from deque2 import Deque
class Polyndrome:
def check(self, str):
# fill
deque = Deque()
for ch in str:
deque.addTail(ch)
# check
iter = deque.size() // 2 # get middle
while iter > 0:
if deque.removeFront() != deq... |
8d6ec639cac91a9d410bbf690ea8adb2b5e73908 | cmulliss/gui_python | /challenges/class_method.py | 1,401 | 4.03125 | 4 | class ClassTest:
def instance_method(self):
print(f"Called instance_method of {self}")
# have called the instance_method 2 times, called that becuase you call it on a class instance. Creating on object of type ClasssTest, can also say creating an instance of ClassTest.
test = ClassTest()
test.instance_met... |
025898bd1283a583f74b2337cb0e7362b020bf44 | cmulliss/gui_python | /revision/magic_no.py | 529 | 3.640625 | 4 | number = 7
user_input = input("Enter 'y' if you would like to play.").lower()
if user_input == "y":
# all these following lines are within the above if statement, so following only run if first if is true
user_number = int(input("Guess the number: "))
if user_number == number:
print(f"Well done , ... |
8bf3495620e50ce9fe8fd65b4c67e9bb15f08611 | cmulliss/gui_python | /.vscode/apps/winfo_children.py | 1,709 | 3.875 | 4 | import tkinter as tk
import tkinter.font as font
from tkinter import ttk
root = tk.Tk()
root.title("Distance Converter")
font.nametofont("TkDefaultFont").configure(size=15)
metres_value = tk.StringVar()
feet_value = tk.StringVar(value="Feet shown here")
def calculate_feet(*args):
try:
metres = float(m... |
13058889f0a43d3d874f7d7183f44faaa257a334 | cmulliss/gui_python | /challenges/if_else.py | 454 | 4.21875 | 4 | n = int(input())
1 <= n >= 100
if (n % 2) == 1:
print("Weird")
elif (n % 2) == 0 and n >= 2 and n <= 5:
print("Not Weird")
elif (n % 2) == 0 and n >= 6 and n <= 20:
print("Weird")
elif (n % 2) == 0 and n > 20:
print("Not Weird")
# Python Program to Check if a Number is Odd or Even
# num = int(input("... |
33c8fb0780b2b2d58e6a94823cad5df9b59fd3dc | cmulliss/gui_python | /challenges/destruct.py | 381 | 3.875 | 4 | # x, y = 5, 11
student_attendance = {"Sue": 96, "Bob": 80, "Anne": 100}
print(list(student_attendance.items()))
# gives a list of tuples
# [('Sue', 96), ('Bob', 80), ('Anne', 100)]
for t in student_attendance.items():
print(t)
# destructured into students and grades:
for student, attendance in student_a... |
a9534971f28bc1a39eddeb81b112c85337d58b3a | cmulliss/gui_python | /revision/oop.py | 311 | 3.75 | 4 | # a dictionary
student = {"mame": "Rolf", "grades": (89, 90, 93, 78, 90)}
# a sequence
def average(sequence):
return sum(sequence) / len(sequence)
print(average(student["grades"]))
# awkward, better if could do:
# print(student.average())
# needs different code to be able to call the 'average' method
|
202a105ebddbd78b41ae4f143ac7d6ee7bac7479 | gpsevdiotis/CM1102-Easter-Date | /Form_Easter.py | 6,332 | 3.875 | 4 | #!/usr/bin/python3
import cgi, cgitb
form = cgi.FieldStorage()
y = int(form.getvalue('Year'))
formatmethod = form.getvalue("formatmethod")
#Code to calculate Easter Date
a=y%19
b=y//100
c=y%100
d=b//4
e=b%4
g=(8*b+13)//25
h=(19*a+b-d-g+15)%30
j=c//4
k=c%4
m=(a+11*h)//319
r=(2*e+2*j-k-h+m+32)%7
n=(h-m... |
6a06387551d1eb4dac06251adaef4dda43d96b7b | kennethshawfriedman/Project-Euler | /Solutions/004.py | 697 | 4.125 | 4 | #Problem
''' A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 x 99.
Find the largest palindrome made from the product of two 3-digit numbers. '''
#Answer
''' 906609 '''
#Code Written & Designed by Kenneth Friedman
#returns true if number... |
46aa04127a4af3b4a6204908e012c5342d84b2ea | HorseBackAI/PythonBlockchain | /8_除错和处理错误/8-debugging-handling-error-examples/debug.py | 142 | 3.953125 | 4 | def add(a, b):
return a + b
def divide(a, b):
return a / b
a = 10
b = 5
sum = add(a, b)
divided = divide(a , b)
print(sum, divided) |
87965c4a7d8319f24732c9d9eaf91daf719b310f | Majestik12/Majestik_test | /dz3/03_division.py | 634 | 3.953125 | 4 | # -*- coding: utf-8 -*-
# (цикл while)
# даны целые положительные числа a и b (a > b)
# Определить результат целочисленного деления a на b, с помощью цикла while,
# __НЕ__ используя стандартную операцию целочисленного деления (// и %)
# Формат вывода:
# Целочисленное деление ХХХ на YYY дает ZZZ
a, b = 179, 37
z = ... |
f43454b522e8d2e0a58867a84459d8eb4b0cc052 | jiangxiaoyong/python | /TwoSum/solution/TwoSum.py | 584 | 3.71875 | 4 | '''
Created on Aug 7, 2015
@author: jxy
'''
def twoSum(nums, target):
list = []
for val1 in nums:
val2 = target - val1
index1 = nums.index(val1)
if val2 in nums and nums.index(val2) > nums.index(val1):
index2 = nums.index(val2)
list.insert(0, index1)
... |
ab423fe02210c94b1d1c5193767dd7e9b4c3109c | TTyron/HomeWork | /第三周课堂练习--钟裕桐.py | 2,106 | 3.671875 | 4 | Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> def check():
name=input ('名字:')
age=int(input('年龄:'))
rs=print(f'{name}在',2018+(100-age),'年后100岁')
return rs
>>> check()
名字:admin
年龄:20
admin... |
f7f29b4f5f71a84beaee2f31222cf84cd73f4a21 | jenniejoyness/ML-traffic-detection | /ID3.py | 8,726 | 3.640625 | 4 | """
Calculate the prediction of a given test line.
Build a tree based on the train data and when
receiving a test line, follow the tree to get
the prediction.
"""
import copy
import operator
import math
import Edge
import Node
'''
returns the entropy of the data
'''
def get_entropy(list_of_rows):
pos = 0
ne... |
2db3a1aee36218a5c05f46b74df03dda7c847384 | ridwannurhayat/dtspython2020 | /chapter5/sudoku/sudoku.py | 969 | 4.21875 | 4 | #https://edube.org/learn/programming-essentials-in-python-part-2/lab-sudoku
def checkBoard(arr):
# cek kotak 3x3
for a in range(3):
for b in range(3):
temp = set()
for c in range(3):
for d in range(3):
num = arr[c+a*3][d+b*3]
... |
8ca8328ce7da4fe84b932292f8fb83605a61fab9 | tohidur/exac | /leet_code/problems/1_dungeon_game.py | 1,068 | 3.90625 | 4 | """
The daemons had captured the princess(P) and imprisoned here in the botton
right corner of a dungeon consists of M x N rooms laid out in a 2D grid.
Our valiang knight (K) was initally positioned in the top-left room and must
fight his way through then dungeon to rescue the princess.
The knight has a initial health... |
a5010b69888e363da203ebf99141ef41f5111284 | hualcosa/Numpy | /statistics_with_numpy/project1/script.py | 1,624 | 4.125 | 4 | import codecademylib
import numpy as np
# Load the data from the file and save it as calorie_stats
calorie_stats = np.genfromtxt('cereal.csv', delimiter=',')
# How much higher is the average calorie count of your competition?
# Save the answer to the variable average_calories
average_calories = np.mean(calorie_stat... |
08623cbc7b8e76c62b7204111657a88c6e27bcec | JordiLuan/Uri-Code | /1001 - Extremamente Básico.py | 112 | 3.640625 | 4 | # Entrada de dados
a = int(input())
b = int(input())
x = a + b
# expressão de saida
print("X = {}".format(x))
|
e1ef8711ff1e0fbfe25572eac71e146c2c52e1ee | jasontclark/hustleandcode180 | /lpthw/ex19-3.py | 1,687 | 4.09375 | 4 | def cheese_and_crackers(cheese_count, boxes_of_crackers):
print "You have %d cheeses!" % cheese_count
print "You have %d boxes of crackers!" % boxes_of_crackers
print "Man, that's enough for a party!"
print "Get a blanket.\n"
print "We can just give the function numbers directly:"
cheese_and_crackers(2... |
57247162564c77dea709ce1195e7b773fe37c2a3 | jasontclark/hustleandcode180 | /lpthw/ex21.py | 844 | 4.09375 | 4 | def add(a, b):
print "ADDING %d + %d" % (a, b)
return a + b
def subtract(a, b):
print "SUBTRACTING %d - %d" % (a, b)
return a - b
def multiply(a, b):
print "Multiplying %d * %d" % (a, b)
return a * b
def divide(a,b):
print "Dividing %d / %d" % (a, b)
return a / b
print "Let's do some... |
64f313e7def83ad9004f57ea25c503f2eb2a2450 | AlexDavies8/procedural-generation | /random-number-generator/random-number-generator.py | 345 | 3.9375 | 4 | from random import randint
try:
min = int(input("Enter minimum:\n> "))
except:
min = 0
try:
max = int(input("Enter maximum:\n> "))
except:
max = 10
print("Enter '0' to exit, press Return/Enter for a new number")
while True:
print(randint(min, max), end='')
if input(' ')... |
8c0ebc4e9b9d2ef03444624f04169d96bc58725d | SylvainMacabrey/MondeParallele-Python | /Position.py | 523 | 3.53125 | 4 | ########################## classe Position ###########################
import math
class Position:
def __init__(self, longitude_degrees, latitude_degrees):
self.latitude_degrees = latitude_degrees
self.longitude_degrees = longitude_degrees
@property # propriété
def longitude(self):
... |
4c211c40b8d0c59eb967c9084a8d859e07e53a73 | a-farhat/python2 | /code.py | 1,318 | 3.8125 | 4 |
calclist= []
ops = [5,2,"C","D","+"]
sum = 0
for i in ops:
print(calclist)
if type(i)==str:
print ('this is a string')
if i=="C":
if(len(calclist)>0):
calclist.pop()
elif i=="D":
if(len(calclist)>0):
listitem = calclist.pop()
... |
3020ab60b21ce2cf8ed2f09f5972fb595318d02f | andrezzadede/Curso_Guanabara_Python_Mundo_3 | /Mundo 3 - Exercícios/96Exercicio - Função.py | 422 | 4.125 | 4 | # Faça um programa que tenha uma função chamada area que receba as dimensoes de um terreno retangular(largura e comprimento) e mostre a area do terreno
def area(largura, comprimento):
terreno = largura * comprimento
print(f'A area do terreno de {largura}X{comprimento} é de {terreno}')
larg = float(input('Qual a ... |
0f37f4804275cd611c7c6e8d7a40d5d2ff166311 | andrezzadede/Curso_Guanabara_Python_Mundo_3 | /Mundo 3 - Exercícios/80Exercicio.py | 512 | 3.984375 | 4 | # Crie um programa onde o usuario possa digitar cinco valores numericos e cadastre-os em uma lista, ja na posição correta de inserção(sem usar o sort) no final, mostre a lista ordenada na tela.
lista = list()
for c in range (0, 5):
n = int(input('Fala o valor: '))
if c ==0 or n > lista[-1]:
lista.append(n) # Se ... |
23fec1961a1efccd7415be1376c7003253288370 | andrezzadede/Curso_Guanabara_Python_Mundo_3 | /Mundo 3 - Exercícios/87Exercicio.py | 727 | 4.15625 | 4 | #Aprimore o desafio anterior, mostrando no final:
#A) A soma de todos os valores pares digitados
#B) A soma dos valores da tecerceira coluna
#C) O maior dos valores da segunda linha
matriz = [[0,0,0], [0,0,0], [0,0,0]]
maior = scol = pares = 0
for l in range(0,3):
for c in range(0,3):
matriz[l][c] = int(input(f'D... |
0d12868730ae5d95d79b3e6d6b5e3dbd7fe43013 | andrezzadede/Curso_Guanabara_Python_Mundo_3 | /Mundo 3 - Exercícios/79Exercicio.py | 601 | 4.09375 | 4 | # Crie um programa onde o usuario possa digitar vários valores numericos e cadastre-os em uma lista. Caso o numero já exista lá dentro, ele não será adicionado, no final, serão exibidos todos os valures unicos digitados em ordem crescente
numeros = list()
while True:
n = int(input('Fale um número aí doidao: '))
if ... |
e228c64022b1daa7483b23b46545b655fad22f04 | andrezzadede/Curso_Guanabara_Python_Mundo_3 | /Mundo 3 - Exercícios/82Exercicio.py | 766 | 3.875 | 4 | #Crie um programa que vai ler vários números e colocar em uma lista. Depois disso, crie duas listas extras que vão contar apenas os valores pares e os valores impares digitados, respectivamente. Ao final, mostre o conteúdo das três listas geradas.
num = list()
pares = list()
impares = list()
while True:
num.append(i... |
5a266661d25e5661daa95ec9097e18012ee19179 | Jimbiscus/Python_Dump | /EX21.py | 480 | 3.890625 | 4 | # mylist = []
# while 0 not in mylist:
# newinput = input("Entrez un nombre : ")
# newinput = int(newinput)
# mylist.append(newinput)
# else:
# print(min(mylist))
# print(max(mylist))
number = input("n: ")
number = int(number)
pg = number
pp = number
while number != 0:
number = input("n: ")... |
a0fa54f69a6022e69cafb15e37b3ac471b593378 | Jimbiscus/Python_Dump | /paperfolding.py | 162 | 3.515625 | 4 |
def num_layers(n):
thicc = "0.0005m"
thicc = float(thicc[:-1]) * (2 ** n)
return thicc
print(num_layers(5))
print(num_layers(21))
# Write your code here :-)
|
1b311c3927d2152d80ad2f3797671eb2a74712b0 | Jimbiscus/Python_Dump | /forloop.py | 245 | 4.15625 | 4 | fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
for x in "banana":
print(x)
for i in range(11):
print("Compteur : " + str(i))
numbers = range(21, 10, -2)
print(list(numbers))
for n in range(21,10, -2):
print(n)
|
a059b833a6e28bfc1bcd4d4fb4b8093187340718 | Jimbiscus/Python_Dump | /countCharacters.py | 162 | 3.8125 | 4 | def count_characters(lst):
length = len(lst)
strLength = len(lst[0])
return length * strLength
print(count_characters([
"###",
"###",
"###"]))
|
c5893ef9bc0e495726b933b10705a76f3250a17d | Jimbiscus/Python_Dump | /Ex14.py | 251 | 3.53125 | 4 | from random import randint
mob_hp = 30
while mob_hp > 0:
attack = randint(5, 10)
mob_hp = mob_hp - attack
print("Le monstre subit un attaque de " + str(attack) + " HP, il lui reste " + str(mob_hp) + " HP.")
print("Le monstre est mort")
|
65485d6555a0d09262147c0986e93ce786a9406c | Jimbiscus/Python_Dump | /HomeworkWithListSum.py | 494 | 3.640625 | 4 |
l = []
somme = 0
numbersStored = 0
while somme < 20:
entry = input("Entrez un nombre : ")
entry = int(entry)
somme += entry
l.append(entry)
numbersStored += 1
else:
l.sort()
print("plus petit nombre : " + str(l[0]))
print("plus grand nombre : " + str(l[-1]))
print("vous avez entré "... |
e4b05f0429a2f51a4710111174f48f2629a695a7 | Jimbiscus/Python_Dump | /Microbit/MB_FillLinewithBButton.py | 463 | 3.5 | 4 | from microbit import *
x = 0
y = 0
while True:
if button_b.was_pressed():
for i in range(5):
display.set_pixel(x, y, 9)
y += 1
if y == 5:
x += 1
y %= 5
x %= 5
if button_a.was_pressed():
for i in range(5):
... |
db0287f36c0c5869a2e1ef2c35b953695d30de4b | Azevor/My_URI_Reply | /beginner/1047.py | 1,013 | 3.6875 | 4 | '''
Read the start time and end time of a game, in hours and minutes (initial hour,
initial minute, final hour, final minute). Then print the duration of the game,
knowing that the game can begin in a day and finish in another day.
Obs.: With a maximum game time of 24 hours
and the minimum game time of 1 minute.
'''
... |
dfed78579f7e68fcf718baafc3aec2ee3fabcc2a | Azevor/My_URI_Reply | /beginner/1038.py | 875 | 3.9375 | 4 | '''
Using the following table, write a program that reads a code and the amount of
an item. After, print the value to pay. This is a very simple program with the
only intention of practice of selection commands.
CODE SPECIFICATION PRICE
1 Cachorro Quente R$ 4.00
... |
50c9067b8f868d6b1a5090817ad2a23346382c22 | Azevor/My_URI_Reply | /beginner/1021.py | 1,377 | 4.03125 | 4 | '''
Read a value of floating point with two decimal places. This represents a
monetary value. After this, calculate the smallest possible number of notes
and coins on which the value can be decomposed. The considered notes are of
100, 50, 20, 10, 5, 2. The possible coins are of 1, 0.50, 0.25, 0.10, 0.05
and 0.01. Print... |
5e6c7acc5296b38a9d833267af5ad43736c7e9cf | Azevor/My_URI_Reply | /beginner/1002.py | 260 | 3.859375 | 4 | '''
The formula to calculate the area of a circumference is defined as A = π . R2.
Considering to this problem that π = 3.14159:
'''
m_PI = 3.14159
def calcAreaCircle(p_R):
return m_PI*p_R**2
print('A={:.4f}'.format(calcAreaCircle(float(input()))))
|
493dc984485412f0475e0b604431433ddc1d7338 | Azevor/My_URI_Reply | /beginner/1042.py | 448 | 4.25 | 4 | '''
Read three integers and sort them in ascending order. After, print these
values in ascending order, a blank line and then the values in the sequence
as they were readed.
'''
m_Input = input().split()
m_Sorted = []
for i in range(len(m_Input)):
m_Input[i] = int(m_Input[i])
m_Sorted.append(m_Input[i])
m_So... |
95e0d0592a6096ef1cb2e59f8d10c20ab11c5388 | Azevor/My_URI_Reply | /beginner/1010.py | 790 | 3.84375 | 4 | '''
In this problem, the task is to read a code of a product 1, the number of
units of product 1, the price for one unit of product 1, the code of a product
2, the number of units of product 2 and the price for one unit of product 2.
After this, calculate and show the amount to be paid.
'''
m_Product01, m_AmountProduc... |
6fade3297aea5de96ecd98471449b32880602a34 | simonjaz/simpyt | /assigment_3.2.py | 258 | 3.828125 | 4 | score = raw_input("Enter score between 0.0 and 1.0: ")
s = float(score)
if s > 1.0 :
print "Out of range"
elif s >= 0.9 :
print "A"
elif s >= 0.8 :
print "B"
elif s >= 0.7 :
print "C"
elif s >= 0.6 :
print "D"
elif s < 0.6 :
print "F" |
6c5c3c9074a9c1ad5cd1e3ccc8fbc48edd3a7ba1 | Dycast/crypto-signal | /app/behaviours/ui/backtesting/decision.py | 3,608 | 3.734375 | 4 |
"""
Decision encapsulates a boolean process that determines when to open and close a trade
"""
class Decision(object):
def __init__(self, indicators):
self.indicators = indicators
'''
Determines if we should buy given our buy strategies and our observed indicators
@param buy_strategy: A dict... |
25a5b6072a6de2005877b8521fc4bee7d51b94e8 | zcielz/scrapytest | /scrapytest/basetest01/demo01/py7.py | 284 | 3.8125 | 4 | # -*- coding: utf-8 -*-
__author__ = 'zciel'
import re
s1 = '我12345+aBCde'
# pattern字符串前加 “ r ” 表示原生字符串
pattern = r'(\w+)\+(\w+)'
# 返回一个匹配的列表
result1 = re.findall(pattern, s1, re.IGNORECASE) # 蒲培不区分大小写
print(result1)
|
fc8403e8c9670495d058394a1b51c1c73eb62750 | lpvera22/Study | /Lista_Ejercicios_3/Ejercicio_12.py | 1,576 | 3.953125 | 4 | # *-* encoding:UTF-8 *-*
'''Considere a matriz A, de dimensão nxn, onde o elemento da linha i e da coluna j é denotado por A ij .
Sabendo que
A ij < A ik , para todo i e j < k
A ij < A kj para todo j e i < k
elabore um algoritmo que, dado elemento x, determine a localização de x na matriz A. O seu algoritmo deve
reali... |
293256f81f1eab61f1847e988b06e9523e0d4a25 | lpvera22/Study | /Lista_Ejercicios_3/Ejercicio_7.py | 833 | 3.53125 | 4 | # *-* encoding:UTF-8 *-*
'''Dados um vetor ordenado A com n números reais e um número real x, escreva um algoritmo para determinar
se existem A[i] e A[j] tais que x = A[i] +A[j], sendo que o seu algoritmo dever ter complexidade O(n) para este
problema. Dica: O que se pode concluir da comparação de A[1] + A[n] com x?'''... |
57ffb0a4139904560778212001dcc6566e432ae0 | zoltancserei/WebScraper | /indeed_jobs.py | 1,981 | 3.59375 | 4 | # Web scraping job postings from indeed.co.uk
import os
import pandas as pd
from bs4 import BeautifulSoup
import urllib
import requests
def load_indeed_jobs(job_title, location):
# Extract the HTML and parse it
var = {'q': job_title, 'l': location, 'fromage': 'last', 'sort': 'date'}
url = (r'https://uk.... |
3c04ef48901cca1e80a7aaf8629f81b41132f21d | stewartt1982/datascience | /python/lynda_LearningPython/Ch2/loops.py | 566 | 3.953125 | 4 | #
# example of loops
#
def main():
x = 0
while(x < 5):
print x
x = x + 1
for x in range(5,10):
print x
days = ["Mon", "Tues", "Wed", "Thu", "Fri", "Sat", "Sun"]
for d in days:
print d
#break and continue
for x in range(5,10):
if(x == 7): break
... |
3545773953e78fb0543379ba6d7f4747d9e519c0 | stewartt1982/datascience | /python/lynda_LearningPython/Ch3/calanders.py | 1,101 | 4.25 | 4 | #
# Example working with calendars
#
import calendar
#create a calendar, plain text
c = calendar.TextCalendar(calendar.SUNDAY)
str = c.formatmonth(2013,1,0,0)
print str
#HTML calendar
hc = calendar.HTMLCalendar(calendar.SUNDAY)
str = hc.formatmonth(2013,1)
print str
#loop over days of the month
for i in c.itermonth... |
5c24e3307db903192aa63dbd4f93c387331a032a | Zariphron/HW-Python | /multiply.py | 889 | 4.375 | 4 | def multiply_list(num_List):
"""
This will take in a list and multiply
each number by the previous number in the list
continuously until it reaches the end of the list.
The end result will be all numbers multiplied together.
Example:
[2,3,4]
Because 2*3*4
Will end up being = 24
... |
297f2130b112a25ecf6f0255f76bfabc387f1fe9 | CurroValero05/TIC-2-BACH | /Cantidad.py | 235 | 3.9375 | 4 | def cantidad():
num=input ("Introudce un numero entero: ")
pal=raw_input ("Introduce una palabra: ")
if [num]==pal:
print ("El numero de letras es el mismo que el numero que has metido")
cantidad ()
|
cbc57bcc5ab9b395b00d6dcf362f52274455a8dc | vanessa617/Dev_2017 | /lambda_func.py | 715 | 4.375 | 4 | #lambda is an annoymous function that allows you to pass a function as variable.
#syntax example - lambda x: x % 3 == 0
#filter is used in conjunction with lambda to determine what to filter.
my_list = range(16)
print filter(lambda x: x % 3 == 0, my_list) # returns only numbers divisible by 3.
languages = ["HTML", "Ja... |
8044efde64570cf359693fd55d800d695d7bf92b | vanessa617/Dev_2017 | /math_funcs.py | 2,202 | 3.96875 | 4 | #math.ceil(x) - return the ceiling value of x - the smallest integer not less than or equal to x.
import math #this imports the math module
print "math.ceil(-45.17): ", math.ceil(-45.17)
print "math.ceil(100.12): ", math.ceil(100.12)
print "math.ceil(119L): ", math.ceil(119L)
print "math.ceil(math.pi): ", math.ceil(ma... |
9a71f7288ec2872bdc1a726558532991613cd6cd | vanessa617/Dev_2017 | /censor problem.py | 284 | 3.78125 | 4 | def censor(text, word):
list = text.split()
for i in list:
if i == word:
i.replace(word, ("*" * len(word))
return " ".join(list)
print censor("this is test", "this")
|
9723627146ac91f9f60d587b6daef1277a721dda | f0xtek/exercism-python-track | /series/series.py | 460 | 3.515625 | 4 | def slices(series, length):
if length > len(series) or length <= 0 or series == "":
raise ValueError("Please specify a length less than or equal to the series length")
slices_list = []
for i in range(len(series)):
if i == 0:
slice = series[i:length]
else:
sli... |
28e2ef43c25431e0af36798869526447b410fcd0 | groszewa/coding_interview | /binary_search/binary_search.py | 1,223 | 4.03125 | 4 | #!/usr/intel/bin/python
def binarySearch(arr,low,high,x) :
#base case
if high >= low:
mid = (high+low)/2
#print "low = " + str(low) + " high = " + str(high) + " mid = " + str(mid) + " arr[mid] = " + str(arr[mid])
if(arr[mid]==x):
return mid
elif(arr[mid]>x):
... |
70238ad5fc84d7ddb65ce1d745d7750e621ba21b | bradyshutt/scripts | /extractflashcards.py | 1,715 | 3.59375 | 4 | #!/usr/bin/env python3
import sys
VERBOSE=False
filename_in = sys.argv[1]
filename_out = sys.argv[1].split('.')[0] + "_flashcards.txt"
terms = []
questions = []
def main():
if len(sys.argv) > 2 and sys.argv[2] == "-v":
VERBOSE=True
if VERBOSE:
print( "Input File: " + filename_in )
... |
d590d94ebb31cf88959eebe955df8a12eac16da0 | tarek20501/Project_Euler | /Problem 6.py | 862 | 3.8125 | 4 | '''
The sum of the squares of the first ten natural numbers is,
1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)2 = 55^2 = 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.... |
85b74be7df2731c2258ee4ead967bd3e30b37057 | Aym83/TIPE | /Frame.py | 2,352 | 3.703125 | 4 | #Importation des différents modules
from tkinter import *
from Maths import *
from KeyListener import *
#Classe pour l'affichage
class Frame():
def __init__(self):
self.frame = Tk()
self.frame.title("Simulateur Système Solaire V0.2")
self.frameW = self.frame.winfo_screenwidth(... |
0667a0ce66d50a7acb6c966399126aa8d8dd1ed3 | cinnamennen/Advent2018 | /02/a.py | 424 | 3.703125 | 4 | from collections import Counter
def contain_two(f: list):
return 2 in Counter(f).values()
def contain_three(f: list):
return 3 in Counter(f).values()
two = three = 0
with open('a.txt') as f:
for line in f.readlines():
strip = list(line.strip())
if contain_two(strip):
two +... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.