blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
2339ed6d5de63e733d5f8cb9c9903af3d12c14ea | Camilo6/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/4-print_square.py | 519 | 4.40625 | 4 | #!/usr/bin/python3
""" This module is from task 4"""
def print_square(size):
"""This function that prints a square with the character #"""
if not isinstance(size, int) or isinstance(size, float):
raise TypeError("size must be an integer")
if size < 0:
raise TypeError("size must be >= 0")
... |
755418e028b135c46d307e2031085b8eaceb9bce | sieczkah/Codewars_KATA | /7 kyu/Speed Control.py | 191 | 3.59375 | 4 | """https://www.codewars.com/kata/56484848ba95170a8000004d"""
def gps(s, x):
speed = [(x[i + 1] - x[i]) / s * 3600 for i in range(len(x)-1)]
return max(speed) if speed else 0
|
6374f63b35a624cbb17a9452ca2e37646497923e | AlexNewson/ProjectEuler | /python/000-050/euler019.py | 1,404 | 3.875 | 4 | import time
import euler
euler.print_problem(19)
start = time.time()
# ==================================================
n_year = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # Normal Year
l_year = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # Leap Year
week = ["Monday", "Tuesday", "Wednesday", "Thursday"... |
9531096b8259c59e372aad6cdbd0cff7472ad623 | gxgarciat/Playground-PythonPractice | /D3_c5.py | 1,876 | 4.03125 | 4 | # Build a program that tests the compatibility between people
# For that, you need to check the number of times the letters in the word TRUE occurs.
# Then check for the number of times the letters in the word LOVE occurs. then combine these numbers to make
# a 2 digit number
# If you want extra cheese, the added price... |
83f3fefdce9e9eb1a2248c810587cba738db1682 | kmcrayton7/python_coding_challenges | /programmr/variables/test_your_variable_knowledge.py | 335 | 4.21875 | 4 | # Ask the user to enter two variables 'a' and 'b'. Then assign the value of 'b-a +100' to 'b' and print values of both 'a' and 'b' as shown below.
value_a = int(raw_input("Enter a value for a: "))
value_b = int(raw_input("Enter a value for b: "))
value_b = value_b - value_a + 100
print "a: %d" % value_a
print "b:... |
ea9cd727d0e549f3347053a93bcd27daafc9ea5f | hegdepunith17/Python-Day-1-Project | /calculator.py | 870 | 4.21875 | 4 |
while True:
option = input("Enter add or subtract multiply divide quit : ")
if option == 'quit':
break
elif option == 'add':
number1 = float(input("Enter first number: "))
number2 = float(input("Enter second number: "))
print(number1 + number2)
elif option == 'subtract'... |
c8c7883a51d77872ff369fa6e7537965d8accb01 | bayoishola20/Python-All | /Data Structure Algorithms (DSA)/linkedList.py | 1,809 | 3.890625 | 4 | class node:
def __init__(self, data=None):
self.data = data
self.next = None
class linked_list:
def __init__(self):
self.head = node()
def append(self, data):
new_node = node(data)
current_node = self.head
while current_node.next != None:
current... |
0b08c53520fe8f4385b7ef986ddd538a82614f8f | yongxuUSTC/challenges | /sort-merge.py | 1,291 | 3.84375 | 4 | '''
Question: Given two sorted lists merge them.
'''
#Source: http://stackoverflow.com/questions/2488889/how-can-i-merge-two-lists-and-sort-them-working-in-linear-time
#Solution 1: Build result array in descending order
def merge1(l, r):
result = []
while l and r:
if l[-1] > r[-1]:
result.append(l.pop())
else... |
8e6cb90d22a77665aad3b6e2bd5634cc125f64e6 | bc24/cbm | /Python 3.8/Tag3 22.11.2019/Funktion/L/dec2bin.py | 262 | 3.546875 | 4 | def dec2bin( dec ):
result = ""
while dec != 0:
result += str( dec % 2 )
dec = dec // 2
return result[::-1]
# print(result[::-1] , "\n\n")
print( dec2bin( 31 ) )
print( dec2bin( 32 ) )
print( dec2bin( 15 ) )
print( dec2bin( 255 )) |
28c395cfde17ef393943ffb75be4c9750142ad8d | taylorperkins/feed-blueberry-dragon | /blueberry_dragon.py | 22,474 | 3.609375 | 4 | # Dragon Eat Dragon (a 2D Katamari Damacy clone)
# By Al Sweigart al@inventwithpython.com
# http://inventwithpython.com/pygame
# Released under a "Simplified BSD" license
import random
import sys
import time
import math
import pygame
from pygame.locals import *
FPS = 30 ... |
f2bc8178ab93326d3e173dae5b2d69a36521d43f | danusarbc/python_drbc | /PythonExercices/Fibonacci.py | 229 | 4.3125 | 4 | #Fibonacci
def Fibonacci(num):
if num <=1:
return num
else:
return Fibonacci(num -1) + Fibonacci(num - 2)
fib = int(input("Enter a number: "))
result = Fibonacci(fib)
print ("Fibonacci number:", result) |
eb4176320a33963e4e62a1217b55a1b58d635ccd | sam1017/pythonstudy | /bank_simulation.py | 4,095 | 3.78125 | 4 | from random import randint
class Customer(object):
def __init__(self, arrived_time):
self.arrived_time = arrived_time
def set_status(self, status):
self.status = status
def set_queqe_number(self,queqe_number):
self.queqe_number = queqe_number
def set_start_process_time(self, s... |
2b6a0b8e17ff992f5d3bc017189ab5c9290c00df | sry19/python5001 | /lab07/pair_of_dice.py | 547 | 3.703125 | 4 | from die import Die
class PairOfDice:
'''A class representing pairs of dice'''
def __init__(self):
'''create two dice
PairOfDice object -> None'''
self.die_1 = Die()
self.die_2 = Die()
def roll_dice(self):
'''roll two dice
PairOfDice object -> None'... |
a8b16b3fd06b961cd002cacfdc0726ec83eddb48 | IntensiveCoding/mylearnings.python | /argparse01.py | 834 | 3.890625 | 4 | import argparse
parser = argparse.ArgumentParser(description='Parsing arguments')
# Optional arguments with short and long flags
parser.add_argument('-s', '--sum', action='store_true', help='Sum the list of numbers')
# Optional arguments with required flag
parser.add_argument('-v', '--verbose', required=True, help='... |
4cd85eebce3fd12b06e28bf727e52fccb9cf7582 | gosftw/Py-CheckiO | /Home/Time Converter (24h to 12h)/mission.py | 766 | 3.765625 | 4 | def time_converter(time):
if time == "00:00":
return "12:00 a.m."
t = time.split(":")
res = ""
if int(t[0]) > 12:
res += str(int(t[0]) % (12 + 1) + 1)
else:
res += str(int(t[0]))
res += ":"
res += t[1]
res += " "
if int(t[0]) > 11:
res += "p.m."
el... |
d8198c34a13a0e7058ca9b986c5d3a17f784c686 | JTMachen/Sponsio-Computatum | /Website/Calendar.py | 1,642 | 3.65625 | 4 | from Website import baseball_bet,basketball_bet,hockey_bet,football_bet
from datetime import datetime
from path import Path
import pandas as pd
import json
import warnings
warnings.filterwarnings('ignore')
from IPython.display import clear_output
def calendar():
with open('transaction_history.txt') as json_file:... |
803c210bb11ce3b07a5e3b33164c52e84bf784a7 | yanghaotai/leecode | /初级算法/3链表/4合并两个有序链表.py | 597 | 4.4375 | 4 | '''
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]
输入:l1 = [], l2 = []
输出:[]
输入:l1 = [], l2 = [0]
输出:[0]
'''
'''
append() 在列表的末尾添加一个元素
extend() 在列表的末尾至少添加一个元素
insert() 在列表的任意位置添加一个元素
'''
def mergeTwoLists(l1, l2):
l1.extend(l2)
l1.sort()... |
bf1e8c5801f631726f1947f0c755737b6f4ff4d3 | daysiG21/RetoSemana1Back | /objetivo1.py | 511 | 3.921875 | 4 | nombre = input("Ingrese su nombre")
edad = int(input("Ingrese su edad"))
hora = 19
#Ingresar un nombre y su edad.
#Si es menor de edad que indique que dependiendo de la hora (si es mas de las 6pm)
#debe ir a dormir y si no hacer la tarea.
#Si es mayor de edad que indique que no esta obligado a hacer nada.
if edad <18 ... |
b9a24ef9ad6236fa6d366b8304f3fb148c988e05 | peterhurford/polygot-code-interview | /fib/fib.py | 1,174 | 3.578125 | 4 | import sys
from datetime import datetime
def timeit(fn):
def timed(*args, **kwargs):
start = datetime.now()
result = fn(*args, **kwargs)
end = datetime.now()
print 'Timeit says this took {}'.format(end - start)
return result
return timed
@timeit
def fib_loop(n):
a,... |
b0cc98144c63b75159d73ead06a6dd92ad4353f9 | nocmt/leetcode | /1. 两数之和.py | 1,472 | 3.90625 | 4 | '''
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
'''
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int... |
a18cd5349b400d8ba956ee3395721b1e113aa2cd | s-kyum/Python | /exercise/262p.py | 1,070 | 3.703125 | 4 | #1번문제
class Calculator:
def __init__(self):
self.value = 0
def add(self,val):
self.value += val
return self.value
class UpgradeCalculator(Calculator):
def minus(self,val):
self.value -= val
return self.value
class MaxLimitCalculator(Calculator):
def add(self,val)... |
e5043ad6af37e48622c0dbd67d0e8a65ea83adfd | amitsaha/learning | /python/unique_url.py | 1,491 | 3.71875 | 4 | '''
You have a file with a large number of URLs, find the first unique URL
PS: The entire file is too big to be brought into memory.
'''
from collections import OrderedDict
# this approach cannot work for large files since we do not
# have enough memory to store the large file
def find_unique_url(file):
urls = O... |
4e6c69e09dd60c11481f86fa09529385e3eb07d1 | xiaotuzixuedaima/PythonProgramDucat | /PythonPrograms/python_program/sort_alphabate_word_string.py | 500 | 4.46875 | 4 | '''
# Python Program to Sort Words in Alphabetic Order ????
# Program to sort alphabetically the words form a string provided by the user
'''
str = "Hello this Is an Example With cased letters"
# str = input("Enter a string: ")
# breakdown the string into a list
words = str.split()
# sort the list
words.sort()
# di... |
dbaf57d68797fb819b53b330eb1f93ed5578d43d | Dhandapani299/python | /64even.py | 98 | 3.890625 | 4 | e = int(input())
f = int(input())
c = e + f
if (c % 2 == 0):
print("even")
else:
print("odd")
|
acbd0f186e42efbc23077f0a3e395317aade1af6 | dhazu/Mygit | /python_workbook/if-elif/ex34_alter.py | 572 | 4.21875 | 4 | """Exercise 34: Even or Odd?
Write a program that reads an integer from the user. Then your program should
display a message indicating whether the integer is even or odd."""
##Solution:
# ask the user to enter a number
num = int(input("Enter an integer number: "))
# apply the condition and display the result
if num... |
0cd36b828f9931b0e76510fd4588377a7d686e1b | CITlabRostock/citlab-python-util | /citlab_python_util/geometry/point.py | 441 | 3.90625 | 4 | def rescale_points(points, scale):
""" Take as input a list of points `points` in (x,y) coordinates and scale them according to the rescaling factor
`scale`.
:param points: list of points in (x,y) coordinates
:type points: list of Tuple(int, int)
:param scale: scaling factor
:type scale: float... |
5cabb8f4d626da0c0d71223d5e47749133ddf99a | MVGopi/python_training_2020 | /module1.py | 309 | 4.15625 | 4 | class EvenOdd:
'''This class used checking whether the given number is even or odd'''
def iseven(N):
if(N % 2 == 0):
return True
else:
return False
def isodd(N):
if(N % 2 == 1):
return True
else:
return False
|
6e7ec93a54c501227c417709f3c70a98af1e9027 | valleyceo/code_journal | /1. Problems/l. Design/c. Stack - Maximum Frequency Stack.py | 1,519 | 3.671875 | 4 | # LC 895. Maximum Frequency Stack
'''
Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack.
Implement the FreqStack class:
FreqStack() constructs an empty frequency stack.
void push(int val) pushes an integer val onto the top of the stack.
int pop() remove... |
4dfc338d7ab3968c3929b56455441cf7b99bda7f | bisolaomisore/projectEuler50 | /DigitCancellingFractions/DCF.py | 301 | 3.515625 | 4 | #!/usr/bin/env python3
"""
Project Euler # 33
"""
for i in range(10,100):
for j in range(10, 100):
if j < i and str(i)[1] != '0':
if j/i == int(str(j)[0])/int(str(i)[1]) and str(j)[1] == str(i)[0]:
print(str(j)+"/"+str(i))
else:
continue
|
b4642af405871a89e0e22fc7a93763896ad1c240 | EngageTrooper/Basic_Calculator_Python | /Calculator_Fle.py | 820 | 4.15625 | 4 | def add(num1,num2):
return num1 + num2
def subtract(num1,num2):
return num1 - num2
def multiply(num1,num2):
return num1 * num2
def divide(num1,num2):
return num1 / num2
print("Please Select Operation -\n" \
"1.Add \n" \
"2.Subtract \n" \
"3.Multiply \n" \
"4.Divide \n" )
select = in... |
b1a17e9223ed2c2fbe634f74159ce0bc47d4587d | s3668087/A1_SIC_S2_2020 | /Q2/charfreq.py | 371 | 3.609375 | 4 | cihpertext = raw_input("Enter a cyphertext: ")
alphabet = [
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','z'
]
hits = [
(alphabet[i], cihpertext.count(alphabet[i]))
for i in range(len(alphabet))
if cihpertext.count(alphabet[i])
]
for letter, freq... |
fe8ac19f7d1e1cdb425bd455012d7fee7c33c313 | masterchoi2020/python_basic | /utilize/2.utilize/gui_project/1-2.remind.py | 830 | 4.03125 | 4 | # 리스트에서 revers()함수와 reversed
lst = [1,2,3,4,5]
print(lst)
lst.reverse() # 원본에 영향 있음(O) : 원본 데이터의 순서를 바꿔버림
print(lst)
lst2 = [1,2,3,4,5]
print("리스트2 뒤집기 전: ", lst2)
lst3 = reversed(lst2) # 원본에 영향 없음(x) : 원본 데이터엔 영향이 없고 출력시 바뀐 값만 lst3에 넣어줌
print("리스트2 뒤집은 후: ", lst2)
print("리스트3: ", list(lst3))
# zip 사용법(같은 열끼리 붂어준... |
9f9f4f67210c1ef24c61ae8741d602b2233721d6 | Sweshrii/hackerrank-challenges | /hackerrank.py | 28,786 | 3.9375 | 4 | # My solutions to hackerrank challenges,
# paste every snippet on hackerrank web to solve it
# https://www.hackerrank.com/challenges/mark-and-toys
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Enter your code here. Read input from STDIN. Print output to STDOUT
def max_toys(prices, rupees):
#Compute and ret... |
3b8dbf0dbc9b5f0e1a064cd6da9b5cf3df76529e | kooshine/LeetCode | /plan_200/008_rotate_array.py | 565 | 3.53125 | 4 | # -*- coding: utf-8 -*-
# -*- coding:utf-8 -*-
class Solution:
def minNumberInRotateArray(self, rotateArray):
# write code here
if len(rotateArray) == 0:
return 0
start = 0
end = len(rotateArray)-1
while start < end-1:
mid = (start+end)/2
... |
8d46a57716a0fac13ee17cd95afc7aba8dedb147 | seangz/PythonCrash | /voting.py | 174 | 3.75 | 4 | age = 17
if age > 18:
print("You are old enough to vote!")
print("Have you registered to vote yet?")
else:
print("Sorry you're whack")
print("Come back when you're 18!") |
bf95f15276e74a95657d798a7789cdd587ae1ead | ridhwanc/ENGINEER-1D04 | /ReverseAString.py | 344 | 4.25 | 4 | # Reverse a string
inputStr = 'RidhwanIsASav'
#initialize an empty string
result = ''
#run a loop from len(inputStr)-1 to 0
#within the loop, append characters from the end of the string to the beginning into the result string
for i in range(len(inputStr)-1,-1,-1):
result = result + inputStr[i]
#print reverse... |
c97a8205ef9a9d4241095b7d12f572b26b761af1 | Oashpak/Lv-625.PythonCore | /HW1/TuziakT/1.py | 396 | 4.0625 | 4 | user_name = input("What is your name?\n")
print("Hello,", user_name)
user_age = input("How old are you?\n")
print("Your age is ", user_age)
user_loc = input("Where do you live?\n")
print("Your live in ", user_loc)
"""
Зараз у терміналі вам по черзі потрібно ввести своє Ім*я
потім свій вік
і також де ви проживаєте
""" |
be9a23369d715ffa3cd81773b2e8d92532dd912a | wansweet/python3basic | /eight/c2.py | 397 | 3.59375 | 4 | # -*- coding: utf-8 -*-
def funcname(parameter_list):
pass
# 1.参数列表可以没有
# 2.return value None
# 1.实现两个数字的相加
# 2.打印输入的参数
# import sys
# sys.setrecursionlimit(1000)
def add(x,y):
result = x + y
return result
def h(code):
print(code)
# print(add(1,2))
# h('python')
a = add(1,2)
b = h('python')
pr... |
0f19d3a23a9105a938aa609e91f9cbfce1881738 | leohasselqvist/Two-Launch-Bot-V4 | /db.py | 5,904 | 3.703125 | 4 | import sqlite3
import datetime
debug = False
def dprint(text):
if debug:
print(text)
tekdb = sqlite3.connect("1tek2.sqlite3") # Get Database, if it does not exist, create it.
dprint("Database connected")
def setup(): # Make sure that the user "template" is in place, otherwise create ... |
c08bffae4efa1ba9384437c21200c70d70b161a5 | jsanon01/python | /imaj2.py | 2,376 | 4.1875 | 4 | # This script has 4 options:
# 1) open image 2) displays image size 3) resize image 4) rotate image
# importing the libraries
from PIL import Image
# print statemnt greeting
print("\nThis script displays 4 options about an image:\n[open image]\t[display size image]\t[rotate image]\t[resize image]")
# I ask the user ... |
7c23c2ebac4341649b745773f8460581205d06a0 | olivierverdier/spinsys | /spinsys/nonlin.py | 3,950 | 3.609375 | 4 | #!/usr/bin/env python
# coding: UTF-8
from __future__ import division
"""
Some nonlinear solvers.
"""
import numpy as np
import numpy.linalg as npl
default_tol = np.sqrt(np.finfo(1.0).eps) # Sqrt of machine epsilon (for default float type).
class StoppingCriteria(object):
"""
Class for testing convergence of a F... |
6391faf0407dad7c9e9f0b323f96d74c4536dde7 | bartoszstepak/Python_2019-2020 | /Zestaw_9/9_1.py | 1,957 | 4 | 4 | class Node:
def __init__(self, data, next):
self.data = data
self.next = next
def __str__(self):
return str(self.data)
class List:
def __init__(self):
self.head = Node(None, None)
self.tail = self.head
def __str__(self):
list = ""
... |
257dccc828bf9d5c73722aa3ed95f8198e49ed6e | hankazajicova/Py-code-challenge | /src/pp_24_draw_a_game_board.py | 405 | 3.953125 | 4 | HORIZONTAL = " ---"
VERTICAL = "| "
def get_board(range_board: int) -> None:
"""
Args:
range_board (int): user input size
"""
for _ in range(range_board):
print(HORIZONTAL * range_board)
print(VERTICAL * (range_board + 1))
print(HORIZONTAL * range_board)
if __name__ == ... |
4807f2d5d97167d76b2c419140bf52fdfc2c9a5c | dustinpfister/examples-python | /for-post/python-getting-started/s2-var/type.py | 237 | 3.59375 | 4 | a = 5
print( type(a) ) # <class 'int'>
b = 5.7
print( type(b) ) # <class 'float'>
c = 'string'
print( type(c) ) # <class 'str'>
d = ['one', 2, 3, 'four']
print( type(d) ) # <class 'list'>
e = bool(0)
print( type(e) ) # <class 'bool'> |
7b40cf4966a118ee3a1b2a7438c8d91b56ca9f56 | etzellux/Python-Demos | /sqlite,json and many others/looping_techniques_data.py | 201 | 3.9375 | 4 | #%% ENUMERATE
for x,y in enumerate(["a","b",7,8]):
print((x,y))
#%% SORTED
for i in sorted({'z','d','e','g','j'}):
print(i," ",end="")
#%% .sort
list1= [1,11,5,7,9]
list1.sort()
print(list1)
|
1ba3bd42600baf321c14f39d635bd30046809c8f | RomanKhripunov/LearningPython | /Algorithms/recursion.py | 1,519 | 3.671875 | 4 | # псевдокод код для нахождения ключа в шкатулках
def look_for_key(main_box):
heap = main_box.values()
while heap is not None:
box = heap.pop()
if isinstance(box, list):
heap.append(box)
elif isinstance(box, str):
return box
def sum_elemtnts(arr):
if len(arr)... |
a3b2e716d0568e6414a8cedc0dba2e3cf1a45763 | stellaluminary/Baekjoon | /1002.py | 348 | 3.703125 | 4 | """
Method 1
"""
for i in range(int(input())):
x1,y1,r1,x2,y2,r2 = map(int, input().split())
dist = ((x1-x2)**2 + (y1-y2)**2)**0.5
if dist == 0 and r1 == r2:
print(-1)
elif dist == (r2+r1) or dist == abs(r2-r1):
print(1)
elif dist > (r2+r1) or dist < abs(r2-r1):
print(0)
... |
23fbb66495a19f169157db521f121601433924ac | Sofista23/Aula1_Python | /Aulas/Aulas-Mundo3/Aula017/Aula017c.py | 159 | 3.671875 | 4 | val=[]
for c in range(0,4):
val.append(int(input("Digite um número:")))
for v in range(0,len(val)):
print(f"O valor na posição {v+1} é o {val[v]}") |
f8fb943f6877c898045746c15843a56ea56c908a | mrlancelot/CodingPractice | /LeetCode/py_strings/group_size.py | 300 | 3.578125 | 4 | groupSizes = [2,1,3,3,3,2]
gs = list(set(groupSizes))
fin = []
for j in range(len(gs)):
gp = []
for i in range(len(groupSizes)):
if (gs[j] == groupSizes[i]):
gp.append(i)
if len(gp) == gs[j]:
fin.append(gp)
gp = []
print(fin) |
57f793f07973848f4f06599f09529db59047a81c | venkateswararao-kotha/it-cert-automation-all-modules | /part1_week5/sample2_try_block.py | 995 | 3.9375 | 4 | import math as mymath
import unittest
# THIS CODE NEEDS TO BE FIXED, add function not available...
# i modified mymath module as math module from original code.. mymath is old module it seems , study more
class TestAdd(unittest.TestCase):
"""
Test the add function from the mymath library
"""
def test_a... |
15c8248231f11d026a1ac4387e7b71b7a75084f7 | shach934/leetcode | /leet662.py | 2,387 | 4.21875 | 4 | 662. Maximum Width of Binary Tree
Given a binary tree, write a function to get the maximum width of the given tree. The width of a tree is the maximum width among all levels. The binary tree has the same structure as a full binary tree, but some nodes are null.
The width of one level is defined as the length betw... |
d3545f4edcaf8548f32d38343e27dd59c65c2b0c | k1xme/leetcode | /python/swapPairs.py | 927 | 3.859375 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# @param {ListNode} head
# @return {ListNode}
def swapPairs(self, head):
if not head: return None
dummy = ListNode(0)
dummy.next = h... |
02484ac106c507a5f6fa337632c317230de41a6b | qTipTip/SplineToolKit | /SplineTK/lib.py | 3,917 | 3.75 | 4 | import numpy as np
def index(x, t, eps=np.spacing(1)):
"""
Given an array t and a value x, return the index i such that
t_i <= x < t_i+1. If x is equal to the last element of t, return the second to last index. If no
such element is found, return -1.
:param eps: floating point value comparison to... |
26d95e3f98bcb5f6769243e76ea0e14321ff69b3 | vitorgabrielmoura/Exercises | /Python 3/Curso_em_video/d96.py | 339 | 3.765625 | 4 | def area(a,b):
art = a*b
print(f'A área do seu terreno {a}x{b} é de {art}m²')
while True:
largura = float(input('Largura: '))
comp = float(input('Comprimento: '))
area(largura,comp)
resp = ' '
while resp not in 'SN':
resp = input('Deseja continuar? [S/N]').upper()
if resp == 'N... |
49c6347e8cb2e14768f717ef1e2862a1fab55639 | jaf88/My-URI-Judge | /1172.py | 774 | 3.609375 | 4 | __author__ = 'joaquim'
"""
URI Online Judge | 1172
Substituição em Vetor I
Adaptado por Neilor Tonin, URI Brasil
Timelimit: 1
Faça um programa que leia um vetor X[10]. Substitua a seguir, todos os valores nulos e negativos do vetor X por 1.
Em seguida mostre o vetor X.
Entrada
A entrada contém 10 valores inteiros, pod... |
c818b38714afc0fa89d2c00558ff19bb13613a8d | tana777/LeetCode | /Search/20_Valid_Parentheses.py | 1,671 | 4.0625 | 4 | """
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Example 1:
Input: s = "()"
Output: true
Example 2:... |
1e863dfe6b95f14546b67459a02b9e1cb2fa6e6a | here0009/LeetCode | /MockInterview/3_reverseKGroup.py | 1,734 | 3.875 | 4 | """
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is.
Follow up:
Could you solve t... |
d4bd070a20ed5f22f9862fd6b3920a825b5d192f | vpunugupati/CodingPuzzles | /LeetCode/BackspaceStringCompare.py | 572 | 3.78125 | 4 | def backspaceStringCompare(S:str,T:str) -> bool :
# def build(S):
# res = []
# for c in S:
# if(c != '#'):
# res.append(c)
# elif res:
# res.pop()
# return "".join(res)
# return build(S) == build(T)
def get_string(st):
... |
60c0e776441396d70746411bad1754d176562b2d | fpgodoy/Exercicios-Python | /ex070.py | 790 | 3.578125 | 4 | total = mais = pricebarato = 0
barato = ''
print('-' * 40)
print('{:^40}'.format('LOJA SUPER BARATÃO'))
print('-' * 40)
while True:
nome = str(input('Nome do Produto: '))
price = float(input('Preço: R$'))
if total == 0:
pricebarato = price
total += price
if price > 1000:
mais += 1
... |
632c850eb5d3c685e49d17fb8f644ce40c8ffe03 | Madalinbv/Python-test-files | /zip_functions/zipping.py | 614 | 3.84375 | 4 | list1 = [1,2,3,4,5]
list2 = ['one','two','three','four','five']
zipped = list(zip(list1,list2))
print(zipped)
unzipped = list(zip(*zipped))
print (unzipped)
for (l1, l2) in zip(list1, list2):
print(l1)
print(l2)
items = ['Apple','Banana','Orange']
counts = [3,6,4]
prices = [0.99, 0.25, 0.5]
sentences = ... |
746659eb70137c971deb5f9112b7d927b509e865 | LucasDonato333/CursoEmVideo | /Python/Exercicios/ex037.py | 644 | 4.125 | 4 | print('''
Escreva um programa que leia um número inteiro qualquer e
peça o usuário escolher qual será a base de conversão:
-1 para binário
-2 para octal
-3 para hexadecimal''')
print(25 * '-=-')
n = int(input('Digite um valor: '))
print('''\nEscolha uma opção
\033[32m[ 1 ] BINÁRIO
[ 2 ] OCTAL
[ 3 ] HEXADECIM... |
d0b54e3adb457fba64ec2daca92d66c97694b4b7 | ay2306/Algortihms | /Machine Learning/Logistic Regression/logisticRegression.py | 3,136 | 3.515625 | 4 | import numpy as np
import math
def hypothesis(x,theta):
sum = 0
i = 0
while i < len(x):
sum = sum * (x[i]*theta[i])
i = i + 1
num = (1/(1+math.exp(-1*sum))) #Note that math.exp(x) returns e^x
return num
def totalCostFunction(x,y,theta):
sum = 0
i = 0
for i in range(len... |
88327eac301535cdbb50d3d86854d70e8c87e2db | Komeroshii/TAlight | /problems/number_theory/infinity_of_primes/evaluator.py | 1,312 | 3.734375 | 4 | import random
import turingarena as ta
def eratostene(givenNumber):
# Initialize a list
primes = []
for possiblePrime in range(2, givenNumber + 1):
# Assume number is prime until shown it is not.
isPrime = True
for num in range(2, int(possiblePrime ** 0.5) + 1):
... |
bd01fcc9bbb0c030e088cefe8beb3a4868f8bd4f | htmlprogrammist/kege-2021 | /tasks_12/task_12_26986.py | 702 | 3.546875 | 4 | """
На вход приведённой ниже программе поступает строка,
содержащая 40 цифр 7, 40 цифр 9 и 50 цифр 4,
расположенных в произвольном порядке.
Запишите без разделителей символы,
которые имеют порядковые номера 25, 71 и 105 в получившейся строке.
"""
s = '7' * 40 + 40 * '9' + 50 * '4'
while '49' in s or '97' in s or '47'... |
e07066f3bc7c6edfba76737adf476ac61974cb4e | nityamall/Python_Projects | /workspace/HelloWorld/PRIME_RANGE.py | 321 | 3.8125 | 4 | range1=input("Input the lower range")
range2=input("Input the highest range")
range1=int(range1)
range2=int(range2)
for steps in range(range1,range2+1):
flag=1
for steps1 in range(2,steps):
if((steps%steps1)==0):
flag=0
break
if (flag==1):
print("%d "%steps... |
339c797219b524d543b4fd70128ea608d45a60fd | wangkai314/leetcode | /practice.py | 751 | 3.578125 | 4 | class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0:
return False
s = str(x)
palindrom = ''
for i in range(len(s)):
len1 = len(self.getLongestPalindrom(s, i, i))
if len1 > len(palindrom):
palindrom = self.getLongestPal... |
3b1c2c1405c24eaf359161cf56ef2973f1ec2c44 | EveEuniceBanda/Beginners-Labs | /try_this Lab 19.py | 1,139 | 3.796875 | 4 | #!/usr/bin/env python3
#Original tuple
chicago_zoo_tuple = ('Kangaroo', 'Leopard', 'Moose', 'Polar Bear', 'Bobcat')
sandiego_zoo_tuple = ('Kangaroo', 'Lion', 'Grizzly Bear', 'Wildcat', 'Antelope')
print("TUPLES...")
print('Chicago Zoo:',chicago_zoo_tuple)
print('San Diego Zoo:',sandiego_zoo_tuple)
print()
... |
334935faf9245a1d0b90e514deb37cc11d90c698 | Umair-Manzoor-47/Semester-2 | /week 1/SquareORnot.py | 291 | 4.3125 | 4 | length = 0
width = 0
length = int(input("Enter length of Shape : "))
width = int(input("Enter Width of Shape : "))
if length != 0 and width != 0 :
if length == width:
print("This is Square")
else:
print("This is NOT a Square")
else :
print("It's not a Shape")
|
5a25bebb9796d2b5143a9f371d0710371332b40d | bukandu1/code-challenge-practice | /leet_code/search_target.py | 1,442 | 4.15625 | 4 | # Given a sorted array and a target value, return the index if the target is found.
# If not, return the index where it would be if it were inserted in order.
# You may assume no duplicates in the array.
import unittest
class Solution:
def searchInsert(self, nums, target):
left = 0
right = len(nu... |
ce7c37dde5276d87b0fe512b69b07abff8b5b2e1 | leon0241/adv-higher-python | /Pre-Summer/nat 5 tasks/task 11/task_11a.py | 162 | 4 | 4 | total = 0
for counter in range (1, 11):
print("please enter value", counter)
value = int(input())
total = total + value
print("the total is", total)
|
dc7d0cf706131e096dd8076eb18224f446458d61 | pvd0anh/Learn-python | /Examble_day_1_OOP/KeThua.py | 1,483 | 3.53125 | 4 | class ConNguoi:
def __init__(self, Ho_Ten, Gioi_Tinh, Ngay_Sinh):
self.Ho_Ten = Ho_Ten
self.Gioi_Tinh = Gioi_Tinh
self.Ngay_Sinh = Ngay_Sinh
def in_thong_tin(self):
print("Ho ten:", self.Ho_Ten)
print("Gioi Tinh:", self.Gioi_Tinh)
print("Ngay Sinh:", self.Ngay_Si... |
36c59a05672b60aa08d253a6d2c01fe2aa2cce66 | mengnan1994/Surrender-to-Reality | /playground/LinkedListPlayground.py | 1,059 | 3.703125 | 4 | class SingleListNode(object):
def __init__(self, x, next=None):
self.val, self.next = x, next
class SingleLinkedListUtil(object):
@staticmethod
def build_linked_list(nodes: list):
if not nodes:
return None
head = SingleListNode(nodes[0])
curr = head
for... |
fe7e6c6d348c117a1bab42a97bf7fdce4670563f | clementeqp/Python_Datos | /Matplotlib/Ejercicio_2.py | 582 | 3.859375 | 4 | """
Escribir una función que reciba un diccionario con las notas de
las asignaturas de un curso y una cadena con el nombre de un color
y devuelva un diagrama de barras de las notas en el color dado.
"""
import matplotlib.pyplot as plt
def diagrama_barras(notas, color):
fig, ax = plt.subplots()
#... |
f948e82ef29759c31cda4923beea841bb77c80bc | djsnipa1/python-shit | /colormind/curses_tutorial.py | 1,364 | 4.3125 | 4 | # coding=utf-8
"""
Tutorial from here:
Curses in Windows with Python | DevDungeon
https://www.devdungeon.com/content/curses-windows-python
"""
import curses
# The `screen` is a window that acts as the master window
# that takes up the whole screen. Other windows created
# later will get painted on to the `screen` wind... |
74647fe285df53f9dec173c124f9a5bcec116343 | krora/Bioinfo-Python | /q2-q4.py | 5,102 | 3.6875 | 4 | #!/usr/bin/env python
# Improved breakpoint reversal sort
# Example: ./prob3.py 8 2 7 6 5 1 4 3
# Based on: cs.helsinki.fi/u/tpkarkka/opetus/14s/AfB/exercise2_problem3.py
import sys
import itertools
# Returns the number of breakpoins.
# Equal to b() in the course book.
# Requires linear time.
def b(u):
assert u[... |
5e75dff49e334c7b45cdc9741560872fd0cdbbc7 | OddExtension5/ProgrammingBitcoin_from_scratch | /elliptic_curve.py | 4,382 | 4.3125 | 4 | # Elliptic curves are useful because of something called point addition.
# Point addition is where we can do an operation on two of the points on the curve and get a third point, also on the curve.
# It turns out that for every elliptic curve, a line will intersect it at either one point or three points, except in a... |
d63484367871c65577678bee6614187a5b78bade | leasleiman/GameTheory-and-anxiety- | /GameOther.py | 2,303 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 9 14:53:21 2019
@author: Lea
"""
from player import Player
import time
from math import exp
import random
class Game:
#initialize a game with a player, a rate of stcok growth, and the initial value of the stock
def __init__(self, player, rate, initValu... |
3ef5e76ea2bccc943b9d86ff022c2d9a87aef682 | mathsigit/python-practice | /Basis/basis/variables.py | 542 | 3.9375 | 4 | #!/usr/bin/env python3
#-*-coding:utf-8-*-
class PointOfVariables():
a = "Hello Python"
print("a="+a)
print("Assigning b equals a")
b = a
print("b=" + b)
print("a=" + a)
a = "1234567890"
print("Re-asign value of a.")
print("a=" + a)
print("b=" + b)
class MultipleVariablesAssi... |
787c630dc877202469dab4a7b375235085c67ae1 | aaronspindler-archive/CSCI1030U | /Labs/lab06.py | 2,282 | 3.90625 | 4 | """
Description: Lab that is used to practice defining and using functions in python
Functions in File: approximatePi, getMembersInRange, and removeEven
"""
#Importing the library needed for this program
import math
import sys
#A function to approximate the value of pi using Archimedes method.
def approximatePi(epsil... |
e71978e1f63b8b715ad5891389591933b1dcefd7 | Nivethika7623/sample2 | /B115.py | 216 | 3.546875 | 4 | def small2(l1,k1):
l1.sort()
return l1[k1-1]
def main():
try:
n1=int(input())
k1=int(input())
l1=[]
for i in range(n1):
l1.append(int(input()))
print(small2(l1,k1))
except:
print('invalid')
main()
|
ecfba223913eb8950a592448970f7e3cd3fb499c | trepudox/Python | /UNIP/LPA/LISTA LPA/exe3.py | 170 | 4.125 | 4 | x = int(input('Digite um número: '))
y = int(input('Digite outro número: '))
triplo = 3 * (x * y)
if triplo > 25:
print((x+y)**3)
else:
print((x**3) + (y**3)) |
996bae8b9a6914125fc6dba838d2854a1c8b9863 | kalliroku/python_Algorithm_data_structure | /graph_BFS_DFS.py | 6,547 | 3.625 | 4 | class Graph:
def __init__(self, max_vertex_count, direct=0, array=0):
self.max_vertex_count = max_vertex_count
self.current_vertex_count = 0
self.directed_graph = direct
self.vertex_list = [0] * (max_vertex_count + 1)
self.edge_matrix = []
self.array_graph = array
... |
5ba08050c825b7be4700d6362d0d0736bc9e73f2 | BU-EC552/ibis | /ibis/datastucture/logic.py | 16,983 | 3.515625 | 4 | """
--------------------------------------------------------------------------------
Description:
Functionality related to parsing verilog and generating logical networks.
Written by W.R. Jackson, Ben Bremer, Eric South
--------------------------------------------------------------------------------
"""
from dataclass... |
66977a5e5259b7dee8e6e07e143fa426d506e308 | MarcosBan/IMPACTA-PROGRAMACAO | /ATIV-TEC-PROG-22-04.py | 610 | 3.640625 | 4 | #Atividade 2 - 22/04 - Marcos Silva 1902671
percentil = float(input("Informe o percentual: "))
valorReal = float(input("Informe o valor do produto: "))
teste = 0
while teste != 1:
if percentil > 0 and percentil <=1:
percentilFloat = percentil * 100
novoValor = percentilFloat*valorReal/100
pr... |
bac91655f839329d34a3210c3dfc04b88fba6e5a | aamer-qadeer/PIAIC | /PIAIC119005_Assignment1.py | 6,504 | 3.921875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[3]:
#Import the numpy library (01)
import numpy as np
print (np.__version__)
# In[6]:
#Define the 1D array
arr1 = np.array([0,1,2,3,4,5,6,7,8,9])
print(arr1)
# In[18]:
#Define the 2D array (02)
arr2 = np.array([[11,12,13,14],
[21,22,23,24],
... |
414736a9a98be7a8ae6398115021d2c298559724 | clusterfudge/dlnd-project-1 | /project1-tests.py | 1,156 | 3.5625 | 4 | import unittest
from project1 import *
np.random.seed(42)
inputs = [0.5, -0.2, 0.1]
targets = [0.4]
class TestMethods(unittest.TestCase):
##########
# Unit tests for network functionality
##########
def test_activation(self):
network = NeuralNetwork(3, 2, 1, 0.5)
# Test that the activ... |
e4f8829df7589af1a318cdf8b5ef7d815d76fb65 | SuperJason/python | /chaos/dbm_watt.py | 461 | 3.625 | 4 | #!/usr/bin/env python3
"""
Plot dBm to Watt
"""
import numpy as np
import matplotlib.pyplot as plt
plt.figure(num=3, figsize=(8,5))
start = -125
end = 35
length = 1600
dBm = np.linspace(start, end - (end - start)/length, length)
mW = 10**(dBm/10)
plt.plot(dBm, mW)
plt.xlim((-125, 35))
plt.ylim((0, 2000))
plt.xl... |
f016dabf47c6b3fd45dc801932e70a9a7fadbac8 | Sin-Yejun/PPS | /week3/14-7_신예준_20210724.py | 161 | 3.5 | 4 | n = int(input())
d = []
for i in range(n):
w = input()
d.append(w)
x = set(d)
d = list(x)
d.sort()
d.sort(key = len)
for i in d:
print(i)
|
2dacca7641922d85a513d4425904eb4ad50ff1e0 | emmanuellabrunye/BalloonTip | /BalloonTipExample.py | 530 | 3.515625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from BalloonTip import BalloonTip
if __name__ == '__main__':
balloon = BalloonTip("Example of BalloonTip class", icon="example.ico")
balloon.create_tray_icon()
number = raw_input("Podaj liczbe: ")
if number.isdigit():
balloon.show_t... |
b1defe0299a9a58aa79162e3446f8bf542613d7f | Offliners/Python_Practice | /code/100.py | 252 | 3.890625 | 4 | # matching more than one number
import re
data = "2019-05-01"
match = re.search("(\d+)-(\d+)-(\d+)",data)
if match:
print(match.groups())
# this is a tuple:
print(type(match.groups()))
# Output:
# ('2019', '05', '01')
# <class 'tuple'>
|
7f83791cab5c5ec3194f7fb82719327b8e4c6c48 | Blue6641/c4t-15 | /session 1/session1.py | 1,024 | 3.828125 | 4 | # 1+1
# # py
# # name = "Voz"
# # print ("name")
# print (name)
# print (11)
# if
# else:
# name = 58
# if name < 30:
# print("Rainy")
# if 30 < name < 60:
# print("Cloudy")
# else:
# print("Sunny")
# if name == 59:
# print ("TH1")
# if name == 58:
# print ("TH2")
# 'username = "techkids"... |
ed91b5005f272711ba8acc4e7c47698186ccd6a0 | smilodon410/Python_code_study | /pythonPractice/dictionary.py | 1,843 | 3.875 | 4 | # Dictionary 를 활용한 Count
# counts = dict()
# names = ['csev', 'cwen', 'csev', 'zqian', 'cwen']
# for name in names:
# if name not in counts:
# counts[name] = 1
# else:
# counts[name] = counts[name] + 1
# print(counts)
# Dictionary : get 함수
# counts = dict()
# names = ['csev', 'cwen', 'csev', 'z... |
ebbcb634656a157a934fea40e89f472b9c6466fa | dylanlee101/leetcode | /code_week32_1130_126/create_maximum_number.py | 1,888 | 3.546875 | 4 | '''
给定长度分别为 m 和 n 的两个数组,其元素由 0-9 构成,表示两个自然数各位上的数字。现在从这两个数组中选出 k (k <= m + n) 个数字拼接成一个新的数,要求从同一个数组中取出的数字保持其在原数组中的相对顺序。
求满足该条件的最大数。结果返回一个表示该最大数的长度为 k 的数组。
说明: 请尽可能地优化你算法的时间和空间复杂度。
示例 1:
输入:
nums1 = [3, 4, 6, 5]
nums2 = [9, 1, 2, 5, 8, 3]
k = 5
输出:
[9, 8, 6, 5, 3]
示例 2:
输入:
nums1 = [6, 7]
nums2 = [6, 0, 4]
k = 5
输出:
... |
0de55b41605c87cd0d33afa9ba51f0de729e0f6e | nsid10/Project-euler | /problems/052.py | 263 | 3.8125 | 4 | def numset(n):
num = []
for i in str(n):
num.append(int(i))
num.sort()
return num
n = 1
while True:
if numset(n) == numset(n * 2) == numset(n * 3) == numset(n * 4) == numset(n * 5) == numset(n * 6):
break
n += 1
print(n)
|
59e29bb39989fefa9132502078addda9fb6094a2 | windn19/Python_Developer | /lesson_6/divisor_master.py | 4,231 | 3.890625 | 4 | def prime_def():
"""
нахождение множества простых чисел
"""
prime_set = set(range(1, 1001)) # множество всех чисел от 1 до 1000
for i in range(2, 101): # перебор всех чисел от 2 до корня из 1000
if i in prime_set: # если очередное число в множестве
prime_set -= set(range(2 * i... |
95fc3fa58f8e68abd85d9ce9f0d620426a939fd3 | SudoBobo/algorithms | /section623/lesson13258/step41605/src/main.py | 787 | 3.640625 | 4 | import numpy as np
def editing_distance(first_word, second_word):
f = np.array(list(first_word))
s = np.array(list(second_word))
n = range(len(f) + 1)
m = range(len(s) + 1)
D = np.array([[1000000 for i in n] for j in m])
for i in m:
D[i, 0] = i
for j in n:
D[0, j] = j
... |
450caddf395d8244a525405cbe0169310e6f81a3 | chichutschang/6.00.1x-2T2016 | /Week 1/Exercise 5.2.py | 157 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Sep 3 15:02:22 2016
@author: chi-chu tschang
"""
divisor = 2
for num in range(0, 10, 2):
print(num/divisor) |
a85eead16a2ed67c607fefc73f86746b9a6796a2 | jakekrafczyk/Data-Structures | /doubly_linked_list/doubly_linked_list.py | 5,389 | 4.40625 | 4 | """Each ListNode holds a reference to its previous node
as well as its next node in the List."""
class ListNode:
def __init__(self, value, prev=None, next=None):
self.value = value
self.prev = prev
self.next = next
"""Wrap the given value in a ListNode and insert it
after this node.... |
91edc904689f542ffff2e51ec9a55989a5bec3fe | neoBontia/cse210-student-hide-and-seek | /hide_and_seek/game/hider.py | 1,901 | 4.28125 | 4 | import random
class Hider:
""""A code template for a the hider. The responsibility of
this class of objects is to spicify a location that the
seeker has to guess and give hints to the seeker according
to its distance from the hider.
Stereotype:
Information Holder
Service Prov... |
19af4706a25f987bc099e831bb851fb4da60eb19 | yansong6688/CS543-Computer-Vision | /MP4/cifar100_cs543.py | 19,280 | 3.96875 | 4 | """
This file has been adapted from the easy-to-use tutorial released by PyTorch:
http://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html
Training an image classifier
----------------------------
We will do the following steps in order:
1. Load the CIFAR100_CS543 training, validation and test datasets usin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.