blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
dfa1e86be7a5995715ff3392810af757693f4602 | sdas13/DSA-Problems | /string/easy/15. greatest-common-divisor.py | 1,397 | 3.75 | 4 | """
Given two strings str1 and str2, return the largest string x such that x divides both str1 and str2. we say "t divides s"
if and only if s = t + ... + t (t concatenated with itself 1 or more times)
https://leetcode.com/problems/greatest-common-divisor-of-strings/discuss/516621/Java-clean-solution-(0-ms)-100
Expla... |
82b4395ad6962736ffa1648bd25d226a90d7e467 | darknetworm/HomeWork03 | /homeWork05.py | 914 | 3.734375 | 4 | total = 0
def summary(nums):
'''
Возвращает сумму введенных пользователем чисел, игнорируя любые другие символы
:param nums: введенные пользователем значения
:return: сумму чисел в глобальную переменную
'''
newList = []
for i in range(len(nums)):
try:
newLis... |
2f74a4445ee78a261bb5a7807d39e621d04887d2 | sanchezpe/pythonproject8 | /pa8.py | 3,733 | 3.578125 | 4 | class Account():
def __init__(self, idIn, balanceIn): # note, the initializer is passed 2 parameters
self.__id = idIn
self.__balance = balanceIn
self.__depositCount = 0
self.__withdrawalCount = 0
self.__depositSum = 0
self.__withdrawalSum = 0
def GetId(se... |
c0ffa13d82654212b5d3a11accb0200fcd853591 | daniel-reich/ubiquitous-fiesta | /vuSXW3iEnEQNZXjAP_18.py | 344 | 3.8125 | 4 |
def create_square(length):
def string(i,j):
return "#" if min(i,j) == 0 or max(i,j) == length - 1 else " "
if length is None:
return ""
elif length < 1:
return ""
else:
s = ""
for i in range(0,length):
for j in range(0,length):
s += string(i,j)
if i < length - 1:
... |
8978e7cdffe3e91f16d3d4dd4c904abaef392ef6 | daltonamitchell/python-algorithms | /lib/morse_code.py | 1,002 | 4.34375 | 4 | """
Build a function, `morse_encode(str)` that takes in a string (no
numbers or punctuation) and outputs the morse code for it.
See http://en.wikipedia.org/wiki/Morse_code.
Put two spaces between words and one space between letters.
"""
MORSE_CODE = {
'a': '.-',
'b': '-...',
'c': '-.-.',
'd': '-..',
... |
0481bb1e8c8d2bfff84770b6949fb61372468b23 | karpust/runstone | /3. Analysis.py | 6,163 | 3.84375 | 4 | """3.7. Dictionaries"""
# import timeit
# import random
#
# for i in range(10000,1000001,20000):
# t = timeit.Timer("random.randrange(%d) in x"%i,
# "from __main__ import random,x")
# x = list(range(i))
# lst_time = t.timeit(number=1000)
# x = {j:None for j in range(i)}
# ... |
90e36977652b734d6bb686792476d94b5ba689bb | calmkart/core_python | /1-2.py | 155 | 3.578125 | 4 | import re
def helper():
str_test = input("input str:")
m = re.findall("[a-zA-Z]+\s[a-zA-Z]+",str_test)
print(m)
return 1
helper() |
171aaf67949f9283900a8749dd80aa87b871516d | valcakova/git_battleship | /Battleship2.py | 1,372 | 4.3125 | 4 | # A board is a list of rows, and each row is a list of cells with either an 'X' (a battleship)
# or a blank ' ' (water)
board = [
[' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' '],
]
# We want to refer to columns by ... |
192c452eac4f8ebd455a1d80b423e9e78eb17aac | hungpchu/code-interview | /differentPair.py | 755 | 3.765625 | 4 | array = [1, 7, 5, 9, 2, 12, 3]
diff = 2
dict = {}
def differ(array,dict,diff):
count = 0
for value in array:
dict[value] = value
print ("dict = ", dict)
for value in array:
if (dict.get(value + diff) ):
print("value = 1st", value)
print(" dict.get(... |
fe291ba7fc641042f768f50f6294a1d4b09168d5 | jiwonryu/Practice-Project_Python | /Week8_MidtermProject/커피 시도.py | 2,210 | 3.6875 | 4 | # 2 커피 자판기
print("\n\n# 2번 문제: 커피 자판기\n")
# 2-1)
class Twosome:
def __init__(self, price, cal, rest):
self.__price = price
self.__cal = cal
self.__rest = rest
# 2-2)
def getRest(self):
if (self.__rest) == 0:
print("죄송하지만 선택하신 음료의 잔여 수량이 0입니다.\n선택하신 음료를 판매할 수 없습니다."... |
303769ff2e34eb1a0507afa47e109bb40ebee424 | kewy76/ICP5 | /One.py | 837 | 3.640625 | 4 | # Kate Williams
# 6/19/2018
# Import packages
import numpy as np
import matplotlib.pyplot as mpl
# Create lists
x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
y = [1, 3, 2, 5, 7, 8, 8, 9, 10, 12]
mpl.plot(x, y, 'bo')
mpl.show() # Plot initial points
# y = mx + b
# Find m (slope)
mx = np.mean(x) # The mean of ... |
cf74dbcc6ab49f881c9d65beb459f43a2fee47c8 | rossardy/python_staff | /cube.py | 238 | 4.0625 | 4 | number = int(raw_input("Input some numbers: "))
def cube(number):
return number*number*number
def by_three(number):
if cube(number)==number*number*number:
print number
else:
return False
by_three(number)
|
98426ab789911abda9ce4fbef3ccbbdd0e5153b6 | mohdanwaroddin/Hacktoberfest-2024 | /pallindrome.py | 185 | 3.875 | 4 | n=int(input())
temp=n
sum1=0
while(n!=0):
r=n%10
sum1=(sum1*10)+r
n=n//10
if(temp==sum1):
print("Number is Pallindrome")
else:
print("Number is not Pallindrome")
|
44c698b884770d2790e06c25e34bb6e89c6a3845 | BethanyFolino/nodict | /nodict.py | 2,948 | 4.28125 | 4 | #!/usr/bin/env python3
"""
Implementation of the NoDict assignment
"""
__author__ = 'Bethany Folino with help from Jacob Short and Matt Perry'
references = """https://www.pythontutorial.net/python-oop/python-__eq__/#:~:text=
Python%20automatically%20calls%20the%20__,
the%20__eq__%20method... |
4234c81162a1265d4188d1c1d0be050e2e5f87e8 | Portojowsky/bigoofmaboi | /ISD Assignment/Week 4/Task 3.py | 227 | 4.15625 | 4 | #Task 3
radius = input(float("Enter the radius: "))
#The input and float need to be reversed in order for this code to work
radius = float(input("Enter the radius: "))
#Here is the same code, but written correctly
|
eb3bf0b21286b72885409ad7e79f43a1c5891967 | dsrlabs/PCC | /CH 7/7_5_MovieTickets.py | 842 | 4.21875 | 4 | prompt = "How old are you?"
prompt += "\nEnter 'quit' when you are finished. "
# The following line of code accepts the age of the moviegoer as an integer
print()
# The following lines of code compares uses an if-elif-else chain to determine the ticket cose per age range
while True:
age = input(prompt)
if age ... |
e6912c50dda95eb57c0b7bfdf232cc5501d74cb3 | EnricoCB/python | /PythonEx/ex37.py | 369 | 4.0625 | 4 | n = int(input('Digite um número: '))
op = int(input('Digite 1 para binario / 2 para octal / 3 para hexadecimal: '))
if op == 1:
print(f'{n} convertido para binario é {bin(n)[2:]}')
elif op == 2:
print(f'{n} convertido para octal é {oct(n)[2:]}')
elif op == 3:
print(f'{n} convertido para hexadecimal é {hex(n... |
8582c563aba5dc933aef22e33ec092c8c0a0cb41 | MishaRuko/Machine-Learning-Algorithms | /MachineLearningAlgorithms.py | 4,690 | 3.515625 | 4 | import numpy as np
from math import sqrt
def meanOf(data):
mean = 0
for i in data:
mean += i
mean = mean/len(data)
return mean
def variance(data):
mean = meanOf(data)
variance = 0
for i in data:
variance += (i-mean)**2
variance = variance/len(data)
return variance
... |
bd8742377ada9442f1ae9b2b58dea70bd4f75886 | sjsawyer/algorithms | /logic/integer_no_temp_swap.py | 925 | 4.0625 | 4 | def swap(x, y):
'''
Swap x and y without creating a temporary variable
(Besides the obvious x, y = y, x pythonic approach)
Solution:
---------
Let ' denote the first update to a variable and
let '' be a second update to the same variable
# first, update x
x' = x + y
# second, ... |
aebdb21fcae6bd6723326db177374a72207a5a0f | gregjanowiak/LPTHW | /mystuff/ex21.py | 656 | 4.03125 | 4 | def add(a,b):
# print(f"ADDING {a} + {b}")
return a + b
def subtract(a,b):
# print(f"SUBTRACTING {a} - {b}")
return a - b
def multiply(a,b):
# print(f"MULTIPLYING {a} * {b}")
return a * b
def divide(a,b):
# print(f"DIVIDING {a} / {b}")
return a / b
print("let's do math with functions... |
94b3d62caf5e4c1650253b7fc68b9a168dc5b21d | JonathanTTSouza/turtle-crossing | /scoreboard.py | 765 | 4.15625 | 4 | from turtle import Turtle
FONT = ("Courier", 24, "normal")
class Scoreboard(Turtle):
def __init__(self):
super().__init__()
self.hideturtle()
self.penup()
self.goto(-280, 250)
def write_scoreboard(self, number_of_wins):
self.clear()
self.write(f"Level: {number... |
16b4535f3b289d55174d58d96125fb3420a3719b | MyreMylar/pygame_basics | /pygame_basic.py | 5,017 | 3.65625 | 4 | import os
import pygame
from pygame.locals import *
def main():
is_left_key_down = False
is_right_key_down = False
sprite_x_pos = 300.0
sprite_y_pos = 400.0
sprite_y_vel = 0.0
pygame.init()
os.environ['SDL_VIDEO_CENTERED'] = '1' # center the window in the middle of the screen
screen... |
7e21f848071c49af0d6821c1fd32c0ff6ac84fe7 | sinasab/cse5914 | /src/brutus-module-weather/brutus_module_weather/owmWeather.py | 1,533 | 3.5 | 4 | import pyowm
import os
def process_input(api_key, string):
cityid = 4509177
owm = pyowm.OWM(api_key)
obs = owm.weather_at_id(cityid)
try:
weather = obs.get_weather()
except AttributeError:
return "Unable to retrieve weather for the specified city"
if("temperature" in string.lo... |
d571c5c326bb2fdec85b214b3834162873d39f81 | satyx/Data-Structure-Practice | /BFS.py | 1,011 | 3.8125 | 4 | tree=[]
stack=[]
def add_node(data):
global tree
tree.append(data)
def dfs_inorder(key):
global tree
if 2*key<=len(tree):
inorder(2*key)
print(tree[key-1])
if 2*key+1<=len(tree):
inorder(2*key+1)
def dfs_preorder(key):
global tree
print(tree[key-1])
if 2*key<=len(tree):
preorder(2*key)
if 2*key+1<=len(... |
3bb55962d7ff5de0d4f5f4a143d75b940aa90cca | mjpatter88/ProjEuler | /Problem099/solver.py | 663 | 3.703125 | 4 | # The key insight for this problem is that you can get the number of digits in
# a ^ b by doing b * log(a, 10). This is a must faster operation than actually
# calculating the value of the exponent.
import math
import operator
lines_to_num_digits = {}
with open("base_exp.txt") as in_file:
lines = [line.strip() fo... |
a130b59f9e9fdf9ff5ce06d62982ded038aa4930 | toroleyson/data-prework | /1.-Python/1.-Snail-and-Well/Problem 1 Bonus - Arnoldo Leyson.py | 1,720 | 3.90625 | 4 | Python 3.6.8 (v3.6.8:3c6b436a57, Dec 24 2018, 02:04:31)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license()" for more information.
>>> import statistics
>>>
>>> well_height = 125
>>> advance_cm = [30, 21, 33, 77, 44, 45, 23, 45, 12, 34, 55]
>>> nightly_di... |
989176850a554d6ad867bc6002a8ac78d32ef77c | detcitty/100DaysOfCode | /python/unfinshed/oppositesAttract.py | 695 | 4.1875 | 4 | # https://www.codewars.com/kata/555086d53eac039a2a000083/train/python
'''
Timmy & Sarah think they are in love, but around where they live,
they will only know once they pick a flower each. If one of the
flowers has an even number of petals and the other has an odd number of petals it means they are in love.
Write a... |
7151ca8a6335148a37c17f0804e784ad7403a88c | holysll/Leetcode | /0144_binary-tree-preorder-traversal.py | 4,579 | 3.796875 | 4 | # !/usr/bin/env python
# -*- coding:utf-8 -*-
# some description
# author: holysll
# datetime: 2020-7-10 20:42
# software: PyCharm
"""
题目:二叉树的前序遍历
给定一个二叉树,返回它的 前序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,2,3]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-t... |
d6f6e141f06dd493188f876ef0c254ecdf975e93 | yitelu/FCC_advPython | /build_in_examples/the_dir.py | 828 | 4.09375 | 4 | # dir() Returns a list of the specified object's properties and methods
"""
dir(...)
dir([object]) -> list of strings
If called without an argument, return the names in the current scope.
Else, return an alphabetized list of names comprising (some of) the attributes
of the given object, and of attribu... |
54a5330ff655d3823c20880943e7833c44f0baf7 | tmarice/cp | /hackerrank/interviews/booking.com_sre/merge_overlapping_intervals.py | 587 | 3.546875 | 4 |
def merge_overlapping_intervals():
n = int(raw_input())
diffs = []
for _ in range(n):
start, end = [int(x) for x in raw_input().split()]
diffs.append((start, -1))
diffs.append((end, 1))
ints = []
start = None
cursum = 0
for t, d in sorted(diffs):
if curs... |
a3223c310c7caee46f25628869474c82fcd70753 | TXF95/SDN_MPLS-s | /topo/topo-6sw-2h.py | 1,274 | 3.8125 | 4 | """Custom topology example
Two directly connected switches plus a host for each switch:
host --- switch --- switch --- host
Adding the 'topos' dict with a key/value pair to generate our newly defined
topology enables one to pass in '--topo=mytopo' from the command line.
"""
from mininet.topo import Topo
class M... |
59724dbf0254a6c18aea7096d9d8d7cb3e647ca9 | Chan-Dru/g4g | /problem/Graph-MinInitialVertexToTraverse.py | 1,783 | 3.78125 | 4 | from Graph import Graph
class Test(Graph):
def __init__(self,v):
super().__init__(v)
def dfs(self,i,j,tc,n):
tc[i][j] = True
# print("=>",i,j)
if (i+1 < n) and (self.graph[i+1][j] <= self.graph[i][j]) and not tc[i+1][j]:
# print("down")
self.dfs(i+1,j,tc... |
ed154628d4efe9150f8d64406fbd9f0de20c9bf0 | Rosarya/HTML-Practice | /Pythonfiles/Elements.py | 189 | 4 | 4 | alist = [1, 2, 3, 4, 5, 6, 7]
def check(alist):
check = input("What number is in the list? ")
if check in alist:
print "True"
if check not in alist:
print "False"
check(alist)
|
bdf8327189dfcdc26fc922d207e5cd438663f559 | sgbbhat/SolderStationAuto | /Development/Graphics/createLabel.py | 448 | 3.625 | 4 | from tkinter import filedialog
from tkinter import *
from tkinter import messagebox
# Create a lable with passed parameters and place them in a location mentioned
def CreateLabel(root, Lname, Ltext , Lheight, Lwidth, Lrelief, Lbg, Lfg, Lfont, Lplacex, Lplacey):
Lname = Label(root, text = Ltext , height = Lheight, ... |
e801ab69bc7c7e18c930473b22a1fdf5f58efb5f | reinmind/py_note | /data_structure.py | 403 | 3.609375 | 4 | # combination data structure
# sequence : string, tuple, list
def f1():
s1 = 'This is python, but I love Java'
s2 = ['Jason', 'Luna', 'Galileo', 'Tracy']
s3 = (1, 1.1, 'str')
s2.append(s1)
print(s2[0::2])
print(s3[-1])
return 0
# set
def f2():
s = {'set', 123, '5'}
t = {'map', "5... |
55799a03bdb473a5a163ad4a55192bf0858c43fe | ederivero/CodigoBlended | /BackEnd/FullDay 15 de Febrero/09-ejercicios.py | 2,125 | 4.0625 | 4 | # Ejercicio 1: Teniendo una lista vacia, ingresar 5 numeros por el teclado e indicar cuales de ellos son primos
# primo => si solamente es divisible entre si y entre 1
# 1 3 5 7 11 13 17 19 23 ....
# https://matematicasies.com/Averiguar-si-un-numero-es-primo
# hint=> use un for con un range como tope el numero en cuest... |
53bd5f1ceb531f6d19593bb5334a38149cda83e8 | rodrigobmedeiros/Coursera-Introdution-To-Scientific-Computing-With-Python | /Exercises/ContaParesImpares.py | 529 | 3.875 | 4 | # escreva o seu programa
contagem = 'sim'
contapar = 0
contaimpar = 0
while contagem != 'não':
numero = int(input('Entre com um número inteiro positivo: '))
RestoDivisao = numero%2
if RestoDivisao == 0:
contapar = contapar + 1
else:
contaimpar = con... |
3078ee28022a75c30250e433d1f9ddf5a0177b14 | Ashikunnabi/python_programming | /basic/_37_sum_of_nth_number.py | 186 | 4.09375 | 4 | print("Enter 0 to end.")
print("Input numbers: ")
sum = 0
while True:
number = int(input())
if number == 0:
break
else:
sum += number
print("Sum =", sum)
|
b79debcce30795acacce4f8e813760059fa352d7 | icejoywoo/python-performance | /avoiding-dots-perf.py | 965 | 3.65625 | 4 | #!/usr/bin/env python2.7
# encoding: utf-8
"""
@brief:
@author: icejoywoo
@date: 15/12/7
"""
import perf
s = ['hello', 'world', 'python', 'is', 'test', 'itself', 'instead', 'of', 'internationlization']
def upper_common():
r = []
for i in s:
r.append(str.upper(i))
return r
def upp... |
dd41e26b785426a57ba09dfcd49fd351305832a9 | yuhao600/project-euler | /src/052. Permuted multiples/052.py | 395 | 3.859375 | 4 | def to_sorted_str(num):
return ''.join(sorted(str(num)))
n = 1
while True:
sorted_str = to_sorted_str(n)
if to_sorted_str(n * 2) == sorted_str and\
to_sorted_str(n * 3) == sorted_str and\
to_sorted_str(n * 4) == sorted_str and\
to_sorted_str(n * 5) == sorted_str and\
to_... |
db5ecd45ccf32d98b9298974bbb977bc74c856e3 | MartiCorbalan/python | /quiz.py | 1,468 | 3.953125 | 4 |
titulo="Bienvenido al test sobre queso"
print("\n" + titulo + "\n" + "-" * len(titulo)+"\n")
puntuacion = 0
opcion=input("Pregunta 1: Que haces quando ves una tabla de quesos?\n"
" A - Salgo corriendo\n"
" B - pruebo uno de los quesos o incluso varios\n"
" C - No puedo evitar d... |
91dc87ef5a4e9b1d129ca8758e43bd839aecbf57 | whitneygriffith/Introduction-to-Com-Sci-Labs | /combine_sorted_lists.py | 2,295 | 4.375 | 4 | '''
Problem 1: Combine sorted lists
Create a file named combine_sorted_lists.py. In it, write a function named CombineTwoSortedLists that combines two sorted lists into a single sorted list. For example, the two list: [3, 4, 7, 9] and [1, 4, 8], would be combined to make the list [1, 3, 4, 4, 7, 8, 9]. CombineTwoSort... |
97d819c35f37ff43312753f99c76b4f5079f5903 | iroshan/python_practice | /get_rainfall.py | 994 | 4.1875 | 4 | from collections import defaultdict
def get_rainfall():
"""collect amount of rainfall for cities and print the summary"""
# create the dict to collect data
# keeping the entered values in a list to use later.
cities = defaultdict(list)
while True:
# input for city name
city = input... |
e3fd1d8aa2ba0ba7024c68a6b80259965c423712 | CSC529GroupProjectDiabetes/DiabetesEnsemble | /datacleaning.py | 3,945 | 3.609375 | 4 | import pandas as pd
# Note: make sure to be on the directory that contains the data set file!!!
# Name of the NYCHANES file: orifile
orifile = 'public_v2_042618.sas7bdat'
# Using default parameters of read_sas to download NYCHanes data
data = pd.read_sas(orifile)
# print(data.head())
# Step 1: Take out r... |
4f55c9d1c5a00142b3fe186d3ec7001c12367e3e | ptresende/work | /learning/reasoning.py | 2,503 | 3.515625 | 4 | import copy
import math
def compare_lists(l1, l2):
# Maybe weigh differently the equal units and equal order measures
w_equal_units = 1#0.3
w_equal_order = 1#0.7
equal_units = 0
equal_order = 0
l1_temp = copy.deepcopy(l1)
l2_temp = copy.deepcopy(l2)
for c in l1:
if c in l2:
l1_temp.remove... |
2888f04459d8ca093ac1e851d84afb3ad8671f7c | syn7hgg/ejercicios-python | /29_4/7.py | 250 | 3.71875 | 4 | def determinante(m):
d = m[0][0] * m[1][1] - m[0][1] * m[1][0]
return d
try:
matriz = [[2, 3], [-1, 2]]
d = determinante(matriz)
print("matriz original: ", matriz)
print("determinante: ", d)
except:
print("Error")
|
53a4325e26797c5e2a32139b1c4e5955de6cca3c | GraydonHall42/Python-For-Data-Scientists-University-of-Calgary-ENSF-592 | /assignment-3-encryption-GraydonHall42/UserPrompter.py | 3,413 | 4.0625 | 4 | # Graydon Hall
import re
class UserPrompter:
"""
Used to communicate with the user. It includes methods to greet the user, get a message to be encoded or decoded,
and also obtain a valid cipher from the user, which is a 26 character string containing lowercase letters
and numbers only.
:param: n... |
580b79ca3dbfad9c517f0468ad8dadc4f9d0686a | CSC132/Final-Project | /Snake Game updated.py | 2,428 | 3.859375 | 4 | from Tkinter import *
from random import randint
master = Tk()
############## Buttons ###########################
def startGame():
pass
def stop():
master.destroy()
def instructions():
newwin = Toplevel(master)
display = Label(newwin, text="The goal of The Snake game is to eat the fruit to... |
f4ab428c63857e12667ef0f6a5f1ee0a76fc3178 | andscost/processo-seletivo-bolsas-2021 | /exercicio_listas/solution.py | 382 | 3.765625 | 4 | def subtracao_de_listas(lista1, lista2):
resposta = []
for elemento in lista1:
if elemento not in lista2:
resposta.append(elemento)
return resposta
def subtracao_de_listas_com_erros(lista1, lista2):
resposta = []
for i in range(0,len(lista1)):
if lista1[i] != lista2[i]... |
0bb1ee0f4cc8f1f1aeffac412dae4a32ca108d29 | jasmine2018jixun/leetcode2020 | /leetcode2019/fibonanci_number.py | 649 | 3.640625 | 4 | # def fib(n):
# nums = []
# for i in range(0, n):
# if i <= 1:
# nums.append(1)
# else:
# nums.append(nums[i-1] + nums[i-2])
# return nums[n-1]
# 进一步优化内存占用
def fib(n):
nums = [1, 1]
if n <= 2:
return 1
else:
for i in range(2, n):
... |
53a3479f44f73c9f1766d8ba7d4db45fc43c2f21 | DikranHachikyan/python-20201012 | /ex32.py | 695 | 4.15625 | 4 | # глобална променлива
value = 100
def foo(*args):
print('Hello pYthon')
# 1. дефиниция
def add_numbers(a, b, *args):
# c е локална променлива
# print(f'type of:{type(args)}')
# print(f'args:{args}')
c = a + b
for v in args:
c += v
return c
if __name__ == '__main__':
# 2. извик... |
ab424f6ee5d9315987bc8985e2375a68f52f8fbe | Quinnan-Gill/Algorithms | /HackerRank/tree/general_tree.py | 821 | 3.6875 | 4 | class Node:
def __init__(self, value):
self.value = value
self.parent = None
self.right = None
self.left = None
class Tree:
def __init__(self):
self.root = None
def set_root(self, value):
self.root = Node(value)
return self.root
def set_right(se... |
e3a2d1d225c502a03a333be7b13f4988d4d15858 | bhuveetech/PythonCorporateTraining | /source/data_types_basics.py | 1,210 | 4.03125 | 4 | """ This module is to practise data types"""
a = 20
print(a)
print(type(a))
b = a
print(b)
print(type(b))
print(id(a), id(b))
print(a is b)
print("====== Changing the object for b ======")
b = "python"
print(a)
print(b)
print(type(b))
print(id(a), id(b))
print(a is b)
# ================== Sequential data type ======... |
037d222a7dba4608f1a52bd53b99c01d543a94c8 | marrerap/python102 | /largest_number.py | 87 | 3.578125 | 4 | num_list = [1, 2, 3, 7, 4, 5, 6]
print("This is the largest element: ", max(num_list)) |
e6a6e43019442097fcf5ee0aadb1a17f2618aab4 | adrija24/languages_learning | /Python/Day 3/Palindrome of a string.py | 194 | 4.28125 | 4 | """Palindrome of a string"""
s = input("Enter the string: ")
s1 = s[::-1]
if s==s1:
print("The string is a palindromic sequence")
else:
print("The string is not a palindromic sequence") |
0ebe45f7a938a81526e24bdf9229bd55bf0394a8 | puba5/Learn_DeepLearning | /perceptron.py | 1,854 | 3.90625 | 4 | import numpy as np
import matplotlib.pylab as plt
#계단 함수
def step_function(x):
return np.array(x > 0, dtype=np.int)
#시그모이드 함수
def sigmoid(x):
return 1 / (1 + np.exp(-x))
#ReLU 함수
def relu(x):
return np.maximum(0, x)
'''
x = np.arange(-5.0, 5.0, 0.1)
y = sigmoid(x)
plt.plot(x, y)
y = step_function(... |
8e503c3a8cae01f788bd77bc07ad751f45f0fc0c | rootpy/rootpy | /examples/tree/overwrite.py | 2,158 | 3.953125 | 4 | #!/usr/bin/env python
"""
======================================
Copy a tree while overwriting branches
======================================
This is an example showing how to copy a tree while overwriting one or more of
its branches with new values.
"""
print(__doc__)
from rootpy.tree import Tree, TreeModel, FloatCo... |
8f15dea9b66b044056a92ffa5e5383e1a0f9cfad | 17764591637/jianzhi_offer | /LeetCode/024_swapPairs.py | 1,876 | 3.9375 | 4 | '''
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例:
给定 1->2->3->4, 你应该返回 2->1->4->3.
思路:
1.找终止条件:本题终止条件很明显,当递归到链表为空或者链表只剩一个元素的时候,没得交换了,自然就终止了。
2.找返回值:返回给上一层递归的值应该是已经交换完成后的子链表。
3.单次的过程:因为递归是重复做一样的事情,所以从宏观上考虑,只用考虑某一步是怎么完成的。
''' ... |
0163ee4aa54d7dd79b1022056dc43eb3d166adf6 | joinalahmed/RC-tool | /sort_sim.py | 489 | 3.515625 | 4 | import pandas as pd
import csv
df = pd.read_csv('../../Desktop/test/smart.csv')
df = df.sort('Level-0')
df.to_csv('../../Desktop/test/Full_List_sorted.csv', index=False)
with open('../../Desktop/test/Full_List_sorted.csv', 'rb') as f:
reader = csv.reader(f)
your_list = list(reader)
row_ins=your_list[-1]
your_... |
232a1d2100591d014f247e1ccf4b883072781b19 | chenshaoping2015/pygame | /python_pratice/python_class/bicyle.py | 1,764 | 3.8125 | 4 | # -*- coding:utf-8 -*-
# @Time :2020/11/20 16:12
# @Author: stevenchen
'''
写一个Bicycle(自行车)类,有run(骑行)方法,
调用时显示骑行里程km(骑行里程为传入的数据);
再写一个电动自行车类EBicycle,继承自Bicycle,
添加电池电量valume属性,通过传入,同时有两个方法:
fill_charge(vol)用来充电,vol为电量,
'''
# 自行车类
class Bicycle:
def run(self, km):
print(f"自行车一共骑行了{km}公里")
# 电动自行车类
class... |
9e3f2bb936b5d35c32b8b3c40b54085c571b7f7f | Aasthaengg/IBMdataset | /Python_codes/p03362/s803908067.py | 564 | 3.625 | 4 | N = int(input())
MAX = 55555
def create_prime_list(n):
if n < 2:
return []
prime_list = [2]
x = 3
while x <= n:
flag = False
for p in prime_list:
if x < p ** 2:
flag = True
break
if x % p == 0:
break
... |
53b0dd57e05484f9fe1eb1418cb83f7141416501 | Brodski/Other-Projects | /Google Foobar/Level_2_bombReplicate/solutionPrint.py | 3,001 | 3.5625 | 4 | import math
import sys
def bombHelp2(M,F):
counter = 0
print '(F % M)', F,"%",M ,"=", float(F) % float(M)
print '(M % F)', M,"%",F,"=", float(M) % float(F)
while M >= 2 or F >= 2:
print counter, "(M,F)", [M,F]
if M < 1 or F < 1:
print "----... |
6d8bcd05fc6d88963ac7cff58adcbd545bdb1763 | aelk/loga | /sort/mergeSort.py | 371 | 4.125 | 4 | import heapq
def sort(arr):
"""Merge sort splits the input into two arrays,
recursively sorts each array, and then combines the two
with a merge subroutine (in this case from heapq)."""
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = arr[:mid]
right = arr[mid:]
left = mergeSort(left)
right = merge... |
203fb816778c2413f904b9525a6297ede70a7f9b | Yash-barot25/functions-timemodlues-ranges | /TimeFunction/reactiongame.py | 605 | 3.890625 | 4 | import time
from time import process_time as my_timer
# from time import perf_counter as my_timer
# from time import time as my_timer
# from time import monotonic as my_timer
import random
# print(my_timer())
input("Press enter to start")
wait_time = random.randint(1, 6)
time.sleep(wait_time)
start_time = m... |
9af52489b2c924cf89dceccd26b89e79b9b0c22c | DaftBeowulf/Whiteboard-Practice | /other/sort_around_target.py | 305 | 3.515625 | 4 | """
given an array and a target, sort the array where the numbers smaller
than the target are sorted to the left side of the target and numbers
larger than the target are sorted to the right side of the target
ex:
input:[6,5,2,3,8], 5
output : [2,3,5,6,8]
"""
# 4 potential approaches
# brute force #1:
|
dc5929b6f6eec93c1d108d92da4214ec5079f737 | BrodyJorgensen/CP1404 | /prac_03/password_entry.py | 215 | 4.0625 | 4 | """Brody Jorgesen"""
min_password_length = 3
password = input("Password: ")
while min_password_length >= 0:
if len(password) >= min_password_length:
print(len(password) * '*')
password = input("Password: ")
|
e4056a086569f29995dd5ba90ad30c392877a029 | cartman9999/Microsoft-Python-Summer-Camp | /second-class/list-exercise.py | 757 | 4.125 | 4 | if __name__ == '__main__':
# print('Cuantas veces quieres ejecutar:')
N = int(input())
list = []
for iteration in range(N):
# print('Introduce la opción:')
action = input()
# print('Ejecutando: ' + action)
if 'insert' in action:
list.insert... |
98898500dc08f076d43bbda2be38b82c102ae5d5 | mako101/training_dragon_python_basics | /Day1/Operators/operators.py | 3,205 | 4.34375 | 4 | # global variables
a = 50
b = 30
# create an arithmetic function
def arithmetic():
# display
print('This is an arithmetic operator')
# # to set the local variables as global
# # needs to be done BEFORE defining the variables
# global a,b
#local variables (overwrite global variables)
a =... |
433e0dce1666eba6689cc1bfd621f64e6e5e6ab5 | nfbarrett/CCIS-1505-02 | /Session08/Session8 InClass/inClass3.py | 739 | 3.78125 | 4 | def BV(l=1,w=1,h=1):
"""This functions receives 0,1,2 or 3 parameters and returns box volume"""
try:
intVol = int(l) * int(w) * int(h)
return intVol
except:
return 0
####Mainline####
strL = input("Enter box length: ")
strW = input("Enter box width: ")
strH = input("Enter box height: ... |
84a226d709697b2690f462a12480c867b495cc14 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_135/3442.py | 650 | 3.65625 | 4 | #!/usr/bin/env python
cases = input()
case=0
while case < cases :
case+=1;
row1_index = input()
row1 = []
row2 = []
count = 0;
number = -1;
for i in xrange(1,5):
if i == row1_index:
row1 = map(int,raw_input().split(" "))
else:
dev_null=raw_input()
row2_index = input()
for i in xrange(1,5):
if i == ... |
ba1b781fa1bb72f4a9a3e3aa23fe24c135b73079 | MAPLE-Robot-Subgoaling/IPT | /data/HW5/hw5_340.py | 591 | 4.125 | 4 | def main():
width = int(input("Please enter the width of the box: "))
height= int(input("Please enter the height of the box: "))
symbolOutline = input("Please enter the symbol for the box outline: ")
symbolFill = input("Please enter the symbol for the box fill: ")
if (height !=1 and width !=1):
... |
120d6744c80fc61c71b0a6c639e74fc49dc0fa4b | koehlma/rigorous | /tests/python/programs/original/lambda-py/multiple_inheritance/super-nested-self.py | 259 | 3.59375 | 4 | class A:
def f(self):
return 'A'
# super() in a nested function with "self" argument
class EE(A):
def f(self):
def nested(this):
return super().f() + 'E'
return nested(self)
___assertEqual(EE().f(), 'AE')
|
a86a7a47b6b97c7bf5bfac41caabe42ae91b0aad | watsonjia/voiceover | /visualize.py | 2,317 | 3.5625 | 4 | import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
def moving_average(data_src: np.ndarray, n: int) -> np.ndarray:
"""
Compute the moving average values for the 1D source array based on n values in window.
Shamelessly stolen from https://gordoncluster.wordpress.com/2014/01/29/pyth... |
cc0f925864f5415c275873301cc41ac54d2f08a9 | richardtully/wiki_movie_data | /get_movie_info_function.py | 4,263 | 3.71875 | 4 | '''
This script creates a class with functions that are used in the main script (movie_data).
'''
import requests
from bs4 import BeautifulSoup
import re
# Fixer.io identifies currencies by a three letter code - wikipedia uses the currencies symbol
symbol_to_currency_code = {
'£': 'GBP',
'CN¥': 'CNY',
... |
faf82cf553585f59c0e30cf0628cdbd875df5a8f | nadim1975/pycharm | /training/trainingPackage/string-methods2.py | 388 | 4.03125 | 4 | """
Examples to show available string methods in python
"""
# Replace Method
a = "1abc2abc3abc4abc"
print(a.replace('abc', 'ABC',2))
# Sub-Strings
# starting index is inclusive
# Ending index is exclusive
sub = a[0:6]
step = a[1:6:2]
print("****************")
print(sub)
print(step)
print (a[2:6])
print( a[:])
pri... |
65503e8e6b31ee311ab32de3064c0a4093699b17 | thebazman1998/School-Projects | /Grade 10/Bp_U2_Assignment6/Bp_U2_Assignment6_V1.py | 3,546 | 3.8125 | 4 | """
Name: Basil
Class: ICS201
Date: 04/0214
Assignment 5
"""
import pygame
import random
pygame.init()
def draw_background():
screen.fill((77, 255, 255))
pygame.draw.rect(screen, (0, 153, 0), ((0, 400), (900, 600)))
for a in range(0, random.randint(0, 2)):
draw_cloud(random.randint(0, 900), rando... |
ff55d6631b54451e4a9e7da1f6f7f07dd0550b95 | lixiang2017/leetcode | /explore/top-interview-questions-easy/Maximum_Depth_of_Binary_Tree.2.py | 3,987 | 3.8125 | 4 | '''
use built-in function pop(index) in list
# Output Limit Exceeded # need to comment out all print statements
You are here!
Your runtime beats 96.01 % of python submissions.
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.... |
90cbdf3e418a8a18219d24148c7b5e3fa52d977f | darkmatter18/Udacity-Computer-Vision-Nanodegree | /CVND_Exercises/3_5_State_and_Motions/3. color.py | 1,164 | 4.375 | 4 | import matplotlib.pyplot as plt
'''
The color class creates a color from 3 values, r, g, and b (red, green, and blue).
attributes:
r - a value between 0-255 for red
g - a value between 0-255 for green
b - a value between 0-255 for blue
'''
class Color(object):
# Initializes a color with rgb values
... |
7c6df927030200a41ad58a1f4f1744550e1b2b14 | ArnabBasak/PythonRepository | /TensorBoard/single_layer_perceptron.py | 1,746 | 3.859375 | 4 | import numpy as np
import matplotlib.pyplot as plt
#nneural network for solving xor problem
#the xor logic gate is
# 1 1 ---> 0
# 1 0 ---> 1
# 0 1 ---> 1
# 0 0 ---> 0
#Activation funtion
def sigmoid(x):
return 1/(1 + np.exp(-x))
#sigmoid derivative for backpropogation
def sigmoid_deriv(x):
return sigmoid(x... |
3ab603de2eaa78572e9a295b9ef43b36ead10289 | Dyr-El/advent_of_code_2017 | /magjac-python/2017/day/8/part2/p8b.py | 1,355 | 3.5 | 4 | #!/usr/bin/python
import sys
def main():
raw_lines = sys.stdin.readlines()
lines = [line.rstrip('\n') for line in raw_lines]
rows_words = []
for i, line in enumerate(lines):
words = line.split()
words = [word for word in words]
rows_words.append(words)
regs = {}
max... |
16e5b49447c14c4cd4395aa9347419762980c36e | ArthurBrito1/MY-SCRIPTS-PYTHON | /Desafios/desafio73.py | 561 | 3.890625 | 4 | times = ('corintias', 'palmeiras', 'santos', 'gremio', 'cruzeiro', 'flamengo', 'vasco','chapecoense', 'atletico', 'botafogo', 'atletico-pr', 'bahia', 'sao paulo', 'fluminense', 'sport', 'vitoria', 'curitiba', 'avai', 'ponte preta', 'atletico')
print('Lista de times do Brasileirão {}'.format(times))
print('Os 5 primei... |
cfd6d43c443567dba0cabd20e94674aee99717cc | justngobs/level0-coding-challenges | /task06.py | 180 | 3.875 | 4 | def maximum_number(*numbers):
largest = float('-inf')
for number in numbers:
if(number > largest):
largest = number
return largest |
569c4f9e865301804cad76a92102a6280bd7f567 | huangno27/learn | /早期/1803211.py | 628 | 3.75 | 4 | #coding utf-8
#for food in ("pate", "cheese", "crackers", "yogurt"):
#if food == "yogurt": #判断是否有yogurt 有就循环
#break
#else: #没有就跳出 调用else条件
#print("sorry no food")
#for food in ("pate", "cheese", "crackers"):
#if food == "yougurt": ... |
2c620de502da8b874145f74dc56adb8c68ff7d01 | coolsgupta/leetcode | /maximum_difference_between_node_and_ancestor.py | 715 | 3.6875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def maxAncestorDiff(self, root: TreeNode) -> int:
def max_tree_diff(node, min_anc, max_anc):
... |
058fdd64fa7702b162b517eb1003a78e5b2289f7 | athul-santhosh/Cracking-the-coding-interview-Python | /chapter 1 : Arrays/1.4 palindrome permutation.py | 995 | 4.03125 | 4 | # cracking the coding interview
# solution 1.4
#Palindrome Permutation
# approach we create a dict ,we iterate through dict, if we get count
# greater than 1 ,we return false else true
def palindrome_permutation(p):
p = p.lower().replace(" ","") # avoiding whitespace and case sensitivity
# print(p)
... |
56a98b5b24bc83e2290c4c919572f4328873d857 | trallard/AoC | /2017/day11.py | 877 | 3.625 | 4 | """
@trallard
Advent of Code 2017: Day 11
"""
import aoc
# Getting the input for the puzzle
helper = aoc.puzzle_data(year = 2017, day = 11)
my_input = helper.get_data()
print(my_input)
def distance(x, y, z):
return sum(map(abs, [x, y, z])) // 2
def main(file):
x, y, z = 0, 0, 0
d = 0
for line in fil... |
05b42521258fc6f7fbf15ede18b0156c2008271b | Tonovasquez/python3 | /Ejercicios 33/ejercicio25.py | 313 | 3.875 | 4 | #Elabore un programa que lea 2 numeros enteros positivos y que muestre la suma y la
#multiplicacion.
n1 = int(input("ingrese numero:."))
n2 = int(input("ingrese numero:."))
suma = n1 + n2
print("la suma es de:.{}".format(suma))
multiplicacion = n1 * n2
print("la multiplicacion es de:.{}".format(multiplicacion))
|
c86aa6c6efca5724c16a06400ca95f1320aa479f | Sree-vathsan/leetcode | /FindAllAnagramsInAString.py | 1,734 | 4.03125 | 4 | """
Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.
Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.
The order of output does not matter.
Example 1:
Input:
s: "cbaebabacd" p: "abc"
Output:
[0, 6]
E... |
e42282b1252a54658e69346a9a595dc311436981 | CameronKline/Assignment_05 | /CDInventory.py | 3,939 | 3.625 | 4 | #------------------------------------------#
# Title: CDInventory.py
# Desc: Starter Script for Assignment 05
# Change Log: (CKline, 8/11/20, 8:35PM Started Assignment)
# Change Log: (CKline, 8/12/20, 6:30AM Still Hacking)
# DBiesinger, 2030-Jan-01, Created File
#------------------------------------------#
# Pse... |
47f32c6f041bf383ad403b436574ae775d7addb6 | Donny97/CoffeeMachine | /coffee_machine/entities/beverage.py | 736 | 3.59375 | 4 | from typing import Dict
class Beverage:
"""
Class for Beverage entity.
Args:
name (str): Name of the beverage.
ingredient_quantity_map (Dict): Ingredient quantity maping.
Returns:
None
"""
_name = ""
_ingredient_quantity_map = {}
def __init__(self, name: str... |
5450e74144e826a164b14bc9232df26e5e7b9075 | daniel-reich/ubiquitous-fiesta | /WS6hR6b9EZzuDTD26_4.py | 214 | 3.53125 | 4 |
def no_duplicate_letters(phrase):
lst = phrase.lower().split()
for i in range(len(lst)):
lst[i] = list(lst[i])
for i in lst:
if len(set(i)) != len(i):
return False
return True
|
03cae3187f2f4ff9767a9b5d19533ffbb883e457 | 1010100101111/Python-Codes | /One-time Pad.py | 1,450 | 3.578125 | 4 | import random
key1={"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9,"j":10,"k":11,"l":12,"m":13,"n":14,"o":15,"p":16,"q":17,"r":18,"s":19,"t":20,"u":21,"v":22,"w":23,"x":24,"y":25,"z":26}
key2={1:"a",2:"b",3:"c",4:"d",5:"e",6:"f",7:"g",8:"h",9:"i",10:"j",11:"k",12:"l",13:"m",14:"n",15:"o",16:"p",17:"q",18:"r",19:... |
a661402d29d7513927d97c7fd46f8f31f94b4f4b | asxzhy/Leetcode | /leetcode/question_824/solution_2.py | 721 | 3.6875 | 4 | """
This is same as the last solution but I tried to use set to see if the program can be any fast. It turns out to be the same
"""
class Solution:
def toGoatLatin(self, S: str) -> str:
S = S.split() # seperate the words
vowels = {"a", "e", "i", "o", "u", "A", "E", "I", "O", "U"}
... |
6427df83fc30092b27d87bb7fad21eac3415221a | programhung/learn-python | /PythonCode/Maths/sin2+cos2.py | 275 | 3.859375 | 4 | import math
def sin(x):
return math.sin(math.radians(x))
print("Enter the number for calcul the sin")
degr=float(input())
print(str(sin(degr)**2))
a=sin(degr)**2
print(str(a))
def cos(x):
return math.cos(math.radians(x))
b=cos(degr)**2
print("So, sin**2+cos**2="+str(a+b))
|
e2a60df73639a10e6850f013e9efe114841f35c3 | mysqlbin/python_note | /2020-03-24-Python-ZST-base/2020-09-03-内建函数/2020-09-03.py | 822 | 4.03125 | 4 | #!/usr/bin/ptyhon
#coding=gbk
# str
s = 'RUNOOB'
print(s)
dict = {'runoob': 'runoob.com', 'google': 'google.com'}
print(type(dict))
print(type(str(dict)))
print(str(dict))
# list
print(list('abc'))
print(list([1, 2, 3]))
print(list({1: 2, 3: 4}))
# tuple
print(tuple('abc'))
print(tuple([1, 2, 3]))
print(tupl... |
f200aea0891a1cf2e9abe69962961a00063dddae | PetejStone/Sorting | /src/recursive_sorting/sorttest.py | 2,062 | 4.0625 | 4 |
if len(arr) > 1: #if array has more than one element
mid = len(arr)//2 #Find the middle point of the array
## understanding slicing with : in arrays
# a[start:stop] items start through stop-1
# a[start:] items start through the rest of the array
# a[:stop] ite... |
b5228afb25ef71117c5847abf124d173b7902cd0 | Kawser-nerd/CLCDSA | /Source Codes/AtCoder/abc104/B/4928281.py | 182 | 3.5625 | 4 | S = input()
if S[0] == 'A' and S[2:-1].count('C') == 1:
c = S.index('C')
if S[1:c].islower() and S[c+1:].islower():
print('AC')
exit()
print('WA') |
e4f08c7f931abc6014e22f537e143c0635b71c96 | luzcn/ml-training | /demo/sciKit_learn_demo.py | 1,327 | 4.40625 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import datasets
def exercise():
"""
We're going to predict the amount of a sale, so we only want rows that have a Won value for the Opportunity Result
and then we want to drop that column from the filtered data.
1. We ... |
b6ef02f3717106721a3ff72d0f641586c431fe46 | wu0727/TQC-python3 | /test7/710.py | 218 | 3.625 | 4 | d = {}
print("Key: ", end = "")
K = input()
while K != "end":
print("Value: ", end = "")
c = input()
d[K] = c
print("Key: ", end = "")
K = input()
print("Search key: ", end = "")
print(input() in d) |
a92afe7d65e22c34d78824c614f4d1769dd46025 | TheusZer0/ctf-archives | /darkCON/2021/crypto/TonyAndJames/src.py | 623 | 3.546875 | 4 | #!/usr/bin/env python3
import random
def get_seed(l):
seed = 0
rand = random.getrandbits(l)
raw = list()
while rand > 0:
rand = rand >> 1
seed += rand
raw.append(rand)
if len(raw) == l:
return raw, seed
else:
return get_seed(l)
def encrypt(m):
l = len(m)
raw, seed = get_seed(l)
random.seed(see... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.