blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
22f1a1402ec99fcca03b7c3e4881b8b2810a4f1e | eraserpeel/Project-Euler | /problem_1.py | 226 | 3.875 | 4 |
#Simple solution
total_sum = 0
for number in range(3, 1000):
if number % 3 == 0 or number % 5 == 0:
total_sum += number
print total_sum
#More pythonic way
print sum([i for i in range(3, 1000) if i % 3 == 0 or i % 5 == 0]) |
71bef7e532fa8bcb0a3e4433b21f0afe5030dea9 | LachlanCrews/pracs | /prac_04/quick_picks.py | 411 | 3.90625 | 4 | import random
quick_pick_line = []
count = 0
number_of_lines = int(input("How many quick picks: "))
while number_of_lines != 0:
while count < 6:
random_number = random.randint(1, 45)
if random_number not in quick_pick_line:
quick_pick_line.append(random_number)
count += 1
... |
6c84065573abb0081f18d58d9ffb92a5f6c7bc4f | zhenkai956/Python-100-Days | /Day01-15/My_Notes/06笔记.py | 4,957 | 4.15625 | 4 | # 文档中的例题
# 例题1:函数的作用
# 我的版本:
# def C(M,N):
def fac(num):
result = 1
# for num in range(num,0,-1):
# for temp in range(num + 1,0,-1):
for temp in range(num,0,-1):
result *= temp
return result
m = int(input('m = '))
n = int(input('n = '))
def C(M,N):
# result = fac(M)//fac(N)//fac(M-N+1)... |
4229f4f0306623a9ee9c9e3fce68c391675c2eb1 | lvh/ladders | /ladders/heuristic.py | 807 | 3.546875 | 4 | """
Heuristic-based graph search.
"""
import functools
from ladders import graph, search
def find_ladders(start, target, words, cache=None):
"""
Find ladders heuristically.
"""
root = graph.LadderNode(start, words, cache)
def heuristic(path):
return graph.distance(path[-1].name, target)
... |
dcd110453f4f8f0b65572350dcbb415c7aafe8ed | beber89/pcap-instructor-samples | /employer_tutorial_app/model.py | 381 | 3.65625 | 4 | class Employee:
def __init__(self, **kwargs):
''' set attributes for employee according to kwargs '''
for k, v in kwargs.items():
self.__setattr__(k, v)
def __repr__(self):
if(hasattr(self, 'name') and hasattr(self, 'age') and hasattr(self, 'city')):
return "name = %s, age = %d, city = %s"%... |
efd1529afc63cb12fcbdddd86361d42c26967ae0 | beber89/pcap-instructor-samples | /employer_tutorial_app/data_entry.py | 614 | 3.671875 | 4 | from model import Employee
class DataEntryError(Exception):
pass
class DataEntry:
def __init__(self, orm, user_input):
self.orm = orm
self.user_input = user_input
def apply_input(self):
try:
user_input= self.user_input.split()
user_input=''.join(user_input)
user_input=user_input... |
7e4afb731364c4ba690ad8bfb7cff0a64f7cfff9 | beber89/pcap-instructor-samples | /inclass-2/exception.py | 242 | 3.953125 | 4 | try:
x = int(input("Please enter a positive number:\n"))
assert x > 0 # AssertionError
except ValueError as msg:
print(msg)
except AssertionError:
print("Number is negative !!!")
print("Program done , out of while loop, output is ") |
7533ae7791a4bbd4b851e1efc4860cc4c3aa99d4 | gtu001/gtu-test-code | /PythonGtu/gtu/data_science/numpy/ex1/numpy_test_003.py | 578 | 3.515625 | 4 |
import numpy as np
a = np.array([0, 1, 2])
b = np.array([5, 5, 5])
c = a + b
print(c)
d = a + 5
print(d)
print("----------------------")
M = np.ones((3, 3))
print(M)
M2 = M + a
print(M2)
print("----------------------")
a = np.arange(3)
b = np.arange(3)[:, np.newaxis]
print(a)
pri... |
a12d06f62d116c8b48eb3abbf7a2aba313bea103 | gtu001/gtu-test-code | /PythonGtu/gtu/_tkinter/tkinter_test_002.py | 1,086 | 3.859375 | 4 | from tkinter import Text, Button, Label
import tkinter as tk
class MainUI():
def __init__(self):
win = tk.Tk()
win.title("產生36報表excel")
l1 = Label(win, text="路徑:")
l1.grid(column=0, row=0)
self.text = Text(win, width=30, height=2, font=("Courier", ... |
c491c5c83cb3fcbad56e6c49c1324c5648cf8618 | gtu001/gtu-test-code | /PythonGtu/gtu/_tkinter/tkinter_test_004.py | 662 | 3.8125 | 4 |
from tkinter.ttk import Combobox
import tkinter as tk
class Example(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.combobox = Combobox(self, values=["a", "b"])
self.combobox.bind('<<ComboboxSelected>>', self.comboboxClick)
self.co... |
27e71943a5a28d1ac44fef7944f89f3f448bd517 | Pengineer/Python34-Syntax | /simple/Demo11_map.py | 608 | 4.34375 | 4 | # map
'''
格式:map(func, *iterables)
filter只对序列中的元素进行过滤,并不会修改元素。map指对序列中的元素进行修改或映射,map函数的第二个参数是收集参数
'''
# 单一序列
print(list(map(lambda x : x * 2, range(5))))
# 多个序列做运算,各序列中相同脚标的元素做运算,func的参数个数与序列个数必须相同
# 如果各序列的长度不相等,则以最小长度的序列为基准
print(list(map(lambda x,y : x+y, range(5), range(20,30))))
# 多序列做映射
print(list(map(lambda... |
964ead0c1414d3b918e2b318261bab178be60feb | Pengineer/Python34-Syntax | /simple/Demo1_random.py | 306 | 3.59375 | 4 | # Demo1.py
import random
print('------------python34-------------')
num=random.randint(1,10)
temp = input("猜一下xxx现在心里想的是哪个数字:")
guess = int(temp)
if guess == num:
print("猜对了!")
else:
print("猜错啦!答案是:" + str(num))
print("游戏结束,88!")
|
1ff770a3d78bb0c32ca1275468844b1652b3c856 | manishbisht/Udacity | /Data Structures and Algorithms Nanodegree/P3 - Problems vs Algorithms/Problem 2 - Search in a Rotated Sorted Array/solution.py | 3,089 | 4.25 | 4 | def rotated_array_search(input_list, number):
"""
Find the index by searching in a rotated sorted array
Args:
input_list(array), number(int): Input array to search and the target
Returns:
int: Index or -1
"""
return rotated_array_search_recursive(input_list,
... |
630415380678949432e8727fad87d47d9fbe26bd | manishbisht/Udacity | /Data Structures and Algorithms Nanodegree/P3 - Problems vs Algorithms/Problem 4 - Dutch National Flag Problem/solution.py | 1,506 | 4.03125 | 4 | def sort_012(input_list):
"""
Given an input array consisting on only 0, 1, and 2, sort the array in a
single traversal.
Args:
input_list(list): List to be sorted
"""
next_0_index = 0
next_2_index = len(input_list) - 1
current_index = 0
while(current_index) < next_2_index + 1... |
edf94245f180921dd5436290b8519859aa8486c1 | manishbisht/Udacity | /Data Structures and Algorithms Nanodegree/P3 - Problems vs Algorithms/Problem 5 - Autocomplete with Tries/solution.py | 2,414 | 3.71875 | 4 | from collections import defaultdict
class TrieNode:
def __init__(self):
self.children = defaultdict(TrieNode)
self.isWord = False
def suffixes(self, suffix=''):
suffixes = []
for char, node in self.children.items():
if node.isWord:
suffixes.append(s... |
5cd9215278c16227ea8aef7bd93073b390f149c4 | DannyMireles/Python | /Lab4_Act4.py | 806 | 4.03125 | 4 | # By submitting this assignment, I agree to the following:
# "Aggies do not lie, cheat, or steal, or tolerate those who do."
# "I have not given or received any unauthorized aid on this assignment."
#
# Names: Daniel Mireles
# Jordan Nguyen
# Tan Nguyen
# Fern... |
0be5812c856954c29241d125baacc8a55586b7e9 | DannyMireles/Python | /Lab7b_Prog2.py | 1,886 | 4.15625 | 4 | # By submitting this assignment, I agree to the following:
# "Aggies do not lie, cheat, or steal, or tolerate those who do."
# "I have not given or received any unauthorized aid on this assignment."
#
# Name: Daniel Mireles
# Section: 102-540
# Assignment: Lab 7b - 2
# Date: 10/10/2019... |
4d43740255e70d7ada37139666a5f5657f1761a9 | DannyMireles/Python | /Lab11b_Act1.py | 3,730 | 3.9375 | 4 | # By submitting this assignment, I agree to the following:
# "Aggies do not lie, cheat, or steal, or tolerate those who do."
# "I have not given or received any unauthorized aid on this assignment."
#
# Name: Daniel Mireles
# Section: 102-540
# Assignment: Lab 1b
# Date: 11/14/2019
... |
afad7d45c39e96b79eb0ba5216cea92040540b7f | Sotatek-TrungNguyen/python-viope-practice | /ex10-1.py | 320 | 3.671875 | 4 | class Player:
teamcolor = "Blue"
points = "300"
def printout(self):
print("The " + self.teamcolor + " contender has " + self.points + " points!")
def main():
player1 = Player()
player1.teamcolor = "Blue"
player1.points = "300"
player1.printout()
if __name__=="__main__":
main() |
4b41662bce3d3f4e27504a9ed0b30508693268f9 | njmck/leetcode-problems | /01_easy/0001_two_sun.py | 704 | 3.59375 | 4 | # Input:
# Input:
# nums = [2,7,11,15]
# target = 9
# Output:
# [0,1]
# Because nums[0] + nums[1] == 9, we return [0, 1].
# In O(n) time:
nums = [2, 7, 11, 15]
target = 9
def twoSum(nums, target):
d = {}
for i, n in enumerate(nums):
m = target - n
if m in d:
return [d[m], i]
... |
1f02ddaaff3b6d593f57c7c5328d5d46e13e42f9 | EldarAshirovich/Eldar_python | /Lesson_6/Task_2.py | 1,316 | 3.640625 | 4 | import pydoc
"""
Autor Sabri Eldar
2. Реализовать класс Road (дорога).
определить атрибуты: length (длина), width (ширина);
значения атрибутов должны передаваться при создании экземпляра класса;
атрибуты сделать защищёнными;
определить метод расчёта массы асфальта, необходимого для покрытия всей д... |
96ecc256770c35915e71b655da90ad60a496a4ad | EldarAshirovich/Eldar_python | /Lesson_5/Task_2.py | 680 | 3.53125 | 4 | import pydoc
"""
Autor Sabri Eldar
2. Создать текстовый файл (не программно), сохранить в нём несколько строк, выполнить подсчёт строк и слов в каждой строке.
"""
try:
with open("task_1.txt") as file:
for i, line in enumerate(file):
print(f"Колчиество слов в строке(№{i+1}): {len(line.spli... |
616b083290c3aef1c5e1983e8dbb3f4c36c5a4c3 | firewa1kwithme/py_first_steps | /07_right_to_left/right_to_left.py | 359 | 3.515625 | 4 | def left_join(phrases):
text = ','.join(phrases)
text = text.replace("right", "left")
print text
test1 = ("left", "right", "left", "stop")
print test1
left_join(test1)
test2 = ("bright aright", "ok")
print test2
left_join(test2)
test3 = ("brightness wright",)
print test3
left_join(test3)
test4 = ("enough",... |
1c594545bb73bba6ac0d38bc1637e8276ab23b79 | firewa1kwithme/py_first_steps | /08_digits_multiplication/digits_multiplication.py | 317 | 3.5 | 4 | def checkio(number):
l = str(number).replace("0",'')
multi = 1
for i in l:
if int(i) != 0:
multi *= int(i)
print multi
test1 = 123405
print test1
checkio(test1)
test2 = 999
print test2
checkio(test2)
test3 = 1000
print test3
checkio(test3)
test4 = 1111
print test4
checkio(test4)
|
6b2ed4ae7c29f8d609dcb64274a9dcf1b02a1e94 | zli192/GeeksforGeeks-python | /Scripts/All pairs whose sum is x ( unsorted arrays ).py | 3,815 | 4.1875 | 4 | # http://www.geeksforgeeks.org/given-two-unsorted-arrays-find-pairs-whose-sum-x/
# Hashing
def sum_pairs(array1: list, array2: list, req_sum: int):
sum_lists = []
# hash array1 for later searching
hash1 = {x: x for x in array1}
for y in array2:
try:
# if hash1[req_sum-y] exists
... |
9549ad58ffd6b153fb66ebdae83e107dc6e5a08e | zli192/GeeksforGeeks-python | /Scripts/Continuous Subset sum problem - NonNegative list.py | 4,275 | 4.125 | 4 | # http://www.geeksforgeeks.org/find-subarray-with-given-sum/
# print the first subset that satisfies the condition
def find_continuous_subset(array: list, req_sum: int):
left = 0
right = 0
temp_sum = array[0]
while left < len(array):
if temp_sum == req_sum:
break
# subset ... |
2325cf8e4f68fc5976121b903018449143ac36db | zli192/GeeksforGeeks-python | /Scripts/Convert Binary Tree to Doubly Linked List.py | 4,535 | 3.953125 | 4 | # http://www.geeksforgeeks.org/convert-a-given-binary-tree-to-doubly-linked-list-set-4/
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def inorder_traverse(head: Node, result: list):
if head is not None:
inorder_traverse(head.left, res... |
468889a4d8d638fbad58afa85a225bd7ce4554d9 | tokomaki/Python-Projects | /straightline_programs/random_int.py | 367 | 3.765625 | 4 | # random_integer.py: Takes two integers a and b from the command line and
# writes a random integer between a (inclusive) and b (exclusive).
import random
import stdio
import sys
# Takes and assigns integers a and b
a = int(sys.argv[1])
b = int(sys.argv[2])
# Writes random integer from range including a and excludin... |
ff5abcf8b9a398cf5cef865c35b8638362c3c739 | tokomaki/Python-Projects | /straightline_programs/three_sort.py | 615 | 4.21875 | 4 | # three_sort.py: Takes three integers as command-line arguments and prints
# them in ascending order, separated by spaces.
import stdio
import sys
# Takes 3 integers and assigns them to variables a, b, and c
a = int(sys.argv[1])
b = int(sys.argv[2])
c = int(sys.argv[3])
# Calculate the largest amongst all variables ... |
124007dfd2b756a887e85b8d7ecd0a6d1e06c422 | maxipavlovic/pgexcercises | /chapter_2/chapter_2_task_2.py | 1,502 | 4.34375 | 4 | from tkinter import *
__author__ = 'Kolyubyakin Maxim'
__email__ = 'maxipavlovic@gmail.com'
'''
Create a program that prompts for an input string and displays output that shows the input string
and the number of characters the string contains.
Example Output
What is the input string? Homer
Homer has 5 characters.
C... |
085c5e92b96810bf4b3b49ba7a20476e2aa1a831 | Jokekiller/Functions | /spot check 2.py | 726 | 4.03125 | 4 | def journeyDetails():
distance = float(input("Enter the distance in miles: "))
mpg = float(input("enter the mpg of your vehicle: "))
fuelPrice = float(input("enter the current price of fuel; "))
return distance, mpg, fuelPrice
def fuelNeeded(distance, mpg):
amountOfFuelNeeded = mpg / distance
... |
278051ec6cbcf629f1cebf9e7ec8534cfb5c0706 | pulkitagrawal34/tictactoe | /tictactoe.py | 2,022 | 4 | 4 | symbol1 = str(input("Hi, Welcome to Tic Tac Toe, Player1 which symbol do you wish to choose X or O :")).upper()
symbol2= ""
if symbol1=="X" or symbol1=="O":
if symbol1 =="X":
symbol2 = "O"
else:
symbol2= "X"
values= [" "," "," "," "," "," "," "," "," "]
def print_grid():
... |
b0e41a38e1e20e94cbac4cf869811194726d1c52 | buildkdom/statistics-201807 | /ml/20180725/overfitting-01.py | 631 | 3.78125 | 4 | import matplotlib.pyplot as plt
import numpy as np
x = np.random.rand(100, 1) # 0~1까지 난수를 100개 만든다
x = x * 2 - 1
y = 4*x**3 - 3*x**2 + 2*x - 1
y += np.random.randn(100, 1)
# 학습 데이터 30개
x_train = x[:30]
y_train = y[:30]
# 테스트 데이터 70개
x_test = x[30:]
y_test = y[30:]
plt.subplot( 2, 2, 1 )
plt.scatter... |
03bd8e8429c5e4a4cdef8a636aa5f8d67a6eb3b3 | buildkdom/statistics-201807 | /comprehension/list.py | 321 | 3.65625 | 4 | elements = [x * 2 for x in range(11)]
print(elements)
vals = [32, 12, 96, 42, 32, 93, 31, 23, 65, 43, 76]
amount = sum(vals)
print([(x / amount)+1 for x in vals])
from math import sqrt
non_squars = [x for x in range(101) if sqrt(x)**2 != x]
print (non_squars)
print(int(sqrt(14)))
print(int(sqrt(14))**2)
... |
80a93ace65cd8ac3b0b4bfa6a324974b4774c39e | alecheil/final_project | /test_02.py | 846 | 3.84375 | 4 |
def main():
def print_menu():
print(" MENU")
print("---------------------")
print("1) Landyachtz Dinghy")
print("2) Sector9 Horizon")
print("3) ThreeSix Dropthrough")
print("4) Kryptonics Pintail")
print("5) quit")
print_menu()
boar... |
8d19ca8383c3775a38a7a43a37e2890d0170f77f | avirupdandapat/ALGOPROJECT | /longestvalidparenthesis.py | 1,150 | 3.5625 | 4 | class Solution:
# @param A : string
# @return an integer
def longestValidParentheses(self, A):
## stack to store unbalanced parenthesis indexes
## -1 at starting and len(A) is added at end to cover corner cases like full balanced parenthesis etc.
stack = [-1]
for x in range(l... |
1145cf3923593d224b5f36685cb0e57262dfec2a | avirupdandapat/ALGOPROJECT | /reorderlistLL.py | 1,961 | 3.828125 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def add(self, lisnod):
self.next = lisnod
def __str__(self):
return "{K}\nv={V}".format(
K=self.next, V=self.val)
# return "v={V}".format(
#... |
636123637890dc0ad6c2fe9f67ceca2cdc443211 | avirupdandapat/ALGOPROJECT | /mergeKList.py | 1,435 | 3.75 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def add(self, lisnod):
self.next = lisnod
def __str__(self):
return "{K}\nv={V}".format(
K=self.next, V=self.val)
# return "v={V}".format(
#... |
a6c5d99c64c27706ed909be37d888763e35ee24d | avirupdandapat/ALGOPROJECT | /cyclelistLL.py | 953 | 3.90625 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def add(self, lisnod):
self.next = lisnod
class Solution:
# @param A : head node of linked list
# @return the first node in the cycle in the linked list
def detectCy... |
69a3470182f864b50bfdf075437cdc53d0080e6d | avirupdandapat/ALGOPROJECT | /hotelbooking.py | 641 | 3.53125 | 4 | class Solution:
# @param arrive : list of integers
# @param depart : list of integers
# @param K : integer
# @return a boolean
def hotel(self, arrive, depart, K):
events = [(t, 1) for t in arrive] + [(t, 0) for t in depart]
events = sorted(events)
guests = 0
for eve... |
b44c27046ea95b2581a8adb4eefd60f0bb36c694 | avirupdandapat/ALGOPROJECT | /palindromelist.py | 1,259 | 3.875 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def add(self, lisnod):
self.next = lisnod
def __str__(self):
# return "{K}\nv={V}".format(
# K=self.next, V=self.val)
return "v={V}".format(
... |
550eda6c3430fc7f8fc70ddfeefe0af5033b277b | avirupdandapat/ALGOPROJECT | /reversestring.py | 377 | 3.546875 | 4 | class Solution:
# @param A : string
# @return a strings
def solve(self, A):
B = ''
A = (str.split(A, ' ')[::-1])
for i in range(len(A)):
if i == 0:
B = B + str(A[i])
else:
B = B + ' ' + str(A[i])
return B
if __name__ =... |
bd12b6122563438465162ef7860ac0eb718c4997 | avirupdandapat/ALGOPROJECT | /simplifypath.py | 518 | 3.53125 | 4 | class Solution:
# @param A : string
# @return a strings
def simplifyPath(self, A):
stack = []
A = A.split('/')
for a in A:
if a == '..':
if len(stack) > 0:
print(stack)
stack.pop()
elif a == '.':
... |
085f29d341f16295260a7979d4bfa3a2ae240e42 | avirupdandapat/ALGOPROJECT | /inordertraversal.py | 998 | 3.90625 | 4 | # Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param A : root node of tree
# @return a list of integers
def inorderTraversal(self, A):
stack = []
node = A
res ... |
d8347e10154a22770498432c617e40c50b002e0d | ilya-zvoznikov/Programming_Python | /Gui/Tour/entry2-modal.py | 891 | 3.546875 | 4 | """
создает модальный диалог с формой;
данные должны извлекаться до уничтожения окна с полями ввода
"""
from tkinter import *
from Gui.Tour.entry2 import makeform, fetch, fields
def show(entries, popup):
fetch(entries) # извлечь данные перед уничтожением окна!
popup.destroy() # если инструкции поменять мес... |
2bd9b23aa42a0e7d2ed5af71fda009c84849f169 | ilya-zvoznikov/Programming_Python | /Gui/Tour/menu_win-multi.py | 363 | 3.78125 | 4 | from tkinter import *
from Gui.Tour.menu_win import makemenu
root = Tk()
for i in range(3):
win = Toplevel(root)
makemenu(win)
Label(win,
text=('Window №%d' % (i + 1)),
bg='black',
fg='green',
font=('system', 40, 'bold'),
width=15,
height=5).pack... |
ed79e1121e8b86a644c82c1e75be4d9bec4f3672 | SatenovaAknur2001/web2020 | /webprojects/hw10 2.py | 63 | 3.59375 | 4 | n=int(input())
for n in range(n):
if n==0:
print(n) |
9f02416e7e7a122f47c7d7a40d08e06d6fc638cb | Mikaspike/SalaryPredictions | /requirements/SalaryPredictions_EDA.py | 12,833 | 3.5 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Salary Predictions Based on Job Descriptions
# We want to be able to predict salaries for new job postings by using a machine learning model. In this notebook, we will clean the data first to be able to do an effective exploratory data analysis.
# The purpose of which is to... |
02708c9968459d4508845d5123e203865168361a | lidianehonorato/lidianehonorato | /aula06.py | 248 | 3.953125 | 4 | #criar uma tabuada
valor= int(input('entre com o numero para tabuada '))
aux=0
print('*' * 18)
print('tabuada de {}'.format(valor))
print('*' * 18)
while (aux <=10):
print('{0} X {1} = {2}'.format (aux,valor,(aux * valor)))
aux = aux +1
|
1a15e75faff43e0323ec14a89d575f48ef78f1a1 | lidianehonorato/lidianehonorato | /aula10.py | 319 | 4.21875 | 4 | tempo = int(input('quantos anos tem o seu carro? '))
if tempo <=3:
print('carro novo')
else: print('carro velho')
print('--fim---')
# segunda forma de montar a solução codigo simplificado
tempo = int(input('quantos anos tem o seu carro? '))
print('carro novo' if tempo <=3 else'carro velho')
print('--fim---') |
c9c31ea8c1452716ce1638608470644ca06a8411 | lidianehonorato/lidianehonorato | /aula10custodeviagem.py | 342 | 3.71875 | 4 | dist = float(input('qual a distancia da viagem? '))
print(' Sua viagem de {} km vai começar!! '.format(dist))
if dist <=200:
preço = dist * 0.50
print(' Voce pagara este valor {:.2f} por ate 200 km! '.format(preço))
else:
preço = dist * 0.45
print(' Voce pagara este valor {:.2f} por ultrapassar 200 km... |
f148d5a67bf95c5fdfca608a0fc34be354663fc5 | lidianehonorato/lidianehonorato | /script3.py | 120 | 3.703125 | 4 | n1=int(input('digite o primeiro numero? '))
n2=int(input('digite o segundo numero? '))
s=n1+n2
print('A soma é =',s)
|
9b55749f8a34fc9329259be8f4ed1bf99ac460ea | priyankitshukla/CurdwithDjango | /core/Topic-12_Class_Constructor.py | 525 | 3.984375 | 4 | #Use Pascal naming convention for declaring class Names.
# for constructor use def __init__(self)
class Point:
def __init__(self,x,y):
self.x=x
self.y=y
def move(self):
print("Move")
def draw(self):
print('Draw')
point=Point(10,20)
print(point.x)
## Excersize
... |
2a2ff8cacfa026a75649be6e4122121d434bee90 | priyankitshukla/CurdwithDjango | /core/Topic-10_Exception.py | 355 | 4 | 4 | # enter a alpha numeric value intead of integer value to exception comes.
# age=int(input('Age : '))
# print(age)
try:
age = int(input('Age : '))
print(f'Age ={age}')
risk = 2000 / age
print(f'Risk = {risk}')
except ValueError:
print('Please try again.')
except ZeroDivisionError:
print(f'Age ca... |
8f47aeb51db763d9152a9fee1979aa2835913bda | priyankitshukla/CurdwithDjango | /testcase/calculator.py | 158 | 3.8125 | 4 | def add(a, b):
return a + b
def subtract(a, b):
if b== 0:
raise ValueError('Cant devide by zero')
else:
return a/b
print(add(2, 2))
|
25fd876112cbd3b30778378ea3a17c1a7fc9f258 | sarahfulkerson/interviewprep | /Sorting/15_bubble_sort.py | 599 | 3.828125 | 4 | #! /usr/bin/env python3
# https://www.hackerrank.com/challenges/ctci-bubble-sort/problem
def countSwaps(a):
count = 0
for x in range(len(a)):
for y in range(len(a)-1):
#Swap adjacent elements if they are in decreasing order
if a[y] > a[y + 1]:
a[y], a[y+1] = a[y+... |
78a4296a170d12ad46cfddba653a6abc15ae856b | sarahfulkerson/interviewprep | /Warm_Ups/3_jumping_on_the_clouds.py | 567 | 4.0625 | 4 | #! /usr/bin/env python3
# https://www.hackerrank.com/challenges/jumping-on-the-clouds/problem
def jumpingOnClouds(c):
counter = 0
n = 0
n2 = 0
res = 0
while counter < len(c)-2:
n = c[counter]
n2 = c[counter+2]
if n == n2:
counter += 2
else:
... |
7aacacb7747d1abdbe6edaa7e6e6492acf216c3c | sarahfulkerson/interviewprep | /Warm_Ups/4_repeated_strings.py | 497 | 3.890625 | 4 | #! /usr/bin/env python3
# https://www.hackerrank.com/challenges/repeated-string/problem
def repeatedString(s, n):
rep = n // len(s)
remain = n % len(s)
a_in_str = 0
a_in_remainder = 0
res = 0
for x in s:
if x == 'a': a_in_str += 1
res = rep * a_in_str
for y in s[:remain]:... |
77086d069860578a96856cc5f31d481a18990675 | gear/learn | /udacity_softwaredev/cryptarithmetic.py | 2,336 | 3.8125 | 4 | # python=3.5.2
import itertools, re, time, cProfile
def solve(formula):
"""
Given a formula 'ODD + ODD == EVEN', fill in digits
to solve it.
"""
for f in fill_in(formula):
if valid(f):
return f
def fill_in(formula):
"""
Generate all possible filling-in of letters i... |
41156e636bbc7cd9105c3b85e171c4fc151a06f7 | gear/learn | /codeforfun/python/how_to_log.py | 978 | 4 | 4 | """Quick tutorial for logging in Python.
"""
# Coding: utf-8
# Filename: how_to_log.py
# Created: 2016-07-12 v0.0
# Description: Tutorial for logging in Python.
## v0.0: File created.
import logging
# Create a log file with log level of 'INFO'
# which means it only saves logging with level
# higher or equal 'INFO'.
... |
431e48a842ea7b59fdd5f73738b2589f3f9810de | Malak-Ghanom/CA18 | /app.py | 6,908 | 3.515625 | 4 | # calcweb
import math
from flask import Flask, render_template, url_for, request, redirect
app = Flask(__name__) # create a new flask application
# define basic routes
@app.route("/add", methods=["POST"])
def add():
print("The page was requested with the method POST.")
# read the values from t... |
8fa06231c81f68f120e35291bb9c9938caf17160 | frhamadiansyah/ujian_modul_1 | /ujian_modul_1.py | 1,533 | 3.65625 | 4 | # Soal 1
print ('Soal 1:')
def calculate_years(principal,interest,tax,desired):
year = 0
while principal < desired:
bunga = principal*interest
bunga = bunga - (bunga*tax)
principal = principal + bunga
year += 1
return print(year)
calculate_years(1000,0.05,0.18,1100)
calculat... |
56f0c5f2cd71a1eca212d8532df0bca21eba7066 | cs-fullstack-fall-2018/python-review-exercise-3-myiahm | /Ex4.py | 94 | 3.625 | 4 | while True:
useInput = input("Enter a number")
if useInput == useInput:
break
|
44ea9bf25633305b1782a4c1820051a1d5060dd8 | ZacharyRSmith/py-sandbox | /callable.py | 432 | 3.71875 | 4 | from collections import defaultdict
class CountMissing(object):
def __init__(self):
self.added = 0
def __call__(self):
self.added += 1
return 0
counter = CountMissing()
current = {
'blue': 2, 'green': 4
}
increments = [
('red', 3),
('blue', 2),
('orange', 1)
]
result... |
861354eeadcfcb3c50f73d1069b15013906b7f28 | akshoop/MA573_ComputationalMethods | /HW1/Q4.py | 3,304 | 3.96875 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
@author: Alex Shoop (akshoop)
HW1, question 4
"""
# importing the necessary packages
import numpy as np
import matplotlib.pyplot as plt
import math #used for floor function
# FIRST LCRNG
##############################################################################... |
76173f4f282462117faf1e78953d00e61cebdd73 | akshoop/MA573_ComputationalMethods | /HW2/Q6.py | 6,835 | 3.515625 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
@author: Alex Shoop (akshoop)
HW2, question 6)
"""
# importing the necessary packages
import numpy as np
from numpy import sqrt, exp, log
from scipy.stats import norm
import matplotlib.pyplot as plt
#################################################################... |
a2e965d9ad728ab4b490e780d78277225fa76868 | childe/leetcode | /perfect-squares/solution.py | 812 | 3.546875 | 4 | # -*- coding: utf-8 -*-
import math
class Solution:
def numSquares(self, n: int) -> int:
q = [(0, n)]
visited = {n: 0}
while q:
# print(q)
# print(visited)
step, num = q.pop()
# print(' ', step, num)
for i in range(int(math.sqrt... |
d45732f97931464ebd8ec39350afec7546084f17 | childe/leetcode | /two-sum/two-sum.py | 1,749 | 3.625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
class Solution:
# @param {integer[]} nums
# @param {integer} target
# @return {integer[]}
def twoSum(self, nums, target):
d = {}
for idx, e in enumerate(nums):
if e in d:
return d[e], idx+1
... |
d7f528259d3b4f93ea2a46b0b357a546dc4fc13b | childe/leetcode | /reverse-nodes-in-k-group/solution.py | 4,721 | 4.0625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
https://leetcode.com/problems/reverse-nodes-in-k-group/
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not... |
59fdc81c2bf68866730c08113e54a48da403b6dd | childe/leetcode | /count-number-of-homogenous-substrings/solution.py | 1,765 | 4 | 4 | #!/usr/bin/env python
"""
https://leetcode.cn/problems/count-number-of-homogenous-substrings/
1759. 统计同构子字符串的数目
中等
39
相关企业
给你一个字符串 s ,返回 s 中 同构子字符串 的数目。由于答案可能很大,只需返回对 109 + 7 取余 后的结果。
同构字符串 的定义为:如果一个字符串中的所有字符都相同,那么该字符串就是同构字符串。
子字符串 是字符串中的一个连续字符序列。
示例 1:
输入:s = "abbcccaa"
输出:13
解释:同构子字符串如下所列:
"a" 出现 3 次。
"aa"... |
3d07d60a268258d87272da945bd4c384addff54c | childe/leetcode | /prefix-and-suffix-search/solution.py | 2,972 | 4.15625 | 4 | #!/usr/bin/env python3
"""
https://leetcode.cn/problems/prefix-and-suffix-search/
Prefix and Suffix Search
Design a special dictionary that searches the words in it by a prefix and a suffix.
Implement the WordFilter class:
WordFilter(string[] words) Initializes the object with the words in the dictionary.
f(string ... |
197218acd377297b9572b9c6ee16525240f327c6 | childe/leetcode | /combination-sum/combination-sum.py | 1,708 | 3.59375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
https://leetcode.com/problems/combination-sum/description/
Given a set of candidate numbers (C) (without duplicates) and a target number (T),
find all unique combinations in C where the candidate numbers sums to T.
The same repeated number may be chosen from C unlimi... |
b246b5eead7e6c18b20862fc7bb0d6404c4eb80c | childe/leetcode | /sum-of-unique-elements/solution.py | 1,177 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
https://leetcode-cn.com/problems/sum-of-unique-elements/
1748. Sum of Unique Elements
You are given an integer array nums. The unique elements of an array are the elements that appear exactly once in the array.
Return the sum of all the unique elements of nums.
... |
2e116600c56c092e1bcbf97ee329606afeb3ffd6 | childe/leetcode | /implement-strstr/implement-strstr.py | 1,146 | 3.953125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
https://leetcode.com/problems/implement-strstr/#/description
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
'''
class Solution(object):
def strStr(self, haystack, needle):
... |
25de5a0736a71d12de5ee3dca5312ff4636aad81 | childe/leetcode | /first-missing-positive/solution.py | 2,204 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
https://leetcode-cn.com/problems/first-missing-positive/
41. First Missing Positive
Given an unsorted integer array, find the smallest missing positive integer.
Example 1:
Input: [1,2,0]
Output: 3
Example 2:
Input: [3,4,-1,1]
Output: 2
Example 3:
Input: [7,8,9,11,12]
Output: 1
Note:
... |
851241ce96f743fb69a2fddb56f63ce8bfaaf183 | childe/leetcode | /median-of-two-sorted-arrays/solution.py | 4,152 | 3.953125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
https://leetcode.com/problems/median-of-two-sorted-arrays/
There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two
sorted arrays. The overall run time complexity should be O(log (m+n)).
1. 每个列表取中间数字 nums[len(nums)/2], 记做x,y,... |
60218cecf2e091d5f716ccd1a980c4ee17e66af6 | childe/leetcode | /path-with-maximum-gold/solution.py | 2,820 | 4.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
https://leetcode-cn.com/problems/path-with-maximum-gold/
1219. Path with Maximum Gold
In a gold mine grid of size m x n, each cell in this mine has an integer representing the amount of gold in that cell, 0 if it is empty.
Return the maximum amount of gold you can c... |
01589ca2c8106fbe64e3ea0b1d3bf1b420874648 | childe/leetcode | /roman-to-integer/solution.py | 2,154 | 3.875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
https://leetcode.com/problems/roman-to-integer/
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
基本字符
I V X L C D M
相应的阿拉伯数字表示为
1 5 10 50 100 500 1000
基本数字 Ⅰ、X 、C 中的任何一个、自身连用构成数目、或者放在大数的右边连用构成数目、都不能超过三个;放在大数... |
90fb658e464eb14826741eb1f5db7ba68d81b659 | childe/leetcode | /find-all-anagrams-in-a-string/solution.py | 2,059 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
https://leetcode-cn.com/problems/find-all-anagrams-in-a-string/
Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.
Strings consists of lowercase English letters only and the length of both strings s and p will not be larger
than 20,100.
The order ... |
bd9d40d5084afabe929b65f2459c8af7dc2fd9ca | childe/leetcode | /all-possible-full-binary-trees/solution.py | 1,631 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
https://leetcode.com/problems/all-possible-full-binary-trees/description/
A full binary tree is a binary tree where each node has exactly 0 or 2 children.
Return a list of all possible full binary trees with N nodes. Each element of the answer is the root node of one possible tree.
Each... |
1b8d787c443d1780fadfc7bb32fc96759d33057f | childe/leetcode | /cells-with-odd-values-in-a-matrix/solution.py | 976 | 3.640625 | 4 | #!/usr/bin/env python3
"""
https://leetcode.cn/problems/cells-with-odd-values-in-a-matrix/
Constraints:
1 <= m, n <= 50
1 <= indices.length <= 100
0 <= ri < m
0 <= ci < n
Follow up: Could you solve this in O(n + m + indices.length) time with only O(n + m) extra space?
"""
class Solution:
def oddCells(self, m:... |
99196602ac2050ccaa655fcf91c9c3aa5d936fdf | childe/leetcode | /integer-to-roman/solution.py | 2,437 | 3.9375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
https://leetcode.com/problems/integer-to-roman/
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
基本字符
I V X L C D M
相应的阿拉伯数字表示为
1 5 10 50 100 500 1000
基本数字 Ⅰ、X 、C 中的任何一个、自身连用构成数目、或者放在大数的右边连用构成数目、都不能超过三个;放在大数... |
9f79428a4e7c820c0b775a8540b5c6ac2a144704 | childe/leetcode | /utf-8-validation/solution.py | 2,853 | 4.3125 | 4 | #!/usr/bin/env python3
"""
https://leetcode-cn.com/problems/utf-8-validation/
Given an integer array data representing the data, return whether it is a valid UTF-8 encoding.
A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules:
For a 1-byte character, the first bit is a 0, followed by... |
b1d73d12987e9863e6b30c259ae79b68715234cf | childe/leetcode | /sudoku-solver/sudoku-solver.py | 6,694 | 3.875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
https://leetcode.com/problems/sudoku-solver/description/
Write a program to solve a Sudoku puzzle by filling the empty cells.
Empty cells are indicated by the character '.'.
You may assume that there will be only one unique solution.
"""
class Solution(object):
... |
0e4fb4d8e6191187de574dfc987ebb9d3c4b2dde | childe/leetcode | /kth-smallest-element-in-a-bst/solution.py | 1,682 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
https://leetcode-cn.com/problems/kth-smallest-element-in-a-bst/
Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.
Example 1:
Input: root = [3,1,4,null,2], k = 1
3
/ \
1 4
\
2
Output: 1
Example 2:
Input: root = [5,3,6,2,4,nu... |
16059edb1f65bedf80b3bd58f152ee335ce4f205 | childe/leetcode | /random-pick-index/solution.py | 1,499 | 4.25 | 4 | #!/usr/bin/env python3
"""
https://leetcode-cn.com/problems/random-pick-index/
Given an integer array nums with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array.
Implement the Solution class:
Solution(int[] nums) Initializes ... |
64a05d95283cff7199d76904fb0385ab5412cd25 | childe/leetcode | /container-with-most-water/solution.py | 2,247 | 3.84375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
https://leetcode.com/problems/container-with-most-water/
Given n non-negative integers a1, a2, ..., an, where each represents a point
at coordinate (i, ai). n vertical lines are drawn such that the two endpoints
of line i is at (i, ai) and (i, 0). Find two lines, which... |
45e10cc891f63134155265a153fe2fbdc82133e8 | childe/leetcode | /search-in-rotated-sorted-array-ii/solution.py | 2,456 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
https://leetcode-cn.com/problems/search-in-rotated-sorted-array-ii/
81. 搜索旋转排序数组 II
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]).
You are given a target value to search. If found in th... |
adab857b02cffd1a7f8c3756308603da7ddb6aaf | childe/leetcode | /open-the-lock/solution.py | 4,980 | 4.0625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
https://leetcode.com/problems/open-the-lock/description/
You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example we can turn '9' to be ... |
046c213585e92f9cd1a6cf0b784f372955e89dca | childe/leetcode | /course-schedule/solution.py | 2,157 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
https://leetcode-cn.com/problems/course-schedule/
207. Course Schedule
There are a total of numCourses courses you have to take, labeled from 0 to numCourses-1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is
expressed as a pair:... |
1a80d7894309c60d0fbe0bf407734e2d6fd60892 | Aaayue/Hello-World | /LeetCode/TwoSum.py | 782 | 3.53125 | 4 | """
给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
"""
import numpy as np
# class Solution:
class Solution:
def __init__(self):
pass
def twoSum(self, nums, target):
nums = np.array(nums)
for i in range(len(nums)):
dist = target - nums[i]
tmp = ... |
b6bcc0bac82a7e6866e833af993f0a62954c5583 | abinavrameshs/learn_flask | /app_store.py | 3,238 | 3.859375 | 4 | from flask import Flask, jsonify, request,render_template
app = Flask(__name__)
"""
# We define a list of stores.
Each store is a dictionary with a name and a list of items.
Each item is a disctionary with a name and a price
"""
stores = [
{
'name' : 'First Store',
'items' : [
{
'name' :... |
cfb34f5683e54e96c53bceefba95ab9894628002 | GainAw/PasswordManager | /Main.py | 1,645 | 4.375 | 4 | import random
import string
password_list = []
def new_password():
website = input("What is the website: ")
username = input("What is the username: ")
password = input("What is the pasword: ")
if password == "random":
while True:
N = int(input("How long do you want? "))
i... |
0acc4b1b2445d318f17ebccc63f2d588ac00148f | obusorezekiel/pycalc | /calculator.py | 3,111 | 3.703125 | 4 | from tkinter import *
def btnClick(number):
global operator
operator = operator + str(number)
text_input.set(operator)
def btnClear():
global operator
operator=""
text_input.set("")
def btnEquals():
global operator
sumup=str(eval(operator))
text_input.set(sumup)
operator=""
... |
6e3ae69b5008a353587783b37321d231cec6b5ac | omerfarukfidan/VSCode-Python-Basics | /01_python_giris/0125_practice.py | 381 | 3.78125 | 4 | """
Lütfen Kısa Kenarı Giriniz: 8
Lütfen Uzun Kenarı Giriniz: 10
Kenar Uzunlukları 8 ve 10 cm. olan dikdörtgenin çevresi 160 cm.
"""
kisaKenar=int(input("Lütfen kısa kenarı giriniz: "))
uzunKenar=int(input("Lütfen uzun kenarı giriniz: "))
cevre=2*(kisaKenar+uzunKenar)
print(f"Kenar Uzunlukları {kisaKenar} ve {uzunKe... |
af345acf97f5ee7acc9771a61b38be1a52cb3236 | omerfarukfidan/VSCode-Python-Basics | /02_karar_yapilari/0219_challange.py | 792 | 3.71875 | 4 | """
kullanıcı adı user
şifre 123
kullanıcı adı hatalı tekar deneyin yazdır kullancıı adı admin123 olmalı
kullanıcı adına admin girdi ama şifreyi yanlıs girdi şifre 123456
"""
kullaniciAdi = input("Lütfen kullanıcı adınızı giriniz: ")
parola = (input("Lütfen parolayı giriniz: "))
if kullaniciAdi == "admin1234":
i... |
8e26d59249994ffd4f153834bbc8b09dce39484d | omerfarukfidan/VSCode-Python-Basics | /01_python_giris/0126_practice.py | 545 | 3.921875 | 4 | """
Lütfen 1. Sayıyı Giriniz : 10
Lütfen 2. Sayıyı Giriniz : 2
10.0 + 2.0 = 12.0
10.0 - 2.0 = 8.0
10.0 * 2.0 = 20.0
10.0 / 2.0 = 5.0
"""
birinciSayi= float(input("Lütfen 1. Sayiyi Giriniz: "))
ikinciSayi= float(input("Lütfen 2. Sayiyi Giriniz: "))
print(f"{birinciSayi}+{ikinciSayi... |
8fadd5f525177ef57e812b299084aa428daaa4a4 | omerfarukfidan/VSCode-Python-Basics | /02_karar_yapilari/0220_challange.py | 802 | 3.90625 | 4 |
sinavNotu1, sinavNotu2 = int(input("İlk sınav notunu giriniz: ")), int(input("İkinci sınav notunu giriniz: "))
ortalama = (sinavNotu1+sinavNotu2)/2
if sinavNotu1>100:
print("100'den büyük bir not giremezsiniz lütfen tekrar giriniz:")
elif sinavNotu2>100:
print("100'den büyük bir not giremezsiniz lütfen te... |
b17725491b000c7bc709e45b4119f183e0d9256c | omerfarukfidan/VSCode-Python-Basics | /02_karar_yapilari/0215_nested_if.py | 243 | 3.8125 | 4 |
sayi=int(input("Lütfen bir sayi giriniz:"))
if sayi>0:
if sayi<=100:
print("Sayi 0 la yüz arasındadır.")
elif sayi>100:
print("Sayi 100'den büyüktür")
else:
sayi=int(input("Lütfen yeni bir sayi giriniz:")) |
b4f63c6f0fd89940f5b86e27db8956ae5d386967 | Aude11/ToDo | /CommandLineUi.py | 1,650 | 3.53125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 1 23:17:20 2021
@author: vernet01
"""
from Command import Command
from UserInput import UserInput
from AddObj import AddObj
from DeleteObj import DeleteObj
from EditObj import EditObj
from IncorrectInputObj import IncorrectInputObj
class CommandL... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.