blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
e61200d2f2eae37f7c8d2f0c115950216b2c9902 | phlalx/algorithms | /leetcode/40.combination-sum-ii.py | 1,712 | 3.5625 | 4 | #
# @lc app=leetcode id=40 lang=python3
#
# [40] Combination Sum II
#
# https://leetcode.com/problems/combination-sum-ii/description/
#
# algorithms
# Medium (43.31%)
# Likes: 1431
# Dislikes: 56
# Total Accepted: 296.5K
# Total Submissions: 642.8K
# Testcase Example: '[10,1,2,7,6,1,5]\n8'
#
# Given a collection... |
931d7cb98196fdd2e04d5b4353b4e758fc4c2d9c | greatabel/PythonRepository | /03Programming in Python 3/1&2Basic_And_DataType/awfulpoetry_strength_ch1answer.py | 951 | 3.671875 | 4 | articles = ['the','a','another','other']
subjects = ['cat','dog','man','woman','boy']
verbs = ['sang','ran','jumped','drank']
adverbials =['loudly','quietly','well','badly']
import random
import sys
def get_input(msg):
while True:
try:
line = input(msg)
return int(line)
except:
# print("unexpected er... |
928129ae586811a75b95b7067888aeca52d7daae | jdanray/leetcode | /verticalTraversal.py | 501 | 3.78125 | 4 | # https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/
class Solution(object):
def verticalTraversal(self, root):
if not root:
return []
vertical = {}
stack = [[root, 0, 0]]
while stack:
node, x, y = stack.pop()
if not node:
continue
vertical[x] = vertical.get(x, []) + [... |
184c4fb17400281ad68d7b1d5257dc850e1a1f49 | yinzhiyizhi/Python_Practise | /函数式编程/高阶函数/filter.py | 3,885 | 4.0625 | 4 | # Python内建的filter()函数用于过滤序列。
# 和map()类似,filter()也接收一个函数和一个序列。
# 和map()不同的是,filter()把传入的函数依次作用于每个元素,
# 然后根据返回值是True还是False决定保留还是丢弃该元素。
# 例如,在一个list中,删掉偶数,只保留奇数,可以这么写:
def is_odd(n):
return n%2==1
list(filter(is_odd,[1,2,4,5,6,9,10,15]))
# [1,5,9,15]
# 把一个序列中的空字符串删掉,可以这么写:
def not_empty(s):
return s and s.str... |
91e52efff48ded70219a0c2a5f028d201c4ee5f2 | ajpiter/PythonProTips | /DeepLearning/Archive/SlopeCalculation.py | 1,257 | 4.125 | 4 | #Slope Calculation Example, with one input and no activation function.
Node1 = Input = 3
Weight = 2
Node2 = Output = 6
PredictedValue = Node2
ActualTargetValue = 10
LearningRate = 0.01
SlopePrediction = Slope of Mean-Squared loss function precdiction
SlopePrediction = 2 * (Predicted Value - Actual Value) = 2*Er... |
07317312d2ffd9b82a44e473c21aab5bf0940f43 | Jehuty-ML/- | /data structure/100!single link list.py | 3,646 | 3.75 | 4 | '''
模仿c语言的内存精度限制,用链表实现求100阶乘的结果
'''
class Node(object):
"""单链表的结点"""
def __init__(self, item):
# item存放数据元素
self.item = item
# next是下一个节点的标识
self.next = None
class SingleLinkList(object):
"""单链表"""
def __init__(self, item):
self._head = Node(item)
def i... |
36205f8f4f724fe22e32dc4ca4a9603661c8cde1 | dprestsde/project-euler | /1.py | 351 | 4.1875 | 4 | # If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
# The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
result = 0
i = 1
while 3*i<=1000 or 5*i<=1000:
if 3*i<=1000:
result += (3*i)
if 5*i<=1000:
result +=... |
6be1eb13f55085ffc05243d94ef2e67dc84722a8 | WaleedRanaC/Prog-Fund-1 | /Lab 6/CheckPoint3b.py | 333 | 4.15625 | 4 | #write a short program using while loop
#that displays each line of the file
def main():
#open file
infile=open('data.txt','r')
#assign and define line
line=infile.readline()
#while loop
while line !='':
printn(line)
line=infile.readline()
infile.close()
m... |
dabab3d13b5912664682629aed907c8ec70237bc | szabgab/slides | /python/examples/dictionary/scores.py | 421 | 3.859375 | 4 | scores = {
"Jane" : 30,
"Joe" : 20,
"George" : 30,
"Hellena" : 90,
}
for name in scores.keys():
print(f"{name:8} {scores[name]}")
print('')
for name in sorted(scores.keys()):
print(f"{name:8} {scores[name]}")
print('')
for val in sorted(scores.values()):
print(f"{val:8}")
print('... |
5b6e9941152b0950fb29d7422bb72c30e31f2aae | dodekaedro6p14/poesia-python | /thursday.py | 574 | 3.609375 | 4 | from turtle import Screen, Pen
import colorsys
screen = Screen()
screen.title("thursday")
screen.bgcolor("black")
t = Pen()
#pen.speed('fastest')
poesia = 0.0 # rando de colores is 0.0 to 1.0
for i in range(200):
color = colorsys.hsv_to_rgb(poesia, 1, 1) # pen wants RGB
t.pe... |
4e7e051841fb766dffd059df99a08d0565540263 | brianfurrer/CSE015 | /Lab_08/Lab_8.py | 1,142 | 3.609375 | 4 | import random
import time
def gen_random_list(n):
assert(n>0)
li = [random.randint(0,10*n) for i in range(n)]
return li
if __name__ == '__main__':
l = gen_random_list(10)
l.sort()
print(l)
def linear_search(s,k):
i = 0
n = len(s) - 1
while(i <= n and k != s[i]):
i += 1
... |
63151ec788741a18645abc0be9cfa55492e22a9a | william-yz/show-me-the-code | /0000.py | 521 | 3.625 | 4 | from PIL import Image, ImageDraw, ImageFont
# get an image
base = Image.open('0000.png').convert('RGBA')
# make a blank image for the text, initialized to transparent text color
txt = Image.new('RGBA', base.size, (255,255,255,0))
# get a font
# fnt = ImageFont.truetype('Pillow/Tests/fonts/FreeMono.ttf', 40)
# get a d... |
d3c0934742e10645002ba74452aafd9d6eba90c9 | sunshinewxz/leetcode | /78-subsets.py | 775 | 3.59375 | 4 | class Solution(object):
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
# result = [[]]
# for n in nums:
# for r in result[:]:
# temp = r[:]
# temp.append(n)
# result.append(temp)
# print(... |
73efcca981af6efe06eee82b13a4334b57c5e41b | Myduzo/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/models/square.py | 1,787 | 3.75 | 4 | #!/usr/bin/python3
"""The Square"""
from models.rectangle import Rectangle
class Square(Rectangle):
"""class Square that inherits from Rectangle with\
private instance attributes"""
pass
def __init__(self, size, x=0, y=0, id=None):
"""Class contructor"""
super().__init__(size, si... |
55238e02e9c30d3c23dbdf7d8c7b2d32c31fc1b7 | muhfikriw/Praktikum8 | /langkah kerja.py | 1,390 | 3.71875 | 4 | a = [1, 5, 6, 3, 6, 9, 11, 20, 12]
b = [7, 4, 5, 6, 7, 1, 12, 5, 9]
a.insert(3,10)
print("a = ", end="")
print(a)
b.insert(2,15)
print("b = ", end="")
print(b)
#penambahan data terakhir
print("_"*35)
x = len(a)
a.insert(x,4)
print("a = ", end="")
print(a)
l = len(b)
b.insert(l,8)
print("b = ", end="... |
674c9fa713737486e2835b892e02eda8e90b1360 | elefteroff/chaining_methods_v2 | /chaining_methods.py | 1,190 | 3.703125 | 4 | class User:
def __init__(self, name, email):
self.name = name
self.email = email
self.account_balance = 0
def make_deposit(self, amount):
self.account_balance += amount
return self
def make_withdrawal(self, amount):
self.account_balance -= amount
re... |
103496b50aae26cc6f8313771d0fbaa6bd6ff827 | steveedegbo/learning_python | /Functions/functions.py | 4,512 | 4.125 | 4 | # # # # # #TAKES NAME & GENDER INPUT AND GREETS ACCORDINGLY
# # # # # def greet(name, gender, age):
# # # # # if gender == "male" and age >= 18:
# # # # # print(f'Hello Mr {name}..!')
# # # # # elif gender == "male" and age < 18:
# # # # # print(f'Hello Mst {name}..!')
# # # # # el... |
3808f700176d80b3051af89fe24bcc584c0ce791 | iambaim/pyEcholab | /echolab2/plotting/qt/QImageViewer/QIVHudText.py | 6,629 | 3.5 | 4 | from PyQt5.QtCore import *
from PyQt5.QtGui import *
class QIVHudText(QObject):
"""
Add text to the scene given the text and position. The function returns
the reference to the QGraphicsItem.
text (string) - The text to add to the scene.
position (QPointF) - The position of the text ancho... |
427a00e3ab81f482e87b8f9ade7e62e79922ecb7 | hubduing/my_project | /Curse_2/module2/2.2/date.py | 645 | 3.84375 | 4 | import datetime
def date_vanga():
#получаем дату и кол-во дней
(y, m, d) = [int(n) for n in input().split()]
day_time = int(input())
date = datetime.date(y, m, d) # полученную дату переводим в тип дата
delta = datetime.timedelta(days=day_time) # находим промежуток времени
delta = date + delta
... |
89f6ba93f1ccb9597cbcffaf3dfd7f2e4e8e3696 | timyu30/legendary-giggle | /Studies/Python_RuneStone/Chapter_1/TimeComparison.py | 1,263 | 3.65625 | 4 | #Comparison of times between dictionary and list access
#%%
import timeit
def find_number_in_list(lst, num):
if num in lst:
return True
else:
return False
short_list = list(range(100))
long_list = list(range(10000000))
#(%) is a Jupyter Magic
%timeit find_number_in_list(short_li... |
1f964b0d6faa68feb20eed354c96fe2188d6b4e2 | 3mjay/PY4E | /py4e/every_chapter_exercies/chapter10.py | 1,569 | 4.21875 | 4 | # Exercise 1: Revise a previous program as follows: Read and parse the “From” lines and pull out the addresses from the line. Count the number of messages from each person using a dictionary.
#
# After all the data has been read, print the person with the most commits by creating a list of (count, email) tuples from th... |
37cde5339b4db31fb2159ba0de127648f4b3b01f | Haitham-Darwish/Cryptography | /Cipher by many type/CipherDecryption.py | 6,717 | 4.03125 | 4 | #!/usr/bin/env python3
'''
Decrypt any English word encrypted by Reverse,
Caesar or Transposition cipher
The program idea taken from (python_code_uncoder)
and edited by Haitham Essam
'''
import sys
import os
import time
from detectEnglish import isEnglish
from CaesarCipher import caesar
# we will... |
206c069eb650487550ce85d175fc11ec66324464 | mreboland/pythonClasses | /car.py | 10,680 | 4.84375 | 5 | # Working with classes and instances
# Once a Class is written, most of the time spent is with instances created
# with that Class. One of the first tasks we'll want to do is modify the
# attributes associated with a particular instance.
# We can modify the attributes of an instance directly or write methods that
# up... |
2d949595e1b4ce666835fe478279dbc6aaeaaf90 | wuyanzhang/Machine-learning | /Logistic/logistic_regression.py | 2,202 | 3.828125 | 4 | import numpy as np
import matplotlib.pyplot as plt
# 函数说明:加载数据集
def loadDataSet():
dataMat = []
labelMat = []
fr = open('testSet.txt')
for line in fr.readlines():
lineArr = line.strip().split()
dataMat.append([1.0, float(lineArr[0]), float(lineArr[1])])
labelMat.append(int(lineA... |
86e953f3b1490caff4ef5e46c892b1eeade465a0 | ibm-5150/Python-HW | /HW-3/task_4.py | 208 | 3.796875 | 4 | string = str(input())
if string.count('a') < 1:
print("False")
elif string.count('a') == 1:
print(string.find('a'))
elif string.count('a') >= 2:
print(string.find('a'), string.rfind('a'))
|
0b2a16e898d30a28d9d0c4127d6c2e4248f9f296 | rbshadow/Python_URI | /Strings/URI_1168.py | 1,009 | 3.546875 | 4 | def math():
loop = int(input())
for i in range(loop):
i_put = input()
count = 0
for j in range(len(i_put)):
if int(i_put[j]) == 1:
count += int(i_put[j]) + 1
elif int(i_put[j]) == 2:
count += int(i_put[j]) + 3
elif int... |
0031990e161576f2e9c0ed178cb40f0dd135dd55 | vgomesn/socket-message-listener | /socket-client.py | 1,122 | 3.65625 | 4 | #
# Veronica Gomes
# File: socket-server.py (Python 3)
#
# Used reference code from these sources:
# Jesse Smith, Python Guide for the Total Beginner LiveLessons
# http://www.informit.com/articles/article.aspx?p=2234249
#
# Description:
# Socket client is a client app that will connect to a socket-server running on lo... |
6b534ff45639843bdeeca9005d40045fac916400 | smspillaz/artificial-intelligence | /artificialintelligence/minimax.py | 8,993 | 4.125 | 4 | # /artificialintelligence/minimax.py
#
# Play a game using the minimax algorithm.
#
# See LICENCE.md for Copyright information
"""Play a game using the minimax algorithm."""
"""
Mancala game v1.0
Lyndon While, 3 April 2014
The program prompts the user for the game size X, then it plays a
game of Mancala between two r... |
cfed77342bcdf960e82f5165771e2b00f7af2c2e | toufeeqahamedns/DataStructures | /Arrays/4 - LeftRotation.py | 728 | 4.1875 | 4 | """
A left rotation operation on an array of size shifts each of
the array's elements 1 unit to the left. For example, if 2 left
rotations are performed on array [1, 2, 3, 4, 5], then the array would become [3, 4, 5, 1, 2].
Given an array of n integers and a number, d, perform d left
rotations on the array. ... |
0e4fd6f7dbff0b15ef6ae5a14cbb90b4b9483d08 | kirubah18/guvi | /codekata/findgcd.py | 136 | 3.609375 | 4 | def gcd(nu1,nu2):
if(nu2==0):
return nu1
else:
return gcd(nu2,nu1%nu2)
nu1,nu2=map(int,input().split())
print(gcd(nu1,nu2))
|
8feaf768ab463736b882b870d33e94e43c7490ed | LBJ-Max/basepython | /多线程/demo1.py | 423 | 3.75 | 4 | # 演示多线程
import threading
import time
def sayEat():
print("吃饭啦")
time.sleep(1)
def main():
t1 = threading.Thread(sayEat())
t2 = threading.Thread(sayEat())
# 查看线程的数量
t1.start()
t2.start()
while True:
print(threading.enumerate())
if len(threading.enumerate()) <=1:
... |
2ee07e879ce14c14e4883b8ed06a881694971cb1 | gilberto-009199/MyPython | /outros/2020-04-25-2.py | 142 | 3.8125 | 4 |
maior = 0;
while True:
val0 = int(input());
if val0 < 0 :
break;
maior = maior if maior > val0 else val0;
print(maior); |
1c2f3e54868f0f6920d6bfe82342381ea692b297 | MahadiRahman262523/Python_Code_Part-2 | /list comprehension 2.py | 167 | 3.75 | 4 | #list comprehension for filter function
num = [1,2,3,4,5]
#result = list(filter(lambda x : x%2 == 0,num))
result = [x for x in num if x%2 == 0]
print(result) |
9986a6da2816628456e50fd00c7add48dbe737ad | SamEpp/TextMining | /texttmining.py | 4,254 | 3.625 | 4 | import requests
import nltk
import pickle
from bs4 import BeautifulSoup
#Mary_Wade_text = requests.get('http://www.gutenberg.org/cache/epub/43585/pg43585.txt').text
#print(Mildred_Wirt_text)
# Save data to a file (will be part of your data fetching script)
# f = open('Mary_Wade_text.pickle', 'wb')
# pickle.dump(Mary_... |
9d8ca098e04a4613170ce08a465de31246a103b6 | vsamanvita/APS-2020 | /Graph_cycle_detection.py | 1,019 | 3.828125 | 4 | # Python program to detect cycle in a graph
from collections import defaultdict
class Graph():
def __init__(self,vertices):
self.graph=defaultdict(list)
self.V=vertices
def addEdge(self,u,v):
self.graph[u].append(v)
def isCyclicUtil(self, v, visited, recStack):
visited[v]=True
r... |
172ee301a4113f9c58f96c9cb30581da2d6a6705 | WOWSCpp/Illumio-Coding-Assignment | /illumio.py | 3,895 | 3.609375 | 4 |
class PortIpRange:
'''
check if port or ip_address is valid
'''
def __init__(self, port_lo, port_hi, ip_lo, ip_hi):
self.port_lo = port_lo
self.port_hi = port_hi
self.ip_lo = ([int(i) for i in ip_lo.split('.')])
self.ip_hi = ([int(i) for i in ip_hi.split('.')]... |
26dc64a9744ec2b575d184dfee409a9985b0c181 | jiriVFX/data_structures_and_algorithms | /interview_problems/monarchy.py | 2,132 | 3.96875 | 4 | # Interface design - design a monarchy class and methods
# time complexity - O(n) - number of members of family
# space complexity - O(n) - number of members of family
class Member:
def __init__(self, name, sex):
self.name = name
self.alive = True
self.sex = sex
self.children = []
... |
3775d73e8a866d70f9365d1d1a8556aaa3873339 | wiecodepython/Exercicios | /Exercicio 2/maarinaabatista/exercicio_semana2.py | 3,562 | 3.59375 | 4 | Python 3.7.1 (v3.7.1:260ec2c36a, Oct 20 2018, 14:57:15) [MSC v.1915 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> #EXERCICIO_SEMANA_2
#QUESTÃO 01
print ("Hello, World!")
Hello, World!
>>> #soma
>>> 3+5
8
>>> 9+12
21
>>> 7+32
39
>>> #decimais
>>> 4.5 + 7.3
11.8... |
23836bb7a43deeed06a57cf4af65fea2bc3f95e9 | Cpharles/Python | /CursoEmVideo/Aula_09/ex026 - Primeira e ultima ocorrencia de uma string.py | 594 | 4.03125 | 4 | """Exercício Python 026:
Faça um programa que leia uma frase pelo teclado e mostre quantas vezes aparece a letra "A",
em que posição ela aparece a primeira vez e em que posição ela aparece a última vez."""
frase = str(input('Digite uma frase:_ ')).strip().lower()
import unidecode # esta lib trata string com acentuação... |
162274bec8bd72fead3878c8f6cef83629355cb5 | PPL-IIITA/ppl-assignment-shubham-padia | /q2/boy.py | 642 | 3.625 | 4 | class Boy:
""" Class for boy"""
def __init__(self, name, attractiveness, min_attraction, intelligence, budget, category, single=1, happiness=0):
self.name = name
self.attractiveness = int(attractiveness)
self.intelligence = int(intelligence)
self.budget = int(budget)
sel... |
5467abc676dc3f44779c4324321339e5f36f4d01 | mimi1987/Python_Script_Mingle_Mangle | /n_factorial_recursion.py | 135 | 3.640625 | 4 | def recursiveCall(n):
# Exit condition
if n == 1:
return 1
# Recursive call of recursiveCall
return n * recursiveCall(n-1)
|
3f0269823041725d11d9b794c67d126c11994c25 | Leadace123/Python-LSystem-Trees | /Tree-Generator/main.py | 2,932 | 3.640625 | 4 | from tkinter import *
import turtle
import random
# Creates Root Window
root = Tk()
root.title('Tree Generator')
root.state('zoomed')
root.config(bg='grey')
w = root.winfo_screenwidth()
h = root.winfo_screenheight()
is_drawing = 0
# Generates Tree
def generate_tree():
global is_drawing
if is_drawing == 0:
... |
e8ac132d618b3d40ae290d0abdbd738dd090a636 | JuanTorchia/pythonPensamientoComputacional | /rangos.py | 296 | 4.0625 | 4 |
my_range = range(1, 5)
print(type(my_range))
my_range = range(0, 7, 2)
my_other_range = range(0, 8, 2)
print(my_range == my_other_range)
for i in my_range:
print(i)
for i in my_other_range:
print(i)
print(my_range is my_other_range)
for i in range(0, 101, 2):
print(i)
|
2455bfc9cd54424860a1c3ec2455e20d2c48c129 | Joie-Kim/python_ex | /final_exercise/ex9.py | 581 | 3.578125 | 4 | # 9. 평균값 구하기
# sample.txt 파일의 숫자 값을 모두 읽어 총합과 평균 값을 구한 후, 평균 값을 result.txt 파일에 쓰도록 하자.
# (1) 파일 읽기
f = open("./final_exercise/sample.txt", 'r')
list = f.readlines()
f.close()
# (2) 총합과 평균 값 구하기
total = 0
for value in list:
score = int(value)
total += score
avg = total / len(list)
# (3) 평균 값 파일에 쓰기
f = open("... |
fe4823fc78f1d7aba084f79ccbc1dde4baccd40a | Siyuan-Liu-233/Python-exercises | /python小练习/017田忌赛马.py | 924 | 3.90625 | 4 | # 这题也是华为面试时候的机试题:
# “ 广义田忌赛马:每匹马都有一个能力指数,齐威王先选马(按能力从大到小排列),田忌后选,马的能力大的一方获胜,若马的能力相同,也是齐威王胜(东道主优势)。”
# 例如:
# 齐威王的马的列表 a = [15,11,9,8,6,5,1]
# 田忌的马的候选表 b = [10,8,7,6,5,3,2]
# 如果你是田忌,如何在劣势很明显的情况下,扭转战局呢?
# 请用python写出解法,输出田忌的对阵列表 c及最终胜败的结果
# 评分
a = [8,15,1,11,6,5,9]
b = [2,8,6,7,5,3,10]
import numpy as np
a,b=np.array(n... |
5d6afb6166a9ca9b5dd697099b9b571c243674db | BabyNaNaWang/41daysToLearnPython3 | /零基础学习python3.day7.容器集合.py | 2,305 | 3.71875 | 4 | # date:2019-4-17
# author:Ivo Wang
# describition:容器集合、三引号字符串、索引、字符串是不可变的、字符串拼接
# editor for code: vs code
# 容器集合
# 定义:集合(set)是一个无序的不重复元素序列。
# 集合中的元素必须是不可变类型的
# 创建集合的方法有两种:
# 第一种:通过set(value)创建空集合
my_set = set('hello')
print(my_set)
# 第二种:通过{value,value1}方式创建
my_set = {1,2,3,3}
print(my_set)
# 定义不可变集合: [变量名] = fr... |
04563d005eb2795bd4e09dd83c4731454d948ea4 | panxiao6494/-study | /python-study/while.py | 267 | 4 | 4 | number=7
guess=-1
print('猜字谜游戏')
while guess !=number:
guess=int(input('请输入你猜的数字:'))
if guess==number:
print('恭喜你,猜对了')
elif guess<number:
print('猜的数字小了')
elif guess>number:
print('猜的数字大了--') |
1faeb4b29ce48ce16e2599570a3f3bf395354b8b | oscarepv/Clase-9 | /ejercicio4.1.py | 170 | 3.59375 | 4 | import turtle
def dibujar(x):
t = turtle.Pen()
angulo=360/x
for x in range (1,(x+1)):
t.forward(100)
t.left(angulo)
dibujar(6)
turtle.getscreen()._root.mainloop() |
ea7147ca5b36c804ddcc5c4edd6a925a57436fe1 | nadishs/easycuberoot | /1.croot-bisection.py | 393 | 4.1875 | 4 | #Nadish Shajahan
#Program to find the cube root of a number using bisection method.
#https://github.com/nadishs/
n = input()
high = n
low = 0
eps = 0.0000001
count = 0 # no of steps
mid = (low + high) / 2.0
while abs((mid**3)-n) > eps :
if mid**3 < n:
low = mid
else:
high = mid
mid = (low + high)/2.0
count =... |
0ef3cb00a17c65199d6416f1b8e7a74503464854 | chiachichuang/Capstone_ML_DL | /Capstone_Hw1_IO_reviews/PyAdv_02_Args.py | 433 | 3.953125 | 4 | ####################
# PyAdv_S02_Args.py
####################
#
# Program to process script arguments
#
import sys
def show_numbers():
print("From show_numbers: 12345678910 ...")
# this is the main function
def main():
print("Number of arguments ...", len(sys.argv))
for a, b in enumerate(sys.argv):
... |
38f81a2c500ab92fc80585ac3b79de2407cb207c | odonnell31/python_data_science_basics | /algorithms/strings/unique_characters.py | 837 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Oct 25 12:16:01 2019
@author: Michael ODonnell
"""
# Question
# write an algorithm to determine if a string has all unique characters
def unique_chars(word):
# plan of attack: append each character to a list, if it is not in list already
# create empty list to ... |
fc35dc85829511903157c837b3b653a21f6e592c | shalgrim/advent_of_code_2020 | /python/day02_1.py | 651 | 3.796875 | 4 | import re
from file_ops import readlines
LO = 'lo'
HI = 'hi'
LETTER = 'letter'
PWD = 'pwd'
PATTERN = re.compile(
rf'(?P<{LO}>\d+)-(?P<{HI}>\d+)\s+(?P<{LETTER}>[a-z]):\s+(?P<{PWD}>\S+)'
)
def is_valid(groupdict):
lo = int(groupdict[LO])
hi = int(groupdict[HI])
letter = groupdict[LETTER]
password ... |
0a7a8cac1ef4faa1cd8321d5119f16d800e8a7bc | harut0601/intro-to-Python | /week5/Practical/decorators1.py | 397 | 3.578125 | 4 | def decorator2(func):
def wrapper(*args, **kwargs):
b = func(*args, **kwargs)
c = "!!! Welcome to the party."
print(b + c)
return wrapper
def decorator1(func):
def wrapper(*args, **kwargs):
a = func(*args, **kwargs)
return a.capitalize()
return wrapper
@decora... |
09ebd1ccdcfc56fff99fe41ac94d57180274d26f | NetworkRanger/python-core | /chapter09/friendsB.py | 1,481 | 3.625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: NetworkRanger
# Date: 2019/8/11 12:28 PM
import cgi
header = 'Content-Type: text/html\n\n'
formhtml = '''
<html>
<head>
<title>Friends CGI Demo (static screen)</title>
</head>
<body>
<h3>Friends list for: <i>NEW USER</i></h3>
<form action="/cgi-bin/friendsA... |
295899eb9199e002ebec71d9b201717bf101d37a | undersfx/python-para-zumbis | /exerc_area.py | 603 | 3.953125 | 4 | '''
Ler tamanho de área de calcular minimo interiro de latas para pinta-la;
Printar o valor total do custo considerando que cada lata;
Tem 18 litros, custa 80 reais e cada litro de tinta pinta 3 metros quadrados.
'''
metros = int(input("M² de área a ser pintada: "))
if metros % 54 != 0:
latas... |
c6b92a1814677ec16af33d832dcc4674b727a4ee | HTReddy/everyDayUseCodes | /excelToJson.py | 764 | 3.5625 | 4 | import pandas
import pprint
import json
jsonDataFrame = {}
def convertExcelToJson(excelFileName=None, jsonFileName=None):
dataFrame = pandas.read_excel(excelFileName)
pprint.pprint(dataFrame.columns) # All the headings of your excel file, these can become the source for JSON Keys
# Iterate throu... |
0b4f27c020a55cf98475c26330e7575291ae6f8a | FjeldMats/Project-Euler | /Python/problem68.py | 3,224 | 3.515625 | 4 | import itertools
class n_gon:
def __init__(self, n):
num_lines = n
self.lines = []
for line in range(num_lines):
self.lines.append([])
for _ in range(3):
self.lines[line].append(0)
def set_with(self, outer, inner):
# put inner n... |
6c100b2ad668b5537d6783054b34ae03c9cc4e00 | pravindra01/DS_And_AlgorithmsPractice | /BInTreeDFS.py | 1,513 | 4.25 | 4 | # Given a binary tree, return the tilt of the whole tree.
# The tilt of a tree node is defined as the absolute difference between the sum of all left subtree node values and the sum of all
# right subtree node values. Null node has tilt 0.
# The tilt of the whole tree is defined as the sum of all nodes' tilt.
# Exa... |
358791111e25574b9e33ffba9a2eed43f04324c2 | vit-shreyansh-kumar/code-droplets | /src/AbstractProperty.py | 397 | 3.734375 | 4 | import abc
class Base(metaclass=abc.ABCMeta):
@property
@abc.abstractmethod
def value(self):
return "To be overridden."
class Implementation(Base):
@property
def value(self):
return "Concrete Implementation."
if __name__ == "__main__":
b = Base()
print("Base.value:", ... |
c65a1d7183ba13846684af1a80a5c144ba7346ab | kaustubhmali/Python_practice | /Python_basics(Part-2)/reduce.py | 501 | 3.953125 | 4 | import functools
import operator
import itertools
lis = [1, 3, 5, 6, 2, ]
# Sum of all the elements in the list
sum = (functools.reduce(lambda a, b: a + b, lis))
print(sum)
# largest element in the list
largest = (functools.reduce(lambda a, b: a if a > b else b, lis))
print(largest)
# Using operator
sum_ = (functoo... |
87889c37912fe7f9666400c7c70e84cf412ea0c8 | wangxiaolinlin/python | /koujue.py | 145 | 3.546875 | 4 | count = 0
while count <= 9:
row = 1
while row <= count:
print("%d*%d=%d"%(count,row,count*row),end="/t")
row+=1
print("")
count+=1
|
ff9626094d23fa6604d9feddb0e9094312f7db6e | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/bob/1f3b4596b75341c781b0f2a34aca84fa.py | 564 | 4.03125 | 4 | #
# Skeleton file for the Python "Bob" exercise.
#
def hey(what):
# Test if string is empty, has space or tab.
if not what or what.isspace():
return 'Fine. Be that way!'
# Test if string is not empty, has ? mark at the end not uppercase.
elif not what or what[-1] == '?' and not what.isupper():... |
e78ece88c96b93a5a754f6342c2bd704e9bf330f | here0009/LeetCode | /Python/1681_MinimumIncompatibility.py | 4,941 | 4.0625 | 4 | """
You are given an integer array nums and an integer k. You are asked to distribute this array into k subsets of equal size such that there are no two equal elements in the same subset.
A subset's incompatibility is the difference between the maximum and minimum elements in that array.
Return the minimum possibl... |
374023baa43370bd924fe383b81b4f323d27775c | linminhtoo/algorithms | /greedy/easy/lemonadeChange.py | 801 | 3.640625 | 4 | # https://leetcode.com/problems/lemonade-change/submissions/
from collections import defaultdict
from typing import List
class Solution:
def lemonadeChange(self, bills: List[int]) -> bool:
cash = defaultdict(int)
for b in bills:
if b == 10:
if cash[5] == 0:
... |
58f2e33e896485a0efdd0676daf3a2b31a9936d7 | dylanbaghel/python-complete-course | /section_15_lambdas_built_in_functions/11_zip.py | 721 | 4.75 | 5 | # zip() Function
"""
zip():
--> The purpose of zip() is to map the similar index of multiple containers so that they can be used just using as single entity.
"""
"""
zipping
"""
names = ['Abhishek', 'Jonas', 'Kora']
marks = [90, 55, 78]
first_zip = zip(names, marks)
print(list(first_zip))
# initializing lists
n... |
5ebcd23fc9a737aed11a2a94cb601f245ef76915 | ipgtzuo/Learn_Python | /demo/minSquenceDiff.py | 544 | 3.5625 | 4 | def minSquenceDiff(list1, list2):
c = list1+list2
c.sort()
n = len(c)
a, b = [], []
for i in range(n):
if sum(a) >= sum(b):
b.append(c[-1])
else:
a.append(c[-1])
c.pop()
if len(a) == n/2:
b += c
break
... |
d15975c7e9d522b1c61dfdfbf7b784841ebe37f7 | beautytasara27/beauty | /driving simulation.py | 1,158 | 3.96875 | 4 | import matplotlib.pylot as plt
Max_Distance = int(input())
Initial_velocity =int(input())
Time_spent =int(input())
Acc =int(input())
Speed_limit=60
Distance_array=[]
Velocity_array=[]
Time_array[]
for i in range(0,Max_distance/10):
Distance_array[i]=i*10
for i in range(0,len(Distance_array)):... |
3a6c0b29649f6306fe62be6950f0694f0b91bc2e | Igorprof/python_git | /HW_3/6.py | 325 | 4.03125 | 4 | def int_func(word):
# Без использовании функции capitalize
letters = list(word)
letters[0] = letters[0].upper()
cap_word = ''.join(letters)
return cap_word
s = input('Введите строку: ')
new_s = ''
for word in s.split():
new_s += int_func(word) + ' '
print(new_s) |
4465ef7dbeac475e023cbad32537d3683e496ebd | magik2art/DZ_1_python_Mamaev_Pavel | /parcent.py | 528 | 3.8125 | 4 | user_text = int(input("Введите число от 0 до 20 "))
text = ()
i = 0
# for i in range(21): # для проверки
if user_text == 1:
text = user_text, "Процент"
elif user_text == 2 or user_text == 3 or user_text == 4:
text = user_text, "Процента"
else:
text = user_text, "Процентов"
# print(text) # для проверки
#... |
a8dfb10c13eaf06e65cc7b419ceb772936537790 | edellle/Python | /lesson_5/task_5.py | 704 | 4.34375 | 4 | # Создать (программно) текстовый файл, записать в него программно набор чисел, разделенных пробелами.
# Программа должна подсчитывать сумму чисел в файле и выводить ее на экран.
with open ('text_5.txt', 'w+') as my_file:
numbers = input ('Введите одно или несколько чисел через пробел: ')
my_file.write(numbers... |
661a04197a4e2d05d61451f10c84f2219fed8fa7 | M0nd4/discopt | /ls/magicsquare/generate_random_square.py | 640 | 4.40625 | 4 | #!/usr/bin/python
import sys
import random
def generate_square(size):
"""Create square of consecutive numbers as test data for magic square"""
nums = size * size
seq = random.sample(list(range(1, nums + 1)), nums)
output = ''
for i in range(nums):
if i > 0:
output += " "
... |
96bc4214616055bbebb5f5d095f8d9d282bcedb3 | ShuklaShubh89/adventofcode2015 | /3a.py | 639 | 3.65625 | 4 | from collections import defaultdict
def def_value():
return 0
directions = input()
directionlist = list(directions)
coordinates = [0,0]
housevisits = defaultdict(def_value)
for x in directionlist:
if(x == '^'):
coordinates[1]+=1
elif(x == 'v'):
coordinates[1]-=1
elif(x == '>'):
... |
8c8d11b6111c82be7e53cb19ff73d76b300d8d6d | Kawser-nerd/CLCDSA | /Source Codes/CodeJamData/15/22/18.py | 1,701 | 3.578125 | 4 | #!/usr/bin/python2.7
import math
f = open('input.txt', 'r')
T = int(f.readline())
def solve_even(r, c, n):
sp = r * c - n
total = 2 * r * c - r - c
if r > c:
t = r
r = c
c = t
if r == 1:
if sp >= c / 2:
return 0
else:
return total - 2 ... |
06d584d7f22583a92088ebcc84ff340707772044 | Zaxcoding/personal-projects | /Project-Euler/Old problems/Problem 12.py | 594 | 3.53125 | 4 | # Problem 12
# What is the value of the first
# triangle number to have over
# five hundred divisors?
#def factors(a): # finds the factors of a
# x = num = 0 # and returns how many to
# while x <= a:
# x += 1
# if a % x == 0:
# num += 1
# return num
def triangle(n):
bestnum = best = 0
b = a = 1
while be... |
0ae91b5293f8cfe23d006d1333f43c259253223e | kamelzcs/study | /fraction_decimal.py | 766 | 3.890625 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
class Solution:
# @return a string
def fractionToDecimal(self, numerator, denominator):
ans = ""
if numerator * denominator < 0:
ans += "-"
numerator, denominator = abs(numerator), abs(denominator)
ans += str(numerator / denominator... |
35f5c7214ea123f524eadc1b8953990844b9ee95 | JurgenTas/Programming | /Python/Algorithms & Data Structures/bst.py | 1,229 | 3.828125 | 4 | __author__ = 'J Tas'
class Node:
def __init__(self, key, val):
self.left = None
self.right = None
self.key = key
self.value = val
class BinarySearchTree:
def __init__(self):
self.root = None
def insert(self, node):
self.root = self._insert(self.root, node... |
ba0af78395c0ebf1320cd0303366d37811934771 | SuchismitaDhal/Solutions-dailyInterviewPro | /2020/01-January/01.17.py | 714 | 3.90625 | 4 | # AMAZON
"""
SOLVED -- LEETCODE#405
Given a non-negative integer n, convert the integer to hexadecimal
and return the result as a string.
Hexadecimal is a base 16 representation of a number,
where the digits are 0123456789ABCDEF.
Do not use any builtin base conversion functions like hex.
"""... |
8712c9be98e00b8190c1d2e84fc1cdd1b0f1575b | UludagUniversitesiYazilim/Basit_Oyunlar | /XoX/XoX_Console.py | 4,676 | 3.65625 | 4 | class XoXMain():
def __init__(self):
self.oyun_tahtasi = [["___","___","___"],
["___","___","___"],
["___","___","___"]]
baslangicYazi="""
XoX oyununa hoşgeldiniz.
Oyun 2 kişiliktir.
1.Oyuncu "X"
2. Oyuncu "O"... |
14f57e6c8cac248a3d52f5de26297134c8dc2228 | zHigor33/ListasDeExerciciosPython202 | /Estrutura de Repetição/L3E8.py | 343 | 3.734375 | 4 | verifyMedia = True
i = 1
sumOfNumbers = 0
while verifyMedia:
numbers = float(input("Informe o "+str(i)+"° número: "))
sumOfNumbers = sumOfNumbers + numbers
i = i + 1
if i == 6:
verifyMedia = False
avarage = sumOfNumbers / (i - 1)
print("A média dos números é "+str(avarage)+" e a soma é "+st... |
4972e7ff161e4e64f2031b6fbcd180b2ad54cff4 | xiaofengyvan/GarvinBook | /3.1/random_sampling.py | 392 | 3.53125 | 4 | import random
def RandomSampling(dataMat,number):
try:
slice = random.sample(dataMat, number)
return slice
except:
print 'sample larger than population'
def RepetitionRandomSampling(dataMat,number):
sample=[]
for i in range(number):
sample... |
c0e714483ffac20c9bc44572b6f1311eaebb2346 | Th3-C0d3-I3r34k3r/Python_Basics | /34pyexcephandling.py | 1,625 | 4 | 4 | #Python Try Except
# try = this block lets you to test ablock of code for errors
# except = this block lets you to handle errors
# finally = this block lets you to ececute code,regardless of the result of the try=and except blocks
print ()
print (" **************************************")
print (" * Pyt... |
c1b7fb9f359a19693bc1e2d7d979065c7a988ad1 | Windsooon/LeetCode | /Next Greater Element I.py | 755 | 3.640625 | 4 | class Solution:
def nextGreaterElement(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
if not nums1 or not nums2:
return []
dic = {}
stack = []
for i in range(len(nums2)):
whi... |
9535ae66f72b181e74236016d945a067ca92a8fa | jkerw/Math-Adventures- | /rotTriangle.pyde | 744 | 3.890625 | 4 | def setup():
size(600,600)
rectMode(CENTER)
colorMode(HSB)
t = 0
def draw():
background(255)
global t
translate(width/2,height/2)
for i in range(90):
rotate(radians(360/90))
pushMatrix() #saves the orientation
#goes to circumference of circle
translate(2... |
30dfb1be543c648cddd18d6999eefd4f3bf919a6 | Mhmdabed11/CrackingtheCodingInterviewExcercisesTypeScript | /stackOfPlates.py | 2,452 | 3.75 | 4 | class StackNode:
def __init__(self, data):
self.data = data
self.next = None
class Stack:
def __init__(self, data=None):
if(data == None):
self.top = None
self.length = 0
return
self.top = StackNode(data)
self.length = 1
def push... |
925803380192f40a71d2189c2bbd09e7f5fc1ba3 | greenfox-zerda-lasers/matheb | /week-03/day-3/01.py | 621 | 4.125 | 4 | # Create a `Circle` class that takes it's radius as cinstructor parameter
# It should have a `get_circumference` method that returns it's circumference
# It should have a `get_area` method that returns it's area
class Circle():
def __init__(self, radius):
self.radius = radius
def get_circumference(sel... |
2fe25d827f8af83b2d2790cac7792638b0757668 | eddycaldas/python | /07-Strings-Methods/the-startswith-and-endswith-methods.py | 239 | 4.0625 | 4 |
another_string = 'Los pollitos dicen'
print(another_string.startswith("L"))
print(another_string.startswith("Lo"))
print(another_string.startswith("lo"))
print()
print(another_string.endswith('n'))
print(another_string.endswith('cen'))
|
71c21e274394859f7bad48b59a851bf49f90b9d4 | KataBharat/guvi | /codekata/check_difference_even_or_odd.py | 102 | 3.625 | 4 | a = [int(x) for x in input().split()]
if((abs(a[0]-a[1])%2==0)):
print("even")
else:
print("odd")
|
5f1c459bbe79e013ee973c5aa3524f1c95213c8f | natashagrasso/PARCIAL1 | /punto3.py | 666 | 3.5 | 4 | # Dado un vector con personaje de las películas de la saga de Star Wars resolver las
# siguientes actividades:
# a. Realizar un barrido recursivo del vector.
# b. Realizar una función recursiva que permita determinar si ‘Yoda’ está en el
# vector y en que posición.
personajes = ['hulk' , 'capitan america', 'yoda', ... |
f6c1608bbaa69e0294e7dd57f484d4718cce9023 | adikabintang/kolor-di-dinding | /programming/basics/crackingthecodinginterview/trees_and_graphs/tries.py | 2,527 | 3.90625 | 4 | # https://www.geeksforgeeks.org/trie-insert-and-search/
# https://towardsdatascience.com/implementing-a-trie-data-structure-in-python-in-less-than-100-lines-of-code-a877ea23c1a1
class TrieNode:
def __init__(self, ch=None):
self.ch = ch
self.children = []
self.is_end_of_word = False
class Tr... |
7c8f48004afdd70bc557e696495543203c4c37df | inJAJA/Study | /homework/딥러닝 교과서/pandas/pd04_series_append.py | 921 | 3.828125 | 4 | import pandas as pd
fruits = {'banana': 3, 'prange': 2}
series = pd.Series(fruits)
print(series)
# banana 3
# prange 2
# dtype: int64
'''요소 추가'''
# Series에 요소를 추가하려면 해당 요소도 Series형이어야 함
series = series.append(pd.Series([3], index = ['grape']))
print(series)
# banana 3
# prange 2
# grape 3
# dtype: int... |
1859ef43f26404490fad292003d132825c45dbdf | darrencheng0817/AlgorithmLearning | /Python/leetcode/BestMeetingPoint.py | 610 | 3.578125 | 4 | '''
Created on 1.12.2016
@author: Darren
'''
'''
A group of two or more people wants to meet and minimize the total travel distance. You are given a 2D grid of values 0 or 1, where each 1 marks the home of someone in the group. The distance is calculated using Manhattan Distance, where distance(p1, p2) = |p2.x - p1.x|... |
a1f47d9cade2c149a42c4db3eb5a6fbe139361e1 | Damian1724/Data-Structure | /MyLinkedList.py | 1,951 | 3.734375 | 4 | /*
Author:Damian Cruz
*/
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class MyLinkedList:
def __init__(self):
self.head = Node()
self.tail = self.head
self.size=0
def enqueue(self, data):
self.size += 1
self.tail.n... |
6f647f71e356180e141ff1473fa7b21ce0d2f1f1 | mathlot/mathlot | /demo/numerical_physics/bisection.py | 339 | 3.6875 | 4 | '''
Created on 2014.4.17
@author: YT
'''
def fun(x):
return x**2-x-1
def bisection(error_bound=0.05):
a = 1
b = 2
while abs(a-b) >= error_bound:
c = (a+b)/2.
if fun(c)*fun(a) < 0:
b = c
else:
a = b
b = c
print "bisection method: x = %.3f"... |
3b93cf57ba30c768031b9770473d6d8d7632dc94 | billgoo/LeetCode_Solution | /Top Interview Questions/Backtracking/51. N-Queens.py | 3,822 | 3.78125 | 4 | #
# @lc app=leetcode id=51 lang=python3
#
# [51] N-Queens
#
# https://leetcode.com/problems/n-queens/description/
#
# algorithms
# Hard (53.54%)
# Likes: 3935
# Dislikes: 122
# Total Accepted: 294.4K
# Total Submissions: 549.7K
# Testcase Example: '4'
#
# The n-queens puzzle is the problem of placing n queens on... |
7f82b6f53580bb7ccd8b219f00b97cdef866dae7 | hoyj/ProjectEuler | /12.py | 3,191 | 3.921875 | 4 | '''
Project Euler Problem #12
The sequence of triangle numbers is generated by adding the natural numbers.
ex) the 7th triangle number would be 1 + 2 + 3 + ... + 7 = 28.
The first ten terms would be: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
Let us list the factors of the first seven triangle numbers:
1: 1
3:... |
74412e044df353a4f7a9efc47a45ed8cab9718de | makrandp/python-practice | /Other/Companies/Amazon/AmazonBlind/FetchItemsToDisplay.py | 2,686 | 4.375 | 4 | '''
An online shopping website contains one to many items on each page. To mimic the logic of the website, a programmer has a list of items and each item has its name, relevance, and price. After sorting the items by (name: 0, relevance: 1, price: 2), the programmer is trying to find out a list of items displayed in a ... |
40246f84c3ce47b9234f5b0edd7e3db200fbc8ad | ivyson10/CANA | /funcbin.py | 165 | 3.59375 | 4 |
t = int(input())
while (t >= 0 ):
cont = 0
num = int(input())
print(num)
while (num%2 != 0):
if (num%2 == 1):
cont = cont +1
print(cont)
t = t-1
|
234a5e24a91af26c3923ba70f3849b0bb08887ef | 7Aishwarya/HakerRank-Solutions | /Python/alphabet_rangoli.py | 2,000 | 3.890625 | 4 | '''You are given an integer, N. Your task is to print an alphabet rangoli of size N.
(Rangoli is a form of Indian folk art based on creation of patterns.)
Different sizes of alphabet rangoli are shown below:
#size 3
----c----
--c-b-c--
c-b-a-b-c
--c-b-c--
----c----
#size 5
--------e--------
------e-d-e------
----e-d... |
87912cc5cbcea8b7fdae7a4e9f70f6c81152d436 | Nadaaqrtl/Tugas-Struktur-Data | /R.1.6.py | 192 | 3.921875 | 4 | def squared_odd_sum(n):
sum = 0
for number in range(n):
if number%2 == 0:
continue
sum =sum + number**2
return sum
print(squared_odd_sum(12))
|
925821fcd82a5155babaefe1c3f93f15ff2c47b9 | gffryclrk/ThinkPython2e | /ch12/ex12_10_3.py | 2,150 | 4.3125 | 4 | """
Exercise 3
Two words form a “metathesis pair” if you can transform one into the other by swapping two letters; for example, “converse” and “conserve”. Write a program that finds all of the metathesis pairs in the dictionary. Hint: don’t test all pairs of words, and don’t test all possible swaps. Solution: http:/... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.