blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
3543f6f7791c4308f5d4404b123a1277ba6a3624 | devinupreti/coding-problems | /staircase.py | 2,109 | 4.1875 | 4 | # PROBLEM : There exists a staircase with N steps, and you can climb up
# either 1 or 2 steps at a time.
# Given N, write a function that returns
# the number of unique ways you can climb the staircase.
# The order of the steps matters.
# For example, if N is 4, then there are 5... |
3422b9b245725603f8ae1800215010fbf69ae7e9 | SergioJune/leetcode_for_python | /listNode/445.py | 1,522 | 4.0625 | 4 | """
给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
进阶:
如果输入链表不能修改该如何处理?换句话说,你不能对列表中的节点进行翻转。
示例:
输入:(7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 8 -> 0 -> 7
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-two-numbers-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
... |
10de9fb88df1c122de85351a2994cb36910db59c | jackmoody11/project-euler-solutions | /python/p003.py | 606 | 3.703125 | 4 | # Compute the max prime factor of 600,851,475,143
# It is easily verified that 71 is the
# smallest prime divisor, and thus we only need to check
# to sqrt of the number (it is not prime itself)
from math import sqrt
from utils import primes
def compute():
TARGET = 600_851_475_143
PRIMES = primes(int(sqrt(TAR... |
0b0dd8d87a8bfc54baec6e62eb85e2f35c7ec034 | ptkuo0322/SI507_Win2021 | /Project/Final/TestingFIle/testing1.py | 5,705 | 3.75 | 4 | import time
def search_condition():
instruction = '''What kind of filtering condition would you like?
1. filtered by Rating first and ordered by ReviewCount.
2. filtered by Rating first and ordered by Price.
3. filtered by ReviewCount first and ordered by Rating.
4. filtered by ReviewCount first an... |
9b993631cb0fdbbed6e708e5237d173e3d589c07 | HalfMoonFatty/Interview-Questions | /313. Super Ugly Number.py | 1,033 | 4.0625 | 4 | '''
Problem:
Write a program to find the nth super ugly number.
Super ugly numbers are positive numbers whose all prime factors are in the given prime list primes of size k.
For example, [1, 2, 4, 7, 8, 13, 14, 16, 19, 26, 28, 32] is the sequence of the first 12 super ugly numbers given primes = [2, 7, 13, 19] of si... |
c674c17f45773718f2f0990bad1a39954d1890a5 | misizeji/python_study_notes | /class-obj/ClassInherit3More.py | 1,139 | 4.25 | 4 | #!/usr/bin/python3
class People():
name = ''
age = 0
__weight = 0
def __init__(self, n, a, w):
self.name = n
self.age = a
self.__weight = w
def speak(self):
print("%s says that I am %d years old"%(self.name, self.age))
class Student(People):
grade = 0
d... |
d9e8c37c9c2095754700d55bde617b74b0e18bc6 | Psami-wondah/Documents | /Escape Velocity and volume of a planet.py | 462 | 3.875 | 4 | import math
def escapevelocity(r,m):
g=(6.67430 * (10 ** (-11)))
Ve=(((2.0 * g * float(m)) / r) ** (1 / 2))
return Ve
def volume(r):
V=(float((4/3)*math.pi*(r**3)))
return V
r=input('Enter radius of planet in meters:\n')
r=int(r)
m=input('Enter mass of planet in kg:\n')
m=int(m)
... |
670fd7e0a8729ee7e1efece7354c9177ad680ea6 | sandy-reddy/first_repo | /Python Practice Problems/practice_15_debig.py | 155 | 3.578125 | 4 |
sent = "hi my name is sandeep"
sep_sent = sent.split()
print(sep_sent)
print (sep_sent[(len(sep_sent)) - 1])
print (sep_sent.index("sandeep")
)
|
c91d40cc2ed02542fdc750a499177d312d68b919 | VictorTestov/Test1 | /CALCULATOR.py | 1,021 | 4 | 4 | # -*- coding: utf-8 -*-
# програма Калькулятор
print "Вітаємо!"
loop = 1
choice = 0
while loop == 1:
print "Vuberit diy:"
print "1) Dodavannya"
print "2) Vidnimannya"
print "3) Mnojennya"
print "4) Dilennya"
print "5) Zakrutu kalkulyator"
choice = input("Oberit vashy diy:... |
f676e5c9c8c58f968a9471b4ed92f12aba380c47 | bagriffith/AMATH582 | /HW4/code/evaluation.py | 5,304 | 4.125 | 4 | import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
from itertools import combinations
import loadmnist
class NaiveClassifier:
"""A model classifier that randomly guesses a digit.
This was created as a simple test article to make sure the number_confusion
code wor... |
90461670616c6142ab31feb81b6cb1e1f202f12a | xuanxuan-good/MyCode | /之前做过的/680.验证回文字符串-ⅱ.py | 1,897 | 3.609375 | 4 | #
# @lc app=leetcode.cn id=680 lang=python3
#
# [680] 验证回文字符串 Ⅱ
#
# @lc code=start
class Solution:
def validPalindrome(self, s: str) -> bool:
# 最多删除一个字符的情况,是否可以构成回文串
# 1.暴力,逐个删除字符,再遍历判断是否回文O(N^2)
'''
# 2.双指针,当碰到有不相等的时候,删除左边或者右边,再判断剩下的是否是回文
isPalindrome = lambda x : x == x[::... |
8fce955147527ddf889c22b62864de271d9c605a | WWPOL/CV-Pong | /game/app/util/log.py | 835 | 3.6875 | 4 | class Enum(set):
def __getattr__(self, name):
if name in self:
return name
raise AttributeError
def log(message, log_class, log_level):
"""Log information to the console.
If you are angry about having to use Enums instead of typing the classes and levels in, look up how any logg... |
128b09ac61e695997c340171f066c21245b18309 | pimvermeij/huiswerk1 | /NS functies.py | 1,112 | 3.71875 | 4 | def standaardPrijs(afstandKM):
'berkent de prijs door middel van de afstand als float'
if afstandKM < 50:
prijs = afstandKM * 0.8
elif afstandKM <= 0:
prijs = 0
elif afstandKM >= 50:
prijs = 15 + (afstandKM * 0.6)
return prijs
def ritprijs(leeftijd, weekendrit, afstandKM):
... |
4e9e58784f137883eed784e09668e046e7194be3 | Loaye/Math-Series | /test_series.py | 1,953 | 3.609375 | 4 | """Test for math series."""
def test_fib_zero():
'''Test fib function to check value 0 of fibonacci'''
from series import fib
assert fib(0) == 0
def test_fib_one():
'''Test fib function to check value 1 of fibonacci'''
from series import fib
assert fib(1) == 0
def test_fib_two():
'''Tes... |
f9950ff7f3a34f1db57cd8af72f675738725e78a | yred/euler | /python/problem_072.py | 1,750 | 4 | 4 | # -*- coding: utf-8 -*-
"""
Problem 72 - Counting fractions
Consider the fraction, n/d, where n and d are positive integers. If n<d and
HCF(n,d)=1, it is called a reduced proper fraction.
If we list the set of reduced proper fractions for d ≤ 8 in ascending order of
size, we get:
1/8, 1/7, 1/6, 1/5, 1/4, 2/7... |
4d501c25eaf3b639f131e094be63aaa0c157115b | amajung/SI507-Project2 | /movies_tools.py | 332 | 3.53125 | 4 | # Define a class Movie that accepts as constructor input one row of the movies_clean.csv file
class Movie():
def __init__(self, row):
cells = row.strip().split(',')
self.title = cells[0]
self.IMDBrating = cells[14]
def __str__(self):
return "{} | {}<br>".format(self.title, self.... |
737d8fe463b9086c63e4f06b0a36f734f61d954f | denisnmurphy/workingwithdata | /tkinter1.py | 178 | 3.828125 | 4 | import tkinter as tk
from tkinter import *
btn=Button()
btn.pack()
btn["text"]="Hello everyone!"
def click():
print("You just clicked me!")
btn["command"]=click
tk.mainloop() |
e39f3d166a168a3f8bdf1a5243aaedd62bb95dff | pflun/advancedAlgorithms | /generatePossibleNextMoves.py | 822 | 3.8125 | 4 | # -*- coding: utf-8 -*-
# You are playing the following Flip Game with your friend: Given a string that contains only these two characters: + and -, you and your friend
# take turns to flip two consecutive "++" into "--". The game ends when a person can no longer make a move and therefore the other
# person will be the... |
d7df128a101b8149cd77e747034606b2bdac94af | AishwaryalakshmiSureshKumar/DS-Algo | /linkedlist_sorted_merge.py | 1,532 | 3.96875 | 4 | def sortedMerge(head1, head2):
temp = Node(None)
result = temp
if head1 is None:
return head2
if head2 is None:
return head1
while(head1 is not None and head2 is not None):
if head1.data<=head2.data:
result.next = head1
head1 = ... |
f1701505a1adee8763ff6fbeec19d03d94f53ae6 | begarn/python-training | /day3/Deck.py | 1,312 | 3.78125 | 4 | #! /usr/bin/env python3
# -*- coding : UTF-8 -*
from Card import Card
import random
class Deck:
def __init__(self, empty = False):
# self.deck = []
# for color in Card.colors:
# for value in Card.values:
# self.deck.append(Card(color, value))
if not empty:
... |
f75a6b9ea125c411d35774a5c5e8c61640991d0f | tbilsbor/Euler-Python | /Euler#29/Euler#29.py | 300 | 3.953125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 26 12:56:53 2018
@author: toddbilsborough
"""
#How many distinct terms are in the sequence
# generated by a ** b for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100?
terms = len(set([a ** b for a in range(2, 101) for b in range(2, 101)])) |
8964012113d6b9a9681cb0f26e4fbb27de65c57c | shivngishrma23/FSDP19 | /day1/mini.py | 216 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue May 7 18:56:15 2019
@author: Shivangi Sharma
"""
import random
guess=0
name=input("enter you rname")
while(g<6):
print("try again")
g=g+1
print("no more guesses left")
|
35fc4873c00db36fc8c958f5227d8590dc78e7f6 | jarbhav/CCBD | /Approach 2/new_latest.py | 6,981 | 3.671875 | 4 | from __future__ import division
import math
import turtle
import random
import time
pointer=turtle.Turtle()
screen=turtle.Screen()
screen.bgcolor('white')
pointer.shape("arrow")
pointer.color("white")
pointer.width(1.1)
#pointer.goto(0,0)
pointer.speed(100)
#equation=[]
color=["green","red","blue","orang... |
0c7fe52667fa2f8bad06b5a2e4d9d40cb854e25f | jpaulo-kumulus/KumulusAcademy | /Exercícios José/Create your first Python program/challenge1.py | 392 | 3.78125 | 4 | print("Today's day?")
day = input()
print("Breakfast calories?")
breakCalories = int(input())
print("Lunch calories")
lunchCalories = int(input())
print("Dinner calories")
dinnerCalories = int(input())
print("Sack calories")
snackCalories = int(input())
sum = breakCalories + lunchCalories + dinnerCalories + snackCalori... |
eb71eb333fc921ef98c64956822a033897d494a3 | yi-fan-wang/bilby | /examples/core_examples/linear_regression_unknown_noise.py | 2,168 | 3.5625 | 4 | #!/usr/bin/env python
"""
An example of how to use bilby to perform parameter estimation for
non-gravitational wave data. In this case, fitting a linear function to
data with background Gaussian noise with unknown variance.
"""
from __future__ import division
import bilby
import numpy as np
import matplotlib.pyplot as... |
7ddbab0c7f4942cfa4997d6742dd2a3c5702fd53 | siri-palreddy/CS550-FallTerm | /CS-HW/HW10-15-17:MineSweeperProject.py | 2,341 | 3.984375 | 4 | import sys
import random
import math
def getRow(cellNumber):
rowNumber = math.ceil(cellNumber/totalColumns)
return rowNumber
def getColumn(cellNumber):
columnNumber = cellNumber%totalColumns
if columnNumber == 0:
columnNumber = totalColumns
return columnNumber
try:
totalRows = int(input('How many rows would... |
4d6a21ebffb7a92a3479ee001c9279516f41487d | ihzarizkyk/LearnPython3byIhza | /fungsi-kuadrat-kali.py | 1,207 | 3.625 | 4 | '''
Author : Mochammad Ihza Rizky Karim
'''
#buat fungsi kuadrat yang didalamnya memuat parameter angka
def kuadrat(angka):
#lalu kembalikan nilai angka dan kuadratkan
return angka*angka
#buat variabel nol sampe sembilan yang menyimpan fungsi kuadrat
#beserta angka 0 - 9
nol = kuadrat(0)
satu = kuadrat(1)
dua = kua... |
dc7f30a9a94f5d89c9cf12d96991624252abfb1e | koziscool/embankment_5 | /e17.py | 1,058 | 3.5 | 4 |
import time
num_letters = { 0:0, 1:3, 2:3, 3:5, 4:4, 5:4, 6:3, 7:5, 8:5, 9:4, 10:3,
11:6, 12:6, 13:8, 14:8, 15:7, 16:7, 17:9, 18:8, 19:8, 20:6,
30:6, 40:5, 50:5, 60:5, 70:7, 80:6, 90:6, 100:10,
200:10, 300:12, 400:11, 500:1... |
34223771c4676e81555b049b9a80601745ce30a6 | Pixaurora/Desmos-Calculator-Generator | /components/gates.py | 3,987 | 3.59375 | 4 | from .component import Component
class LogicGate(Component):
"""An arbitrary Logic Gate.
By default, no conversion or computation is implemented, but is instead
implemented by the other children classes.
Attributes
----------
inputs: List[Component]
A list of all the inputs t... |
f50044c8f432e4512d6fe6b97e0f51d7e8bd3a75 | XiwangLi/LeetcodeArchive | /String/Leetcode_String.py | 8,856 | 3.71875 | 4 |
# coding: utf-8
## 1: Implement strStr() Leetcode 28
# The first question is StrStr. It is the first problem in almost all the books of pactice material
# The brute force way of solve this problem is very easy and the time-complexity is O(m*n).
# Everybody will say, the brute force O(m*n) method is not good. We wan... |
bdfde5dfd25a5439d7a0ce5392bb63e96ed6ef69 | koukijohn/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/2-matrix_divided.py | 589 | 3.625 | 4 | #!/usr/bin/python3
"""
This module divides the matrix by div.
"""
def matrix_divided(matrix, div):
""" This function divides all elments of a matrix.
Args:
matrix: This is the matrix.
div: This is to divide.
Returns:
a new matrix.
"""
new_matrix = []
for row in ran... |
834afa56934730be698d2d48cf16bc1085f44d0e | AmalfiAnalyticsOrg/Meta-Model | /adaptative-app/adaptative/data_structures/sklearn_data_structure.py | 1,668 | 3.5625 | 4 | '''
DataStructure to serialize a Keras Model
It puts the network architecture as metadata and pickles the weights.
'''
import pickle
from soil.data_structures.data_structure import DataStructure
class Model(DataStructure):
# @staticmethod
@classmethod
def unserialize(serialized, metadata):
... |
9a742e8bcd32f2bc03636482444ae37936566ebc | kouyalong/StudyCode | /python_data_structure/leetcode/338.counting-bits.py | 562 | 3.53125 | 4 | # -*- coding: utf-8 -*-
from typing import List
class Solution:
def countBits(self, num: int) -> List[int]:
ret = [0, 1]
if num <= 1:
return ret[:num+1]
flag = 1
for i in range(2, num+1):
if (flag << 1) == i:
flag = flag << 1
... |
78d95db0411c661fa5c68509b322c4f74e86244d | itskeithstudent/Programming-and-Scripting-Labs | /Topic04-Flow/Lab04.03-average copy.py | 661 | 4.25 | 4 | #Program to keep reading numbers until user enters a 0
#take number from user
user_num = int(input("Enter a number please (0 to quit): "))
entered_numbers = [] #list of entered numbers
if user_num == 0: #if user has entered a 0 we proceed no further
print("You entered 0 immediately")
else: #else user must not have... |
0e4322487eb2f318db228f0f774cc5e3bbc17d21 | MaxGubin/mywifes_homework | /homework1205.py | 946 | 3.8125 | 4 | from __future__ import print_function
CSV_NUM_FILEDS = 5
CSV_SID = 0
CSV_GPA = 4
def load_file():
"""Loads the file, return a list of tuples with SID, GPA"""
result = []
for line in open('cats.txt'):
elements = line.strip().split(',')
if len(elements) != CSV_NUM_FILEDS:
contin... |
1d84d696d3db120a8779881bfefaa54d2a4c3ef5 | Yobretaw/AlgorithmProblems | /Py_leetcode/045_jumpGame2.py | 926 | 4.0625 | 4 | import sys
import math
from collections import defaultdict
"""
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number ... |
3a38dc90c9c00f0e0394bbac4edade20b357e90a | Pumala/python_rpg_logic | /rpg-5.py | 9,910 | 3.90625 | 4 | """
Added a store. The hero can now buy a tonic or a sword. A tonic will add 2 to the hero's health wherease a sword will add 2 power.
"""
import random
import time
class Character(object):
def __init__(self):
self.name = '<undefined>'
self.health = 10
self.power = 5
self.coins = 20... |
a76e74ec036b349222cc48d444ad9541778b0405 | domenicoven/python-katas | /string-calculators-kata/string_calculator.py | 845 | 3.609375 | 4 | import re
class StringCalculator:
def add(self, numbers):
delimiters = self.__retrieveDelimiters(numbers)
numList = re.split(delimiters, numbers)
total = 0
for val in numList:
total = total + self.__str_to_int(val)
return int(total)
def __str_to_in... |
e4c11fa168529e50e8e542131f03a15b21918574 | psbarros/Variaveis3 | /2019-1/231/users/4219/codes/1719_2505.py | 211 | 3.6875 | 4 | from math import*
x = eval(input("angulo :"))
k = int(input("insira: "))
i = 0
soma = 0
while i<k :
conta = x**((2*i) + 1)/factorial (2*i+1)
x = -1 *x
soma = soma + conta
i = i + 1
print (round(soma, 10))
|
55481b8fef77a13f67eed56f641949f034f96bb8 | hoanhan101/gumroad | /pivot.py | 864 | 3.90625 | 4 | def find_pivot(numbers: list):
if len(numbers) <= 2:
return -1
left = numbers[0]
right = sum(numbers)
for i in range(1, len(numbers) - 1):
left += numbers[i - 1]
right -= numbers[i]
if left == right:
return i
return -1
def test_find_pivot():
assert... |
0848a6c6d26b0eede22ebca5f82c87145b313750 | kesia-barros/exercicios-python | /ex001 a ex114/ex016.py | 381 | 4.0625 | 4 | from math import trunc, floor
n = float(input("Digite um número: "))
print("O número",n)
print("tem a parte inteira",floor(n))
# Outra forma de fazer é:
n = float(input("Digite um número: "))
print("O número",n)
print("tem a parte inteira",trunc(n))
# Outra forma de fazer é:
n = float(input("Digite um número: "))
pr... |
03a42e155dadadcc261d974dcde4a252cd8fcf4d | Linkin-1995/test_code1 | /day05/exercise02.py | 521 | 3.65625 | 4 | # 练习:
# 字符串: content = "我是京师监狱狱长金海。"
# 打印第一个字符、打印最后一个字符、打印中间字符
# 打印第三个字符、打印倒数第五个字符
# 命题:金海在字符串content中
# 命题:京师监狱不在字符串content中
content = "我是京师监狱狱长金海。"
print(content[0])
print(content[-1])
print(content[len(content) // 2])
print(content[2])
print(content[-5])
print("金海" in content) # True
print("京师监狱" not in content) #... |
69de80b7c5b079a654876c66dea0f0cab4c82cd1 | gabopotestades/python_mini_projects | /Hackerrank/Built-ins/ginortS.py | 518 | 3.9375 | 4 | #Declare list for storage
lcase = []
ucase = []
odd = []
even = []
#Determine each character which list they will be inserted
for s in input():
if s.isdigit():
if int(s) % 2 == 0:
even.append(int(s))
else:
odd.append(int(s))
elif s.islower():
lcase.append(s)
... |
362b604f4e219e8da4cda1663733c70cd715eacb | LSaldyt/q-knap | /scripts/dynamic.py | 2,061 | 3.84375 | 4 | import functools
def memoize(obj):
'''
Decorator that caches function calls, allowing dynamic programming.
If a function is called twice with the same arguments, the cached result is used.
obj: function to be cached
'''
cache = obj.cache = {}
@functools.wraps(obj)
def memoizer(*args, *... |
0f65c20e850f35911d9dbfba1967076391328163 | MarijaLaz/Awele_Othello | /Awele/awele.py | 4,672 | 3.859375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
sys.path.append("..")
import game
def initialiseJeu():
""" void -> jeu
Initialise le jeu (nouveau plateau, liste des coups joues vide, liste des coups valides None, scores a 0 et joueur = 1)
"""
#plateau = [[4 for i in range(6)] for i in rang... |
4510c4cf5d314d787b11142440aed2178be1f137 | SS4G/AlgorithmTraining | /exercise/leetcode/python_src/by2017_Sep/Leet173.py | 1,213 | 4.03125 | 4 | # Definition for a binary tree node
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from AlgorithmTraining.G55Utils.Py.Utils import *
class BSTIterator(object):
"""
O(1) times
O(n) memory
"""
def __init__(self, r... |
9bd995b601321c0ab60d7a180586605051d851d1 | alphadome/python | /Programs/toppings.py | 278 | 3.71875 | 4 | requested_toppings=['mushrooms', 'cheese', 'ham', 'pepperoni']
for requested_topping in requested_toppings:
if requested_topping == 'mushrooms':
print("Sorry out of mushrooms.")
else:
print("Adding " + requested_topping +".")
print("\nFinished making your pizza!")
|
9516ec9bab68674f78cd3e5b44568f9e4b2ba164 | Iceberry-qdd/python_exercise | /day3/5.py | 266 | 3.796875 | 4 | score=float(input('请输入成绩:'))
if score>=90:
print('A')
elif score<90 and score>=80:
print('B')
elif score<80 and score>=70:
print('C')
elif score<70 and score>=60:
print('D')
elif score<60:
print('E')
else:
print('输入错误!') |
17a1135c177ceaf3e0679788902801ed4c01dbf5 | Rkutta/Sedgewick_Algorithms_2nd_ED_in_Python | /Fundamentals/Elementary Data Structures/linked_list.py | 1,309 | 3.984375 | 4 | '''
Algorithms 2nd. Ed by Robert Sedgewick
Chapter 3: Elementary Data Structures pg 20
Program: linked_list
Implemented in Python by Edward Heronzy
'''
# Single Linked List
class node:
def __init__(self, key=None, next=None):
self.key = key
self.next = next
def listinitialize():
gl... |
3796a0bc6fe44f5b96de92466cc3b0e942de2962 | PPinto22/ProjectEuler | /p052.py | 289 | 3.625 | 4 | found = False
x = 0
while not found:
x += 1
for m in range(2,7):
smx = str(m*x)
sx = str(x)
if len(sx)!=len(smx) or not all(sx.count(digit) == smx.count(digit) for digit in sx):
break
else:
found = True
for i in range(1,7):
print(str(i) + " * " + str(x) + " = " + str(i*x)) |
10072a9d9cc5260af2eff37ead2ae63d65112ac7 | dkp-1024/face_counter | /my_work/pro6.py | 593 | 3.90625 | 4 | #pasting of the image on another image
from PIL import Image
def main():
try:
#Relative Path
#Image on which we want to paste
img = Image.open("picture.jpg")
#Relative Path
#Image which we want to paste
img2 = Image.open("picture2.jpg")
img.paste... |
e5c02a47a1ab6dcca709a2691c3dc949ea880c02 | 221002-Fety/Tugas-Besar | /tugasBesar.py | 10,280 | 3.515625 | 4 | import csv
import datetime
import os
filecsv= 'loginPass.csv'
def clear():
os.system('cls')
def backtoMenuWarga():
print("\n")
input("Tekan ENTER untuk kembali...")
menuWarga()
def backtoMenuAdmin():
print("\n")
input("Tekan ENTER untuk kembali...")
menuAdmin()
def ... |
b077c1df0a453e800b4f483287248323df8366f2 | Mr-Coxall/Computer-Based-Problem-Solving | /code_examples/4-Functions/1-Understanding_Functions/Python/main.py | 1,106 | 3.875 | 4 | #!/usr/bin/env python3
"""
Created by: Mr. Coxall
Created on: Sep 2020
This module uses user defined functions
"""
def calculate_area() -> None:
"""The calculate_area() function calculates area of a rectangle, returns None."""
# input
length = int(input("Enter the length of a rectangle (cm): "))
widt... |
25ffe3668f47f84be295fda37e9fd12f895e7934 | Nishitakesharbani/practice | /ex25.py | 576 | 4.3125 | 4 | def break_word(stuff):
"""This function will break your word"""
words=stuff.split(' ')
return words
def sort_words(words):
"""sort the word"""
return sorted(words)
def print_first_word(words):
"""Prints the first word after popping it off"""
word=words.pop(0)
print(word)
def print_las... |
1aeead6f35bce0a72ee2049c99e49a5ded83d403 | watermelon-lee/leetcode | /code/406.根据升高重新建队.py | 1,064 | 3.75 | 4 | """
@File : 406.根据升高重新建队.py
@Time : 2019-10-28 10:13
@Author : 李浩然
@Software: PyCharm
@Email: 1901210423@pku.edu.cn
"""
from typing import List
import functools
class Solution:
def sorted_key(self,x,y):
if x[0]>y[0]:
return 1
if x[0]<y[0]:
return -1
else:
... |
27feb15854f24cfa9048ee76d8cee1006a8233b9 | BartVandewoestyne/Python | /2.X/examples/mutable_default_arguments.py | 880 | 4.71875 | 5 | # Python's default arguments are evaluated once when the function is defined,
# not each time the function is called (like it is in say, Ruby). This means
# that if you use a mutable default argument and mutate it, you will and have
# mutated that object for all future calls to the function as well.
#
# References:
#
#... |
b196ffa8065669971d998cc6c86fb39d9e5c93b9 | lezakkaz/Python-workshop | /Examples/example_2-1.py | 649 | 4.28125 | 4 | # Python workshop Part 3 by Khiati Zakaria
# Example 2-1 (Functions)
# Create the function named helloWorld without any arguments and returns nothing
# it is suppose to print a number before it prints hello world!
# for exampe, if your input is helloWorld(5) it should print 5 Hello world!
def helloWorld(x):
... |
c5b02b0d7e22e458c0d0952c02bd2ef9401cde91 | SouzaCadu/guppe | /Secao_05_Lista_Ex_41e/ex_04.py | 322 | 3.875 | 4 | """
Se o número digitado for positivo:
- calcule o quadrado
- calcule a raiz quadrada
"""
v1 = float(input("Digite um valor positivo para saber o quadrado e a raiz quadrada:"))
if v1 > 0:
print(f"O quadrado de {v1} é {v1 ** 2:.2f} e a raiz quadrada é {v1 ** 0.5:.2f}")
else:
print("Digite um valor positivo.") |
b5eae3020cd8404311c6da6cba3123aabab728b6 | taeheechoi/coding-practice | /implementStrStr.py | 308 | 3.875 | 4 | # Example 1:
# Input: haystack = "hello", needle = "ll"
# Output: 2
# Example 2:
# Input: haystack = "aaaaa", needle = "bba"
# Output: -1
# Example 3:
# Input: haystack = "", needle = ""
# Output: 0
def implmentStrStr(haystack, needle):
return haystack.find(needle)
print(implmentStrStr("", "")) |
d9ef8101a0b2f8937b3460dc51150480e526f521 | Skyy-Bluu/longest-substring-without-repeating-characters | /Longest Substring Without Repeating Characters.py | 1,197 | 3.703125 | 4 | def lengthOfLongestSubstring(string):
highscore = 0
counter = 1
if string == " " or len(string) == 1:
return 1
elif string == "":
return 0
substring = string[0]
longestString = ""
for i in range(1, len(string)):
print("Substring ", substring, " String[i] ", string[i],... |
95f665d1f534415fb1c5e42db48b2250dc19375e | sribalakrish14/guvi-codekata | /noinletters.py | 117 | 3.5625 | 4 | num=int(input())
list=["Zero","One","Two","Three","Four","Five","Six" ,"Seven","Eight","Nine","Ten"]
print list[num]
|
acaca947838eb2dd10827b656aa2f9184d2fe4b8 | victorsemenov1980/Coding-challenges | /findUnique1.py | 931 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 25 12:02:50 2020
@author: user
"""
'''
There is an array with some numbers. All numbers are equal except for one.
Try to find it!
find_uniq([ 1, 1, 1, 2, 1, 1 ]) == 2
find_uniq([ 0, 0, 0.55, 0, 0 ]) == 0.55
It’s guaranteed that array contains at... |
670592e91b66013b4f50b59beeda938c0e81eca2 | GBenia/PythonforABM | /Q4_OopsDoo.py | 487 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Questão 4 - Escreva um programa que corre os números de 1 a 50 e imprime. Mas, quando for múltiplo
de três, imprima ‘Oops’, quando for múltiplo de 5 imprima ‘Doo’, quando for de ambos
imprima ‘OopsDoo’.
"""
for i in range(1, 51):
if i % 3 == 0 and i % 5 != 0:
print(i, 'Oops')
... |
e67e44f7b7d74555ffe140c188bd16d833c40459 | davelpat/Fundamentals_of_Python | /Ch11 exercises/producer-consumer.py | 3,672 | 3.71875 | 4 |
import time, random
from threading import Thread, currentThread, Condition
class SharedCell(object):
"""Shared data for the producer / consumer problem."""
def __init__(self):
"""Data undefined at startup."""
self.data = -1
self.writeable = True
self.condition = Condition()
... |
f80311b0d70570da1fc0a08dd3380aa72b960b2d | Fjelle/penguin-breakfast | /player.py | 2,985 | 3.71875 | 4 | import os
class Player():
def __init__(self,playernumber):
self.score=[]
self.rewarded_by=[]
self.playernumber=playernumber
self.victory_points=0
self.money=5
def return_victory_points(self):
return self.victory_points
def tell_rewarded(self,co... |
c9ec092763c94610b3cca5797021c5fa5da5a142 | Nolagg/DataAnalysisMatplotlib | /script20_pieLabel.py | 744 | 3.515625 | 4 | import codecademylib
from matplotlib import pyplot as plt
import numpy as np
payment_method_names = ["Card Swipe", "Cash", "Apple Pay", "Other"]
payment_method_freqs = [270, 77, 32, 11]
#make your pie chart here
# Legend can be added with
# plt.legend(payment_method_names)
# or
# plt.pie(payment_method_freqs, labels=... |
52414bec08d6de6cc45d82a8e047c4fff39f7b94 | Praveenramkannan/Python_Assignments | /python-solutions/problem set 1/books.py | 485 | 3.5625 | 4 | '''
name:books.py
date:2-12-20017
author:praveen.ram.kannan@accenture.com
question:Suppose the cover price of a book is Rs.24.95, but bookstores get a 40% discount. Shipping costs
Rs.3 for the first copy and 0.75p for each additional copy. What is the total wholesale cost for
60 copies?
'''
def calculate_sp(n):
sel... |
dc67a74409667fbf7eb51ecc9c5dce729b5b1b69 | jayanthnagasai/pythongames | /Countdown.py | 1,326 | 3.921875 | 4 | import time
import sys
print()
print("Jay's countdown timer")
print()
c = ':'
print()
years = input("Years: ")
months = input("Months: ")
days = input("Days: ")
hours = input("Hours: ")
mins = input("Minutes: ")
secs = input("Seconds: ")
print()
hour = int(hours)
min = int(mins)
sec = int(secs)
day = int(days)
m... |
f7ef83c89889a516ed410ea3a00e4ac74b236144 | JoseVale99/CursoPyQt5 | /mult_inheritance.py | 273 | 4.15625 | 4 | class A:
"""
Example of multiple inheritance
"""
def a(self):
print("- From to A")
class B:
def b(self):
print("- From to B")
class C(A,B):
def c(self):
print("- From to C")
letter = C()
letter.a()
letter.b()
letter.c() |
82001e0cb34cce6563eb114abd61484cbc2f5274 | iankronquist/dotfiles | /windows/untag.py | 838 | 3.875 | 4 | import sys
import string
def is_hex_string(s):
# Is the set of actual characters - set of allowed characters == empty set?
return set(s) - set(string.hexdigits + 'xX') == set()
def num_string_to_tag(s):
tag = ''
if s.startswith('0x') or s.startswith('0X'):
s = s[2:]
for pair i... |
e940094bb4e5086e439ef7fb67aa794f950223b8 | Teslatic/SC2-Freiburg | /cartpole/assets/helperFunctions/plotter.py | 11,572 | 3.5 | 4 | import numpy as np
import matplotlib.pyplot as plots
class Plotter():
"""
The Plotter class is used to plot the results from the experiment reports.
"""
def __init__(self, experiment_dir):
self.cwd = experiment_dir
###############################################################################... |
bd5e847ceb798755e1ecc40bbfb40f4c56510409 | danfinn/pythoncode | /russian_peasant.py | 337 | 4.03125 | 4 | #! /usr/bin/python
# Uses the russian peasant algorithim to add 2 numbers
num1 = int(raw_input('First number please: '))
num2 = int(raw_input('Second number please: '))
def russian_peasant(a,b):
x = a; y =b
z = 0
while x > 0:
if x % 2 == 1: z += y
x = x >> 1
y = y << 1
return z
print russian_pe... |
eecc4718a355cfb23fc57f441cda775b13ae4592 | DuongNg0403/PythonDA | /Data Structures/Set.py | 268 | 3.609375 | 4 | s1 = {1,1,5,3,4,7,5}
print(s1)
s2 = {2,3,7,5,9}
print(s1|s2) #s1|=s2 equivalent to s1 = s1|s2
print(s1&s2) #s1&=s2 equivalent to s1 = s1&s2
print(s1-s2) #s1-=s2 equivalent to s1 = s1-s2
print(s1^s2) #s1^=s2 equivalent to s1 = s1^s2
print(s1.isdisjoint(s2)) |
6b3b208b669687b5dd6d1da5c8d4e4024829f8de | xy2333/Leetcode | /leetcode/addTwoNumbers.py | 726 | 3.78125 | 4 | # Definition for singly-linked list.
# 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
"""
res = ListNode(0)
p = res
while l1 is no... |
9f880cdc098dbae21342e97d3d99c3cf91ff8e58 | cerealkella/rpi-examples | /salt_level.py | 2,239 | 3.5 | 4 | import RPi.GPIO as GPIO
import time
import signal
import sys
import send_email
from creds import TO
def close(signal, frame):
print("\nTurning off ultrasonic distance detection...\n")
GPIO.cleanup()
sys.exit(0)
def calculate_distance_mean():
# use Raspberry Pi board pin numbers
GPIO.setmode(GPIO.... |
d9f55994a26c042a822072a86f2bb3383d94f27a | agronja/cse-34872-su20-examples | /lecture07/02_cookies/cookies.py | 645 | 3.59375 | 4 | #!/usr/bin/env python3
import sys
# Functions
def feed_children(children, cookies):
count = 0
while cookies and children:
child = children.pop(0)
cookie = cookies[0]
if child <= cookie:
cookies.pop(0)
count += 1
return count
def main():
while ((chi... |
805884a12554012df8f5597409fded6a87268523 | JenZhen/LC | /lc_ladder/company/gg/high_freq/My_Calendar_II.py | 4,513 | 3.84375 | 4 | #! /usr/local/bin/python3
# https://leetcode.com/problems/my-calendar-ii/
# Example
# Implement a MyCalendarTwo class to store your events. A new event can be added if adding the event will not cause a triple booking.
#
# Your class will have one method, book(int start, int end). Formally, this represents a booking on... |
4934cda57fe6f2f81ebe7fa01d77d9213eb4a79e | xxcocoymlxx/Study-Notes | /CSC108/practices/class example/Class_example2.py | 1,036 | 3.703125 | 4 | class Actor:
def __init__(self, HP, AP, sex):
self.HP = HP
self.AP = AP
self.sex = sex
class Monster(Actor):
def attack(self,other, AP, HP_cost):
if (other.HP >= HP_cost):
other.HP -= HP_cost
print("Attack Successfully")
return True
... |
0a497a4a10622fa93aaa4eaa97b461e77a44af1d | josecervan/Python-Developer-EOI | /module2/lambda_funcs/sorting_a_sequence.py | 619 | 3.859375 | 4 | notas = [{'nombre': 'Lola', 'final': 9},
{'nombre': 'Javier', 'final': 9.2},
{'nombre': 'Marta', 'final': 9.5}]
if __name__ == '__main__':
nombres_ordenados = sorted(notas, key=lambda nota: nota.get('nombre'))
notas_ordenadas = sorted(notas, key=lambda nota: nota.get('nombre'))
minima = ... |
9611d0b89d91166cdb607f6692de77cc2d44a2ae | RolfHaakon/PythonExercises | /Exercises/SimpleNeuralNetwork.py | 1,150 | 4.21875 | 4 | """
https://www.kode24.no/guider/the-best-way-to-learn-deep-learning/71003527
Simple neural network
"""
def simple_neural_netowrk(input, weight, goal_prediction, train):
for i in range(train):
prediction = input * weight
"""
Squared root error is used to always get a positive number to ... |
b75ac45c451be2c68c87f5bd0ae53b8d69266d3a | risoyo/CodingInterviews | /剑指offer-牛客/08-跳台阶.py | 478 | 3.5625 | 4 | # -*- coding:utf-8 -*-
class Solution:
def jumpFloor(self, number):
if number == 1:
return 1
elif number == 0:
return 0
elif number == 2:
return 2
result = [0, 1, 2]
jt = 0
j1 = 1
j2 = 2
for i in range(1, number-1):
... |
b1020091986a1897a0246022f15bc97310eec117 | Shraddha0501/Covid-19-Analysis | /covid19 analysis.py | 1,732 | 3.859375 | 4 | #Importing Pandas
import pandas as pd
#Library used to fetch the data from web
import requests
#Data collection/scraping from url(wikipedia)
url = 'https://en.wikipedia.org/wiki/COVID-19_pandemic_by_country_and_territory'
request_url = requests.get(url)
#The desired data will be fi... |
793bc622604a641cb69f6b9ce39d06c8ddcede38 | ljubicamiljkovic56/op2018 | /ProjekatOP2018 ver2/funkcije/pretragaRezervacija.py | 2,057 | 3.515625 | 4 | def formatTabela():
print("Sifra |Sb|Datum rezervac. |Datum prijave |Datum odjave |K.ime |Tip sobe|Kl|Tv|Kp|Tr|Cena|Rezerv.|O")
print("------+--+----------------+----------------+----------------+------+--------+--+--+--+--+----+-------+-")
def pretragaRezervacija():
print("Pretraga rezervacija")
print(... |
33b606e8032349fd9feb44aea503fb09b22d47c4 | mkokol/design_patterns | /structural/decorator/src/component.py | 524 | 3.59375 | 4 | from abc import ABC, abstractmethod
class AbstractComponent(ABC):
@abstractmethod
def render(self):
pass
@abstractmethod
def get_size(self):
pass
class TextComponent(AbstractComponent):
def __init__(self, text):
self.text = text
@property
def text(self):
... |
f7abfa9863b7dade169f9ccf6422138011336e57 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/rna-transcription/708dfc085bc34edcb36a606113c3da87.py | 253 | 3.59375 | 4 | class DNA(object):
def __init__(self,strand):
self.strand = strand
def to_rna(self):
tr = {'G':'C', 'C':'G', 'T':'A', 'A':'U'}
rna = ''
for strand in self.strand:
rna += tr[strand]
return rna
|
32a88153fa15eb016907e2a4f7255d1b2467d36c | pkmm91/competitive-programming-solutions | /URI/1070.py | 209 | 3.671875 | 4 | import os
import sys
num = int(raw_input())
count = 0
while (1):
if (num % 2 != 0):
print (num)
count = count + 1
num = num + 1
if (count == 6):
break
|
671a7c9934c89837e0c43e17561749889de17657 | mandypar/Python-Coursework | /PythonCode/Assignment5_2a.py | 412 | 4.15625 | 4 | largest = None
smallest = None
while True:
num=raw_input('Enter a number:')
if num == "done": break
try:
numfinal = int(num)
except:
print 'Invalid input'
continue
if numfinal>largest:
largest=numfinal
continue
if numfinal is not smallest:
smallest=numfinal
continue
if numfinal... |
f6d6e6cb0179be2b73ff66ae3a72fbe59e4dd13c | osmarsalesjr/AtividadesProfFabioGomesEmPython3 | /Atividades1/At1Q16.py | 294 | 3.796875 | 4 | def main():
lado_quadrado = float(input("Digite o valor do lado do quadrado para obter sua area: "))
print("A area desse quadrado é ", calcula_area(lado_quadrado), "u².")
def calcula_area(valor_lado):
area = valor_lado ** 2
return area
if __name__ == '__main__':
main() |
ae661253d50c9d9843e75196ed8988c47e05e739 | jkohans/adventofcode2020 | /day5/day5.py | 1,900 | 3.75 | 4 | import math
def find_passport(input_filename):
num_rows = 128
num_columns = 8
seat_codes = []
current_max = 0
for line in open(input_filename):
line = line.rstrip("\n")
row_directions = line[:7]
column_directions = line[7:]
row_answer = bin_search(num_rows, row_di... |
1b87ded4567a47b0a7bb30ec38be246d2caadec2 | pflun/advancedAlgorithms | /threeSumSmaller.py | 922 | 3.703125 | 4 | # -*- coding: utf-8 -*-
class Solution(object):
# two pointer, one from left (after i), the other one from most right
# 跟 3 sum 一样,固定一点,从这点下一个开始两头往中间扫
# 利用 sum < target 时,i 和 left 不动,介于 left 和 right (包括 right) 之间的所有元素 sum 也一定小于 target 的单调性。
def threeSumSmaller(self, nums, target):
nums.sort()
... |
d8d9c686e622429780d9db46d0457601a1cd1cd5 | rongpenl/k16math-course | /exercises/solution_02_02_01.py | 364 | 4.09375 | 4 | # Given a __distance__ in miles, find its value in __kilometers__.
def mileToKilometers(mile):
if mile > 100 or mile < 0:
print("{} is not valid. Please make sure it is between 0 and 100.".format(mile))
return None
else:
kilo = mile*1.6
print("{} mile(s) is roughly () kilometer(... |
6c742d854ea4efa2c99ed384588f118ea717511e | 35sebastian/Proyecto_Python_1 | /CaC Python/EjerciciosPy1/Ej5.py | 161 | 4.0625 | 4 | nombre = input("Ingrese su nombre: ")
numero_entero = int(input("Ingrese un numero: "))
print()
for i in range(numero_entero):
print(str(i+1) + " " + nombre) |
26cb69c5b86bafb8ae702b9ae54a6e5d49335ebf | rafaelperazzo/programacao-web | /moodledata/vpl_data/389/usersdata/313/73603/submittedfiles/poligono.py | 68 | 3.65625 | 4 | n=int(input('digite o valor de n'))
nd=n(n-3)/2
print('%d' % nd)
|
1709904989c53e8b793c94b008a48f36811a636d | nhatsmrt/AlgorithmPractice | /LeetCode/369. Plus One Linked List/Solution.py | 668 | 3.578125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def plusOne(self, head: ListNode) -> ListNode:
carry = self.plus(head)
if carry:
return ListNode(carry, head)
r... |
de502088598a929241f3eda2d9e671e4a7b21f6e | ARSimmons/IntroToPython | /Students/A.Kramer/session03/mailroom.py | 2,402 | 3.859375 | 4 |
def execute():
"""Run the main program """
donors = [["Jon Doe", 50, 2], ["Jane Doe", 35, 7], ["Anonymous", 30, 10]]
prompt = "Please, select the following options\n1 - Send a Thank you Letter\n2 - Create Report\n3 - Quit\n"
while True:
print prompt
answer = raw_input("What is your choi... |
3cecccb85d1114a64abe8c5e6f5a9c5e74d2f05f | a69e/LeetCode | /DFS/51.n-queens.py | 2,252 | 3.796875 | 4 | #
# @lc app=leetcode id=51 lang=python3
#
# [51] N-Queens
#
# https://leetcode.com/problems/n-queens/description/
#
# algorithms
# Hard (55.13%)
# Likes: 4654
# Dislikes: 137
# Total Accepted: 322.7K
# Total Submissions: 584K
# Testcase Example: '4'
#
# The n-queens puzzle is the problem of placing n queens on a... |
3310a3de21a47bae6def014f018ee22b6b6d2d92 | bhakes/Sprint-Challenge--Algorithms | /Short-Answer/scratch_pad.py | 811 | 3.59375 | 4 | import time
def test(n):
a = 0
t0 = time.time()
while (a < n):
print(a)
a = a + 1
t1 = time.time()
total = t1-t0
print(total)
test(10000)
def test2(n):
t0 = time.time()
sum = 0
for i in range(n):
i += 1
for j in range(i + 1, n):
j += 1
... |
6b6b490f63b1be54482cd36444e3c88e5bb461a9 | NoeNeira/practicaPython | /Guia_2/Ejercicio1.py | 662 | 4.40625 | 4 | """
Pedir al usuario que ingrese un mensaje cualquiera, si el mensaje tiene más de 100 caracteres
imprimirlo por pantalla, si tiene entre 50 y 100 caracteres imprimirlo al revés,
si no se cumple ninguna de las opciones anteriores, por pantalla devolver un mensaje que diga
"su mensaje es demasiado corto"
"""
texto =... |
927edb4da224aa650898b1ab1a5ec4e3557a4f3d | xprime480/projects | /examples/python/circlepoints.py | 914 | 4.1875 | 4 | #!/usr/bin/env python3
"""
Generate and print points on the radius of a circle.
"""
import random
import math
def main(radius, count) :
points = make_points(radius, count)
print (count_quadrant(points))
for x in points :
print (x[0], x[1])
def count_quadrant(points) :
quad = [0,0,0,0]
... |
7465cde937dd5a02c432c40ac89a58524d18cf05 | Hyunwoo29/python-oop | /encapsulation/calculator-constructor.py | 728 | 3.796875 | 4 | def add_fucntion(first, second):
return first + second
def mul_fucntion(first, second):
return first * second
def sub_fucntion(first, second):
return first - second
def div_fucntion(first, second):
return first / second
class Calculator:
def setdata(self, first, second):
self.first = first
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.