blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
cbe6e0bacd4d3809c76d6316627a84702905f723 | jack7b/centos-7 | /python实例/day3_if_else.py | 287 | 3.78125 | 4 | number = int(input("输入您想送几朵玫瑰花,小默会告诉您含义"))
if number==1:
print("1朵:你是我的唯一")
elif number == 3:
print("3朵:I LOVE YOU")
elif number ==10:
print("10朵:十全十美")
elif number ==99:
print("99朵:天长地久")
|
7aa7541d2bca486620351966d380a4e2d28107e7 | shulyak86/hillel_ira | /homework 4 lesson/task3.py | 188 | 3.9375 | 4 | a = int(input('vvedite A'))
b = int(input('vvedite B'))
if a < b:
while a <= b:
print(a)
a += 1
elif a > b:
while b <= a:
print(b)
b += 1
|
4c1f2fa0bc29eea95dd24ac38d74c3ff1f2d4c9a | tkim92/Python-Programming | /school_exercies/exercise7/ex7d.py | 320 | 3.875 | 4 | def spaceit(istr):
if len(istr) == 1:
return istr[0]
else:
if istr[0] == istr[1]:
return istr[0] + " " + spaceit(istr[1:])
return istr[0] + spaceit(istr[1:])
def main():
astr = input("Enter your string: ")
print(spaceit(astr))
if __name__ == "__main__":
main()
|
0823571a481601125862bdfd664208894f44e6f2 | alehpineda/python_morsels | /window/window.py | 423 | 3.671875 | 4 | from collections import deque
from typing import Iterable
def window(iterable: Iterable, number: int, *, fillvalue=None) -> Iterable:
if number == 0:
return
iterator = iter(iterable)
current = deque(maxlen=number)
for _ in range(number):
current.append(next(iterator, fillvalue))
yi... |
c76ac9be325d6c9da32fef1299a1550f12bcfd61 | vernittyagi/General-Algorithms | /heap_sort.py | 723 | 4.0625 | 4 | def heapify(arr,n,i):
largest = i
l=2*i+1
r=2*i+2
if l<n and arr[i]<arr[l]:
largest = l
if r<n and arr[largest]<arr[r]:
largest = r
if largest!=i:
arr[i],arr[largest]=arr[largest],arr[i]
heapify(arr,n,largest)
def heapsort(arr):
n = len(arr)
#building a m... |
7535651e5bb29ff2ce61337c532209881c8f1432 | kamil-g-cc/pb-sep-game-inventory | /game_inventory.py | 928 | 3.515625 | 4 |
# This is the file where you must work.
# Write code in the functions (and create new functions) so that they work
# according to the requirements.
def display_inventory(inventory):
"""Display the contents of the inventory in a simple way."""
pass
def add_to_inventory(inventory, added_items):
"""Add to... |
1713d47015d16934fa8da366fc680291a696d10a | timothypearson/learning-python | /training/course_1/strings.py | 1,614 | 4.34375 | 4 | # Learn python - Full Course for Beginners [Tutorial]
# https://www.youtube.com/watch?v=rfscVS0vtbw
# freeCodeCamp.org
# Course developed by Mike Dane.
# Exercise: Strings / Variables / Functions
# Date: 28 Aug 2021
print(" /|")
print(" / |")
print(" / |")
print("/ |")
# Define variables
character_name = "Tom... |
24eb7de70e9de46a676ff215ddd1d881c82921bd | vikas972/Analytics_course | /Numpy_Pandas_MatplotLib/m1yi6ymury/574_m4_codes_v3.1/DS_mod4/slide_92.py | 111 | 3.53125 | 4 | import numpy, matplotlib.pyplot as plt
x = numpy.arange(0, 5, 0.01)
plt.plot(x, [x1**2 for x1 in x])
plt.show() |
98eac4d6ffb531bd3cd28b90f8da386b7e0c60d9 | Hemie143/realpython | /chp12 - SQL Database Connections/12-163.py | 439 | 4.25 | 4 | import sqlite3
# get person data from user and insert into a tuple
first_name = input("Enter your first name: ")
last_name = input("Enter your last name: ")
age = int(input("Enter your age: "))
person_data = (first_name, last_name, age)
# execute insert statement for supplied person data
with sqlite3.connect('test_da... |
494f0b95593ee5ad226078b1a6f985b82c01b100 | xsky21/bigdata2019 | /01_jump to python/CHAP07/2_Regular_Expression_Practice/q6.py | 408 | 3.578125 | 4 | # 숫자 0 혹은 알파벳 b 여러 개가 알파벳 a 뒤에오는 문자열을 찾는 파이썬 프로그램을 만들어라
import re
def matching(answer):
p = re.compile("ab{2,3}")
m = p.search(answer)
print(m)
matching("abbbb")
matching("abb")
matching("a")
matching("abbb")
#여기선 b가 세 개일 때, b 세개를 출력해주지만. b2개를 출력시키고 싶다면 |를 써야된 |
cb19309a462426773e59faee613fbbaf7fb96772 | abhising10p14/SciCalcy | /Gauss_Elimination/input.py | 1,725 | 3.96875 | 4 | from tkinter import *
from easygui import*
from numpy import *
import math
import gaussian as xy
# http://www.python-course.eu/tkinter_layout_management.php -> Important source to learn
# This integer box takes the input of the order of the matrix, where the default value is set to null
n = integerbox(msg="In... |
420a34b1b9ded231a538ca1b0d43b91f758ca8de | Kadzup/neironetwork | /function.py | 1,573 | 3.546875 | 4 | #%%
import numpy as np
def sigmoid(value):
"""Обчислення ф-ції активації"""
return 1 / (1 + np.exp(-value))
def softmax(value):
"""обчислення"""
return np.exp(value)/np.sum(np.exp(value))
def learning(array_vector, nw):
"""Навчання"""
epoch = 0
while epoch < 200:
num = np.r... |
094bee314fc2ff611bd5ace1162d89f68f375bb1 | hitochan777/kata | /atcoder/abc246/B.py | 91 | 3.5 | 4 | A, B = (int(x) for x in input().split())
C = (A ** 2 + B ** 2) ** 0.5
print(A / C, B / C)
|
c36b6c45c3829da8d695b9522db4bed50fff567d | CollinErickson/LeetCode | /Python/160_IntersectionLinkedLists.py | 1,252 | 3.640625 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def __repr__(self):
s = '' + str(self.val)
node = self.next
while node is not None:
s += " -> " + str(node.val)
node = node.next
... |
f935b9737ab8e527973cbf8056629ed61b396962 | susunini/leetcode | /220_Contains_Duplicate_III.py | 2,721 | 3.65625 | 4 | """
As a followup question, it naturally also requires maintaining a window of size k. When t == 0, it reduces to the previous question so we
just reuse the solution.
Since there is now a constraint on the range of the values of the elements to be considered duplicates, it reminds us of doing a range
check which is i... |
47f8446fc929d29e3bc7a95d6b54a0bfc096101c | ashwin4ever/Programming-Challenges | /Cracking the Coding Interview/arr_bst_seq.py | 1,240 | 3.8125 | 4 | #Find all possible
#binary trees with given Inorder Traversal
class Tree:
def __init__(self , val = None):
self.data = val
self.rightChild = None
self.leftChild = None
def preOrder(self , node):
if node is not None:
pri... |
19240f2deff2c2abe0092025a8d4dde816a0346c | wualbert/r3t | /utils/utils.py | 371 | 3.5625 | 4 | import numpy as np
def wrap_angle(theta):
theta %= 2*np.pi
if theta>=np.pi:
return theta-2*np.pi
else:
return theta
def angle_diff(theta1, theta2):
cw = (theta2-theta1)%(2*np.pi)
cw = wrap_angle(cw)
ccw = (theta1-theta2)%(2*np.pi)
ccw = wrap_angle(ccw)
if abs(cw)>abs(cc... |
b21554408e75071fc1133481f49b9fbc6b3e2ed3 | psukhomlyn/Hillel_PythonAQA | /HW4/HW4-4.py | 674 | 4.1875 | 4 | """
4 у вас есть список имен переменных в формате кэмел кейс ["FirstItem", "FriendsList", "MyTuple"].
преобразовать его в список имен переменных для пайтона в формате снейк кейс ["first_item", "friends_list", "my_tuple"]
"""
camel_case = ["FirstItem", "FriendsList", "MyTuple"]
snake_case = []
for word in camel_case:
... |
8eb78b3389db2d408bb6d7dc3edcc71a1c3d6e2f | Thorgalm/bootcamp_2018 | /zadanie_7.py | 302 | 3.9375 | 4 | x = float(input("Podaj liczbę:"))
print(x % 2 == 0 and x % 3 == 0 and x > 10 or x == 7)
# ctrl+alt+L sktót do formatowania zgodnie ze standardem PEP8, m.in. spacje
# ctrl+/ komentuje i odkomentowuje
# shift +END zaznacza od kursora do konca linii
# ctrl+D kopiuje cała linie
# ctrl+Y usuwa linie
|
5571f233ee020d622e635b5a3acd15ee2bb3de62 | ismayil89/Py_DSA | /DSA/Python/LinkedList/DoublyLinkedList.py | 7,333 | 3.921875 | 4 | __author__ = "Mohamed Ismayil"
__credits__ = ["William Fiset"]
__version__ = "1.0"
__maintainer__ = "Mohamed Ismayil"
__email__ = "ismayil.ece@gmail.com"
__status__ = "Prototype"
__date__ = "19-Dec-2020"
import math
class Node:
def __init__(self, data, previous, next):
"""
Constructor: Constructs ... |
a73b412488ac50a3b61f7f666201f5c08418e67d | GutemaG/python-practice | /dataStructure/Stack.py | 517 | 4 | 4 | class Stack:
def __init__(self):
self.stack=[]
def __str__(self):
return str(self.stack)
def Push(self,value):
self.stack.append(value)
return True
def Pop(self):
if len(self.stack)==0:
return "The Stack is Empty"
else:
self.stack.p... |
593682cc22cbd6ac0f8706d521317308fcfd8994 | YOON-JUN-YONG/Python | /Cal.py | 268 | 4 | 4 | a = int(input("enter First number: "))
b = int(input("enter Second number: "))
result = a + b
print (a, "+" ,b, "=", result)
result = a - b
print (a, "-" ,b, "=", result)
result = a * b
print (a, "*" ,b, "=", result)
result = a / b
print (a, "/" ,b, "=", result)
|
52b439993166c9f5e3e0dd090e5b5626ed1d32fb | leonardo185/Python_ObjectOrientedProgramming | /object_param.py | 281 | 3.578125 | 4 | class Mobile:
def __init__(self, price, brand):
self.price = price
self.brand = brand
#Object as parameter to a function.
def change_price(mobile_obj):
mobile_obj.price = 3000
mob1=Mobile(1000, "Apple")
change_price(mob1)
print (mob1.price)
|
31593e24adde7b1da860702fc2ac00a7168bc78e | newbieeashish/LeetCode_Algo | /2nd_35_questions/PathCrossing.py | 934 | 4.21875 | 4 | '''
Given a string path, where path[i] = 'N', 'S', 'E' or 'W', each representing
moving one unit north, south, east, or west, respectively. You start at the
origin (0, 0) on a 2D plane and walk on the path specified by path.
Return True if the path crosses itself at any point, that is, if at any time
you are ... |
7b3d7af2a8ca27f53091b0995924805e7aa08e4f | sagar877/game | /game.py | 975 | 3.984375 | 4 | import random
print("Welcome to the Snake,Water,Gun game.")
def gameWin (comp,you):
if comp==you:
return None
elif comp=="s":
if you=="w":
return False
elif you=="g":
return True
elif comp=="w":
... |
243b7b3f7656bc4f244a1dd77080665962a67afb | freelife1191/Python-CodingTest-Note | /ExhaustiveSearch/소수찾기2.py | 272 | 3.59375 | 4 | import math
def solution(n):
n = n + 1
is_primes = [True] * n
max_langth = math.ceil(math.sqrt(n))
for i in range(2, max_langth):
if is_primes[i]:
for j in range(i+i, n, i):
is_primes[j] = False
return [i for i in range(2, n) if is_primes[i]]
|
41bbdc722461329da21d78258b46778cf3e2b780 | ZhiCheng0326/LeetCode-Practices | /solutions/206.Reverse Linked List.py | 835 | 4 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
# Method 1: stack
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
ptr = head
stack = [None] #important!
while ptr:
stack.appe... |
7a12ad84b2d200a1ef567ce4a22cd4074642184e | mofostopheles/python_art_book | /dist/scripts/pattern_023.py | 1,143 | 3.65625 | 4 | # -*- coding: utf8 -*-
"""
• Using matplotlib to display number patterns.
• Author: Arlo Emerson <arloemerson@gmail.com>
• License: GNU Lesser General Public License
"""
from decimal import Decimal
import math
import matplotlib.pyplot as plt
import lib.common as _common
def pattern_023():
# Simple pat... |
4e1e9a419b6b12e3110e8e11154601f20cebcd1f | TheThornBirds/pythonworker | /OOP/useSlots.py | 1,294 | 3.859375 | 4 | class Student(object):
pass
s = Student()
s.name = 'Michael' #动态给实例绑一个属性
print(s.name)
def set_age(self, age): #定义一个函数作为实例方法
self.age = age
from types import MethodType
s.set_age = MethodType(set_age,s) #给实例绑定一个方法
s.set_age(25) #调用实例方法
print(s.age) #测试结果
def set_score(self, score):
self.score = s... |
7a6a0bfc2ce55fa1229d3cc438d1611329c76dc0 | tangentstorm/pirate | /pirate/PirateTest.py | 5,036 | 3.5 | 4 | import unittest
import pirate
import os.path
def trim(s):
"""
strips leading indentation from a multi-line string.
(for dealing with multi-line indented strings)
"""
lines = str(s).split("\n")
# strip leading blank line:
if lines[0] == "":
lines = lines[1:]
# strip indendation:
... |
41a9fc882a63f9bdfa188713ff5fa6f96a5ad620 | wangliangguo/algorithm022 | /Week_03/78.子集.py | 842 | 3.625 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
#@Author :wangliangguo
#@time : 20-12-31 下午1:12
# class Solution:
# def subsets(self, nums: List[int]) -> List[List[int]]:
# ans = [[]] # 迭代法
# for num in nums:
# subsets = []
# for suba in ans:
# new_suba = suba +... |
3a495b8a0c16abdbe4a60ba8decdc6d7cca55dfb | LenHu0725/02_JZOffer-Notebook | /题目33:二叉搜索树的后序遍历序列.py | 1,643 | 3.671875 | 4 | # -*- coding:utf-8 -*-
"""
名称:二叉搜索树的后序遍历序列
题目:输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。
如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
测试:功能测试:输入后序遍历序列对应一棵二叉树,包括完全二叉树,所有节点都没有左/右子树的二叉树、只有一个节点的二叉树;
输入的后序遍历序列没有对应一棵二叉树。
特殊测试:指向后序遍历序列的指针为nullptr指针。
"""
# 解题思路:递归,数组最后必为根节点,左子树根节点值<根节点值<右子树根节点值
class Solution:
def VerifySe... |
12c04a58a76975de7919a3ab5510701bb7576414 | tanyavasilkova/lesson3 | /old_dz/dz5/dz5.vasilkova.py | 12,461 | 3.578125 | 4 | import json
def main():
print('Выберите действие:\n\
1. Зарегистрироваться\n\
2. Войти')
deistvie = str(input('Введите 1 либо 2: '))
if deistvie == '1': registration();
elif deistvie == '2': auth()
elif deistvie != '1' or deistvie != '2':
print('Вы ввели неверный симво... |
e053b56d72440597c10ef69aaf5cb937c92858ab | mkjois/edu | /cs61a/hw3/hw3.py | 8,726 | 3.953125 | 4 | """61A Homework 3
Name: Manohar Jois
Login: cs61a-3u
TA: Allen Nguyen
Section: 203
"""
from doctest import run_docstring_examples
test = run_docstring_examples
def str_interval(x):
"""Return a string representation of interval x.
>>> str_interval(interval(-1, 2))
'-1 to 2'
"""
ret... |
0b961b4692f7a643d580b838a167ab95d0169d58 | FabioRosado/100DaysOfCode | /Part II/day-11/naive-string-matching-algo.py | 942 | 3.75 | 4 | '''
Pseudocode:
naive_string_matcher(text, pattern):
n = text.length
m = pattern.length
for s in range (n - m)
if pattern[1..m] == text[s + 1 .. s + m]
print "Pattern occurs with shift" s
'''
text1 = "acaabc"
pattern1 = "aab"
text2 = "000010001010001"
pattern2 = "0001"
def naive_string_matcher(text, ... |
152220156a3105897ff4e23975affc87247bbd6c | DaeYeong97/e_on | /assignment4.py | 582 | 3.59375 | 4 | def bubble_sort(x): #bubble_sort 함수
for i in range(0,len(x)-1,1): #입력받은 수 길이-1(0부터 세기때문), 1씩 증가
for j in range(0,len(x)-1,1):#입력받은 수 길이-1, 1씩증가
if x[j] > x[j+1]: #(입력기준) 왼쪽 숫자가 크면
x[j], x[j+1] = x[j+1], x[j] # 스위치
return x #반환값
a = list(map(int,input("숫자를 입력해주세요").split())) ... |
de9741b35f42d67a2d7c5c11052280eb9d460a24 | ajay016/Dataquest-1 | /Python for Data Science Intermediate/oop classes.py | 1,879 | 4.59375 | 5 | # OOP practice / classes
# learn about OOP by emulating the append method
class NewList(DQ): # use DQ for dataquest checking
pass
newlist_1 = NewList()
print(type(newlist_1))
class NewList(DQ):
def first_method():
return "This is my first method"
newlist = NewList()
class NewList(DQ):
def first_... |
182f757467857114119abe08fca637c904b83197 | budavariam/advent_of_code | /2017/12_1/code.py | 1,935 | 3.75 | 4 | """ Advent of code 2017 day 12/1 """
from argparse import ArgumentParser
import re
from collections import deque
class Node(object):
""" Node of the network """
def __init__(self, name, connections):
""" Constructor of the node """
self.name = name
self.connections = [] if not connectio... |
9b37e576784dc8678d136ea333bf14c3a041891b | giovannyortegon/holbertonschool-interview | /0x03-minimum_operations/0-minoperations.py | 502 | 4.0625 | 4 | #!/usr/bin/python3
""" Minimum Operations """
def minOperations(n):
""" minOperations
n: (int) number to operate
Return
ops: (int)number of operations.
"""
swap = 0
ops = 0
add = 1
if n <= 1 or type(n) is not int:
return 0
else:
while add < n:
... |
3e49a2854d86516aa2d49bb1a762a614062ed87d | mukund1985/Python-Tutotrial | /Core_Python/43. Higher Order Function Filter Map Reduce/3. map1.py | 232 | 3.6875 | 4 | a = [10, 20, 30, 40, 50]
# Without Lambda
def inc(n):
return n+2
result = list(map(inc, a))
print(result)
print(type(result))
# With Lambda
result = list(map(lambda n: n+2, a))
print(result)
print(type(result))
|
0434d144074e1d990ed919fb5c604a8ddfda0566 | frclasso/revisao_Python_modulo1 | /cap05-operadores-basicos/extras/boolean-operators3-not.py | 288 | 4.21875 | 4 | #!/usr/bin/env python3
#Exemplos utilizando operadores booleanos (and, or, not, in, not in, is , is not).
a = True
b = False
x = ('bear', 'bunny', 'tree', 'sky','rain')
y = 'bear'
if not b: #Not b(False) = True
print('Expression is true')
else:
print('Expression is false')
|
70df532d8d36aeda93d614495bb78224eefb811e | croysdaa/osu-cs362-s21 | /password.py | 195 | 3.5625 | 4 | import random
usernum = input("Enter a number: ")
i = 1
password = random.randint(1,10)
while i < int(usernum):
password = str(password) + str(random.randint(1,10))
i = i + 1
print(password)
|
ea1244d3271b49a0e1015dbb59a976707b39a3f3 | isabella0428/Leetcode | /python/445.py | 913 | 3.6875 | 4 | class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
l1_list, l2_list = [], []
while l1:
... |
4fe88464a48515e02934922fc7f475b0408e3bcf | Prerna99-star/clustering-algorithms | /Kmeancluster.py | 1,537 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Apr 30 01:19:51 2020
K Mean clustering
"""
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#Importing the dataset
dataset = pd.read_csv('Mall_Customers.csv')
X = dataset.iloc[:, [3, 4]].values
# Using the Kmean method to find the optimal no. of clust... |
69bbdbec97ad33c4ce6818cb1742179ebde41b00 | khoIT/10xclub-hw | /inclass-activities.py | 1,944 | 4.375 | 4 |
''' SET A
1. Unique items
Write a function that takes in an array. It should return a new array
containing only the elements that were unique in the original array.
For example:
ary = [1, 5, 5, 7, 16, 8, 1, 8]
unique = unique_items(ary)
unique # => [7, 16]
'''
from sets import Set
def unique_items(arr):
co... |
d373cfd2f97153ca74e0301f36b9932c76565320 | YeseniiaBorzova/Python_labs | /Lab1.2/Third_Task.py | 267 | 3.609375 | 4 | import numpy as np
height = np.array([68,71,72,75,75,75,68,74,78,71])
weight = np.array([155,185,185,200,225,225,220,160,205,235])
height = height/39.37
weight = weight/2.205
bmi = weight/(height*height)
print("All indexies: \n",bmi)
print("BMI < 21: ",bmi[bmi<21])
|
e2095672543023dd3151ecd95cfd287d8d509b48 | SigitaD/python_cash | /cash.py | 924 | 3.671875 | 4 | from cs50 import get_float
def main():
# reikiama graza paimama is get_change f-cijos.
change = get_change()
# graza paverciama centais ir suapvalinama.
cents = round(change * 100)
# monetu counteris nustatomas nuliui. Kiekviena karta ivykus sekmingam loopui, monetu counteris padides +1.
coin... |
5b9e90c1c6df0fdc36e56310144bd1ea2e612c8c | Nasim992/python | /6.Dictionary.py | 690 | 4.1875 | 4 | # In dictionary each value should contain key
# Declaring a dictionary A = {} or A = dict()
A = {'name': 'Nasim Hossain','email':'mdnasim6416@gmail.com','phone':'01755706416'}
print (A['name']) # Nasim Hossain
A['name'] = 'Md.Nasim Hossain'
print(A['name']) # Md.Nasim Hossain
B = {'hometown':'Kushtia,Jessore,Dhak... |
6741a7376d92cf3098efc8fc5241aa8bfd08f410 | ViniciusGranado/_studies_Python | /_exercises/exercise029/exercise029.py | 783 | 4.03125 | 4 | def validate_number(str_number):
is_valid = True
if not (str_number.isnumeric()) or int(str_number) < 0:
is_valid = False
return is_valid
def get_number():
is_number_valid = False
while not is_number_valid:
velocity_str = input('Qual é a velocidade atual do carro em Km/h? ')
... |
81ff6ede20dd971f4fa2937196305ad524cf44e9 | Amos-zq/dresscode | /rect_tools.py | 1,162 | 3.984375 | 4 | import numpy as np
import cv2
'''
Our rectangle notation convention is (x,y,w,h).
With (x,y) top left corner.
The following functions are some useful routines to
manipulate rectangles.
'''
def get_rect_img(img):
return (0,0,img.shape[1],img.shape[0])
def get_img_crop(img,crop):
x,y,w,h = cro... |
adf7162521698ec23cafcbdc822c93bbd6220243 | vishalpanwar/2048-Game | /Matplotlib/Unix_time.py | 3,479 | 3.59375 | 4 | import matplotlib.pyplot as plt
import numpy as np
import urllib
import matplotlib.dates as mdates
#matplotlib has its own date converter or date handler as mdates
#urllib module provides a high-level interface for fetching datya across the world wide web. In particular,
#the urlopen() function is similar to the bui... |
899002760702df2c8d6e00f6e59766c617882c4b | bkruszewski/iSAPython3 | /day4/petla_for1.py | 670 | 3.734375 | 4 | # drukujemy liczby na ekranie
for liczba in range(30, 43765, 4):
print(liczba * 343)
wyraz = "konstantynopolitanka"
# bierzemy każdą literę i coś z nią robimy
for litera in wyraz[::-1]:
print(litera.upper())
# tutaj nic nie robimy z otrzymanym elementem kolekcji
# wykorzystujemy długość kolekcji do wykonani... |
0f82ea6fcd4662322f411d32f1491a34db66803a | hristoivanov/euler | /problem19.py | 319 | 3.765625 | 4 | import calendar
import time
start=time.time()
c=calendar.TextCalendar(calendar.MONDAY)
the_ans=0
for x in range(1901, 2001):
for y in range(1,13):
aux=c.itermonthdays2(x,y)
for z in aux:
if z[0]==0:
continue
if z[1]==6:
the_ans+=1
break;
print 'Answer: '+`the_ans`+' Time: '+`time.time()-start`
|
f99ed6d6db73e668d7c3d32f449c8be4dfff4571 | ciceroroberto2019/PythonExercicios | /ex011.py | 259 | 3.578125 | 4 | print('=' * 20, 'Exercicio 011', '=' * 20)
l = float(input('Informe a largura da parede: '))
a = float(input('Informe a altura da parede: '))
m4 = l * a
print('Sua parede tem {:.3f} m² e precisara de {:.3f} litros de tinta para pintar ela'.format(m4, m4/2))
|
3de2c4eefc75bf7aa9bf04d55a32448a069b845b | waveboys/Leetcode | /Integer_to_Roman.py | 3,075 | 4.21875 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
#@Time : 2020/3/10 上午11:09
#@File : Integer_to_Roman.py
import enum
"""
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D ... |
a3a9ecf8570951969462ae8779186cc7776d369c | siddharthadukkipati/cspp1-assignments | /m5/p1/perfect_cube.py | 374 | 3.953125 | 4 | '''Write a python program to find if the given number is a perfect cube or not'''
def main():
"""Perfect cube"""
s_v = int(input())
guess_v = 0
while guess_v**3 < s_v:
guess_v += 1
if guess_v**3 == s_v:
print(str(s_v)+" is a perfect cube")
else:
print(str(s_v)+" is not a... |
5b4c01abe97d6a3257d924999c21e5a2c1dbaf95 | markmuetz/cosmic | /cosmic/fourier_series.py | 5,158 | 3.75 | 4 | """Provides class and functions for performing Fourier Series (Harmonic) analysis.
See e.g. https://en.wikipedia.org/wiki/Fourier_series for formulae used."""
import numpy as np
import scipy.integrate as integrate
from typing import Iterable, List, Tuple
class FourierSeries:
"""Represent 1D fourier series over a... |
be110e01c8cf30fa6129f623caf5714550e5e64b | vdalonso/cse-130--PA3 | /tokenizer.py | 820 | 3.609375 | 4 | import sys
#print("Number of arguments:" + str(len(sys.argv)))
if len(sys.argv) != 2:
print("incorrect number of parameters \nusage: $ python tokenizer.py 'FILENAME' ")
quit()
grammer = {
chr(92): "LAMBDA",
chr(46): "DOT",
chr(32): "APPLICATION",
chr(40): "L_PARENTHESIS",
chr(41): "R_PARENT... |
3f484f23ddc9eafcac94aa04327342b0f6ddd393 | Orderlee/tjoeun | /pycharm/ch05/ex14.py | 462 | 3.84375 | 4 | import random
for i in range(10):
#실수형 난수: 0.0~1.0 미만인 값
print(random.random(),end='')
#정수형 난수 randint(start,end)
print(random.randint(1,10),end='')
print(random.randint(10,30))
result=[]
for i in range(10):
result.append(random.randint(1,10))
print(result)
#무작위로 섞음
random.shuf... |
88d734f9240a33b7471a3318898f26cc3c4c907d | sumanth-vs/leetcode | /14.py | 1,443 | 3.515625 | 4 | <<<<<<< HEAD
class Solution:
def longestCommonPrefix(self, strs):
mtStr = ""
if len(strs) == 0:
return ""
else:
lp = strs[0]
for i in strs:
if len(i) < len(lp):
lp = i
print('initailly lp = ', lp)
... |
457851fa9fa84177a483bec8188d708345281deb | Huijuan2015/leetcode_Python_2019 | /426. Convert Binary Search Tree to Sorted Doubly Linked List.py | 4,822 | 3.984375 | 4 | """
# Definition for a Node.
class Node(object):
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
"""
class Solution(object):
def treeToDoublyList(self, root):
"""
:type root: Node
:rtype: Node
"""
... |
3bbc3a13b7982864aebfe573fb91b6fa1f6aa731 | viniielopes/uri | /iniciante/1006.py | 557 | 3.953125 | 4 | pesonumero1 = 2
pesonumero2 = 3
pesonumero3 = 5
numero1 = input()
numero2 = input()
numero3 = input()
multiplica_numero1 = float(numero1) * pesonumero1
multiplica_numero2 = float(numero2) * pesonumero2
multiplica_numero3 = float(numero3) * pesonumero3
somapesos = pesonumero1 + pesonumero2 + pesonumero3
somanumeros = m... |
e6ca347a46466b62d1a3a4462cd91a4f1b62b10b | MyChoYS/K_TIL | /python/PYTHONexam/day4_func/funcTest8.py | 167 | 3.765625 | 4 | def add(num1, num2) :
print(num1 + num2)
r1 = add(10, 20)
v1 = 100; v2 = 200
r2 = add(v1, v2)
print(r1)
print(r2)
print(add(1000, 2000))
print(1+add(1000, 2000))
|
0be290a04698a43eecef1aad8fe3ce5e162c0865 | jenniferehala/bank_account | /bank_acct.py | 990 | 3.796875 | 4 | class BankAccount:
def __init__(self, int_rate = 0.01, balance=0):
self.int_rate = int_rate
self.balance = balance
def deposit(self,amount):
self.balance += amount
# print(self.balance)
return self
def withdraw(self,amount):
self.balance -= amount
# p... |
9d7faa0ce5e83355abd82016ab5bcc5ef7ff517a | Amaayezing/ECS-10 | /Investments/investments.py | 7,814 | 4.09375 | 4 | #Maayez Imam 10/18/17
#Investments Program
import random
import math
def investments():
loan_amount = float(input("Enter how much money you owe in loans: "))
while loan_amount < 0:
loan_amount = float(input("Enter how much money you owe in loans: "))
interest_rate_loan = float(input("Enter the an... |
0c2715b12388f24a8890cd7503abd0a3f6673a53 | paulosergio-dev/exerciciopython | /questao12.py | 575 | 3.953125 | 4 | #12. Fazer um algoritmo para calcular a contribuição ao INSS, IR e a associação
# de funcionários a partir do salário bruto, que é dado de entrada.
# As taxas sobre o salário bruto são as seguintes:
#• INSS - 10%
#• IR - 25%
#• Sindicato - 0.5 %
# O programa deve imprimir as contribuições e o valor do salário líquid... |
bcbb765aca7cf455f51420e3c38ea7a0c2580c7a | calmwalter/python_homework | /lab2/2.1.py | 459 | 3.578125 | 4 | lst=input().split(" ")
lst1=[]
mean=0
deviation=0
for x in lst:
lst1.append(eval(x))
mean=mean+eval(x)
mean=mean/len(lst1)
for x in lst1 :
deviation=deviation+(x-mean)**2
deviation=(deviation/len(lst1))**0.5
lst1.sort()
l=len(lst1)
print("l:",l)
if l%2==0:
median=(lst1[len(lst1)//2-1]+l... |
4020a5a7481a21ee2b780d7f33a441d2afd275a0 | nokello2002/Python-Class | /Nicholas_Trials_4.py | 3,157 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
def absolute_value(number):
"""This function returns the absolute
value of the entered number"""
if number >= 0:
return number
else:
return -number
print(absolute_value(4))
print(absolute_value(-6))
print(""... |
de3f316ae87bafec2acdc686fe081df7c86fd862 | saurabhk7/chess-self-play | /chess/ChessLogic.py | 8,772 | 3.96875 | 4 | from pythonchess import chess as chess
import numpy
'''
Author: Eric P. Nichols
Date: Feb 8, 2008.
Board class.
Board data:
1=white, -1=black, 0=empty
first dim is column , 2nd is row:
pieces[1][7] is the square in column 2,
at the opposite end of the board in row 8.
Squares are stored and manipulated as... |
8360b81992c2f6c7dca82c41550c8a923c344757 | Crisscrisis/kaikeba_cv | /week1_2_1/homework_week1.py | 6,590 | 3.71875 | 4 | '''
author : Lucas Liu
date : 2020/1/18
description : week 1 homework, low level image process method, including crop, color shift,
rotation, perspective transform, and related testcase
'''
import cv2
import matplotlib.pyplot as plt
import numpy as np
import random
'''
description:
... |
72f38faf6389a272fa6418743424b05673c2e1cf | rukipgus/Algorithm | /Baek_2920.py | 176 | 3.59375 | 4 | a = input()
b = "12345678"
c = "87654321"
a = a.replace(" ","")
if a == b:
print("ascending")
elif a == c:
print("descending")
else:
print("mixed") |
de904b127ec841c146982d4e9b97c22d7693486e | kevinszuchet/itc-fellows-part-time | /lesson_3/snake/snake.py | 1,448 | 4.125 | 4 | """Program that tries to beat the cyber monster."""
from monster import substitution_cipher_dict, ciphered_message
def decipher_message(monster_message, decipher_dict):
"""
Given a ciphered message and a dictionary to decode characters,
it resolves the monster puzzle and returns the deciphered message.
... |
9a0350f5768f6ed8790019c5a0b2579a3ca8da38 | WHKcoderox/microbit-template | /flappy_bird.py | 2,654 | 3.90625 | 4 | from microbit import *
import random
display.scroll("Get ready...")
# Game constants - These variables have capitalised names to suggest that they are not supposed to be edited. (They store constants)
DELAY = # ms between each frame
FRAMES_PER_WALL_SHIFT = # number of frames between each t... |
7111e797d4a9ef845c269e27e023ff32f26afee1 | BoltzBit/LP | /Exercicios/ex09-3f.py | 174 | 3.78125 | 4 | #calculo da area do circulo
import math
raio = float(input('Insira o valor do raio: '))
area = math.pi*pow(raio,2)
msg = 'Area do circulo é {}'
print(msg.format(area))
|
38636c51c92b83ae49477acce1561eda264ba38b | pecata83/soft-uni-python-solutions | /Programing Basics Python/Conditional Advanced Exercise/05.py | 802 | 3.8125 | 4 | budget = float(input())
season = input()
destination = ""
accommodation_type = ""
percentage_spend = 0
if budget <= 100:
destination = "Bulgaria"
if season == "summer":
percentage_spend = 0.3
accommodation_type = "Camp"
elif season == "winter":
percentage_spend = 0.7
acc... |
d9810fa8c4161d16d6a355b17e52ced39518fa3c | ejmurray/python_workout_solutions | /chapter_003_lists_and_tuples/e09_even_odd_sums.py | 471 | 4.125 | 4 | """
Write a function that takes a list or tuple of numbers. Return a two-element list, containing (respectively)
the sum of the even-indexed numbers and the sum of the odd-indexed numbers. So calling the function as
even_odd_sums([10, 20, 30, 40, 50, 60]), you’ll get back [90, 120].
"""
def even_odd_sums(sequence):
... |
9418b2cda46939e9a9160b9793c423a71c3a160e | btrif/Python_dev_repo | /Courses, Trainings, Books & Exams/Lynda - Python 3 Essential Training/13 String Methods/strings_03_splits_joins.py | 605 | 3.96875 | 4 | #!/usr/bin/python3
# strings.py by Bill Weinman [http://bw.org/]
# This is an exercise file from Python 3 Essential Training on lynda.com
# Copyright 2010 The BearHeart Group, LLC
def main():
s = 'this is a string of words'
print(s.split()) #split each word, after space
words = s.split()
pr... |
24310d6d44a226ab743e23e3543d77f54e159987 | jkgiesler/project-euler-solutions | /shortscripts.py | 506 | 3.890625 | 4 | '''
look for unique powers
a**b
2--100 a
2--100 b
'''
lst=[]
for a in range (2,101):
for b in range(2,101):
print(a)
lst.append(a**b)
z=set(lst)
print(len(list(z)))
'''
fifth powers
Find the sum of all the numbers
that can be written as the sum
of fifth powers of their digits.
'''
cond=True
s... |
4eb4b80b4de1307aeae8b2e9370ebbe01b8fee40 | chenxu0602/LeetCode | /169.majority-element.py | 1,423 | 3.765625 | 4 | #
# @lc app=leetcode id=169 lang=python3
#
# [169] Majority Element
#
# https://leetcode.com/problems/majority-element/description/
#
# algorithms
# Easy (58.56%)
# Likes: 3348
# Dislikes: 224
# Total Accepted: 668.3K
# Total Submissions: 1.1M
# Testcase Example: '[3,2,3]'
#
# Given an array of size n, find the ... |
86e1cc5d64cc24b07ff8172d51991572381391f9 | Yobretaw/AlgorithmProblems | /EPI/Python/Strings/7_12_implementUnixTailCommand.py | 775 | 4.09375 | 4 | import sys
import os
import re
import math
"""
============================================================================================
The UNIX 'tail' command displays the last part of a file. For this problem, assume that tail
takes two arguments - a file name, and the number of lines, starting from ... |
950663c4bf01b9dc3a3f65b458361397a173ea1b | llenroc/Python-Data-Structure | /Recursion/countdown.py | 270 | 4.15625 | 4 | def countdown(x):
if x==0:
print("Done");
else:
print(x)
countdown(x-1);
# what if we put the statement below this
# function returns in reverse order so you will get 1, 2, 3, 4, 5
print("wow ", x)
countdown(5); |
e54b5e3a138f25fc3c07c3e5e126e911a2370d6e | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/difference-of-squares/3f33aa5696624402b554b67ee9e6442a.py | 325 | 3.765625 | 4 | __author__ = 'agupt15'
def square_of_sum(num):
sum = 0
for i in range(num + 1):
sum += i
return sum * sum
def sum_of_squares(num):
sum = 0
for i in range(num + 1):
sum += i * i
return sum
def difference(num):
return square_of_sum(num) - sum_of_squares(... |
aa72d6314c8e4a081d9507017fa6c5f8191fd555 | codingdojotulsajanuary2019/Skylar_M | /Python_Stack/python/data_structures/singly_linked_lists/server.py | 1,067 | 4.1875 | 4 | def print_values(self):
runner = self.head
while (runner != None):
print(runner.value)
runner = runner.next # set the runner to its neighbor
return self # once the loop is done, return self to allow for chaining
def add_to_back(self, val):
... |
2badcdcf683ae735cf1a936c7d723443d6d27eea | juferafo/spark-playground | /spark-sql/sql.py | 2,550 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
This script is intended to be used to test Spark SQL functionalities
"""
# importing spark and other libraries
from pyspark.sql import SparkSession
spark = SparkSession\
.builder\
.appName("SparkExampleSQL")\
.getOrCreate()
csv_path = "./flights/departuredelays.csv"
df = (spa... |
2cfd27b0dd4921de02791d83992943e261da99e0 | MattPhillips1/1531-Tutorials | /wk8/travelGood.py | 465 | 3.8125 | 4 | from abc import ABC, abstract_method
class Transport(ABC):
@abstract_method
def move(self):
pass
class Car(Transport):
def move(self):
print("car moving..")
class Bike(Transport):
def move(self):
print("bike moving..")
class Traveller():
def __init__(self, mode_travel)... |
b751481c7e9d39f7f9538e69e9bec253954a3556 | sahitya-pavurala/FF_assignment | /Question2.py | 406 | 4.28125 | 4 | import re
def convert(input_string):
"""
Method to convert string to int/float
if it can be converted
:param input_string: string input
:return: float/int value of input_string
"""
if re.match("^\d+?\.\d+?$", input_string) is not None:
return float(input_string)
elif re.match(r... |
503d70b4648847919c9741e6e8891a6561161d28 | LucasLudueno/page-rank | /URLResolver.py | 3,134 | 3.609375 | 4 | import re
import json
import numpy as np
import BeautifulSoup
from urlparse import urlparse
from PageRank import PageRank
class URLResolver:
""" Module to resolve urls into a html content and link them with other into a url graph"""
""" Given a map of urls like: { "0": { "url": "http://www.google.com/", "con... |
40e0edb3a3a3269815d4a4f47285f24e07a8ccd7 | shunw/python | /pygame/snake.py | 2,004 | 3.796875 | 4 | '''
this game is for memory of the eating snake in nokia, classic game
'''
import pygame
import enum
black = (0, 0, 0)
white = (255, 255, 255)
bright_green = (0, 255, 0)
green = (0, 200, 0)
display_width = 800
display_height = 600
snake_one_block = 10 # this means after the snake eat one bean, it wil... |
27dd25f1516137c9b0ba5d76834de76f4cd59b1b | huangshaoqi/programming_python | /XDL/python/Part_1/Day09/buy.py | 2,048 | 3.84375 | 4 | Products = [
["iphone", 5000],
["bike", 800],
["ipad", 6000],
["computer", 8000]
]
cost = 0
buy_product = set()
top_info = "超市".center(50, "=")
print(top_info)
for num, product in enumerate(Products):
print(num + 1, product[0], product[1])
button_info = "=" * len(top_info)
print("输入0退出")
print(butt... |
2ad81a15d05845fbd02577e90c625ac0039e93ef | missionmars/diceroll | /dice.py | 433 | 3.78125 | 4 | import random
from time import sleep
def lets_roll():
print "1 - 10 How hard do you want to roll?"
roll_speed = raw_input()
dice_roll = random.randint(1,int(roll_speed))
for x in range(dice_roll):
print 'Dice rolling...'
sleep(1)
if x == dice_roll-1:
print 'Dice landed on %s' % (random.randint(1,6))
l... |
f2c129d1d7191a29b3e6d54e415d48ae4942bef0 | TiroLiroLD/DataStructureCourse | /app/ArvoreBinariaBusca.py | 1,266 | 3.71875 | 4 | class No:
def __init__(self, valor):
self.valor = valor
self.esquerda = None
self.direita = None
def mostra_no(self):
print(self.valor)
class ArvoreBinariaBusca:
def __init__(self):
self.raiz = None
self.ligacoes = []
def inserir(self, valor):
... |
79b5fb958477af1f654a1ef9b0ae38e68e455a2a | emanaziz1/Internship-Experience-UK-2021-On-Demand- | /src/video_player.py | 14,872 | 3.75 | 4 | """A video player class."""
from .video_library import VideoLibrary
from .video_playlist import Playlist
import random
class VideoPlayer:
"""A class used to represent a Video Player."""
def __init__(self):
self._video_library = VideoLibrary()
self.current_video = []
self.pausing_video... |
a1b445cb50565b5d1ce9f2b25644291723ee3f81 | kickscar/deep-learning-practices | /02.library-fundamentals/01.matplotlib-practices/ex07.py | 414 | 3.8125 | 4 | # figure와 subplot
"""
subplots() 함수 사용
"""
from matplotlib import pyplot as plt
import numpy as np
from numpy.random import randn
fig, splts = plt.subplots(2, 2)
splts[0, 0].plot([2, 4, 5, 6], [81, 93, 91, 97])
splts[0, 1].plot(randn(50).cumsum(), 'k--')
splts[1, 0].hist(randn(100), bins=20, color='k', alpha=0.... |
795af2c2303ad27637426ebfe4d64a941ab1a3ff | adithya-16/18CS128-ADA | /Program7.py | 1,699 | 4.03125 | 4 | from math import factorial
class DirNum:
def __init__(self, num):
self.num = num
self.dir = -1 # right to left
def changeDir(self):
self.dir = -self.dir
def __gt__(self, other):
return self.num > other.num
n = int(input("Enter n: "))
nums = [DirNum(i) for i in rang... |
004e437e2291b635ca1023066bd8abc9bf94cb26 | gbox3d/python_study | /class/ex02.py | 372 | 3.875 | 4 | #%% 클래스 변수
class Ex02Class :
className = "Ex02Class"
def __init__(self, name, age) :
self.name = name
self.age = age
def getClassName(self) :
return self.className
#%%
a = Ex02Class("홍길동", 20)
print(a.className)
print(Ex02Class.className)
# %%
print(type(a))
# %%
if __name... |
d19d3b28765fdfc40b05f7e5cf745eea3954177a | amrkhailr/python_traning- | /week2/persoinfo.py | 344 | 3.796875 | 4 | Name=input('Name : ')
Address=input('Address : ')
City=input('City : ')
State=input('State : ')
ZIP=input('ZIP : ')
Telephone=input('Telephone Number : ')
print(" My Identity")
print("==========")
print('Name', Name)
print('address',Address)
print('City: ',City)
print('Sate: ',State)
print('Zip:',ZIP)
print("Phone:",Te... |
60e3a9a9e14ff972315f50491d61c9600c11dadf | mixassio/example_code | /files_example.py | 1,928 | 3.703125 | 4 | # Открытие файла
f = open('text.txt', 'r')
# 'r' открытие на чтение (является значением по умолчанию).
# 'w' открытие на запись, содержимое файла удаляется, если файла не существует, создается новый.
# 'x' открытие на запись, если файла не существует, иначе исключение.
# 'a' открытие на дозапись, информация добавляется... |
dd39732ba1605b67f7c26f401a4e7fd5d9582a1b | aryan4avj/Python-Stuff | /solved/vending_machine.py | 5,999 | 3.5625 | 4 | #
# File: fileName.py
# Author: your name
# SAIBT Id: your email id
# Description: Assignment 2 - place assignment description here...
# This is my own work as defined by the University's
# Academic Misconduct policy.
from decimal import Decimal # Leave this here! You're going to need it!
import inventory_item
# Glob... |
d62c2ebf019318844d5e32e5ef46af209bb43bed | floracitrus/1531_lab_optional | /tut-errorhandle/errorHandle.py | 771 | 3.953125 | 4 | # define Python user-defined exceptions
class Error(Exception):
"Base class for other exceptions"
pass
class InputTooSmallError(Error):
"Raised when the input value is too small"
pass
class InputTooLargeError(Error):
"Raised when the input value is too large"
pass
# user guesses a number until he/she gets it righ... |
53247583ae30ca0424f0098f0ccc7ddf0832bb09 | Cian747/password-lock | /user.py | 1,009 | 4.0625 | 4 | class User:
"""
Created user class that will store all the data upon login
"""
pass
user_list = [] #List that will contain the user's input details
def __init__(self,first_name,last_name,user_name,password):
"""
Initialized an object with self and the parameters it will u... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.