blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
3211cb76c5277f8400bf0a666d45cf2a183bf03b | elevinixl/git_practice | /jmejia/py/refresher/iterate.py | 1,629 | 3.640625 | 4 | import copy
def sum(list) :
if len(list) == 0 :
return 0
else :
x = 0
for v in list :
x += v
return x
def max(list) :
if len(list) == 0 :
return None
else :
x = list[0]
for v in list :
if x < v :
x = v
return x
def triple(list)... |
f76cbae686a9f53ad9e40d9d0c741e16cab8c6bb | ianhom/Python-Noob | /Note_3/Example_73.py | 468 | 4 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
'''
题目:反向输出一个链表。
'''
if __name__ == '__main__':
ptr = []
for i in range(5):
num = int(raw_input('please input a number:\n'))
ptr.append(num)
print ptr
ptr.reverse()
print ptr
# Result
'''
please input a number:
12
please input a number:
23
... |
cd5b89dda0ce27d88438439d7e58b3c89128384d | ianhom/Python-Noob | /Note_1/list.py | 566 | 4.28125 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
list = [ 'abcd', 123, 1.23, 'Ian' ]
smalllist = [ 123, 'Jane' ]
print list # print all elements
print list[0] # print the first element
print list[1:3] # print the second one to the third one
print list[2:] # print the third and followi... |
b38e221744db27b3c75af44d18abf5cc1672031f | ianhom/Python-Noob | /Note_2/bill.py | 964 | 4.0625 | 4 | #!/usr/bin/python
width = input("Please enter width: ");
price_width = 10;
item_width = width - price_width;
header_format = '%-*s%*s';
format = '%-*s%*.2f';
print '=' * width;
print header_format % (item_width, "Item", price_width, "Price");
print "-" * width;
print format % (item_width, 'Apples', price... |
e83f224399b224014392a186ce55302022d0387f | ianhom/Python-Noob | /Note_3/Example_38.py | 486 | 3.6875 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
'''
题目:求一个3*3矩阵对角线元素之和。
'''
if __name__ == '__main__':
a = []
sum = 0.0
for i in range(3):
a.append([])
for j in range(3):
a[i].append(float(raw_input("input num:\n")))
for i in range(3):
sum += a[i][i]
print sum
# res... |
b5a1803cae24a766c8ae0edf9f8d866038837d1a | ianhom/Python-Noob | /Note_3/Example_72.py | 399 | 3.921875 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
'''
题目:创建一个链表。
'''
if __name__ == '__main__':
ptr = []
for i in range(5):
num = int(raw_input('please input a number:\n'))
ptr.append(num)
print ptr
# Result
'''
please input a number:
2
please input a number:
3
please input a number:
4
please inpu... |
c00a4cbed2ed5edb26bbcb8741d12f2e6bc3bf1b | ianhom/Python-Noob | /Note_2/class1.py | 981 | 4.15625 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
class dog:
'This is a dog class' #函数提示
dogcnt = 1;
def __init__(self, name, age): #构造函数
self.name = name
self.age = age
dog.dogcnt += 1
def ShowCnt(self):
print "The count of dog is %d" % dog.dogcnt
de... |
6aacdca2727612598fdcf26c9f1b698541ef038e | ianhom/Python-Noob | /App/CodeModuleGenerator/GUI.py | 1,476 | 3.703125 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
import tkinter as tk # Use for Python3
#import Tkinter as tk # Use for Python2
import CMG
window = tk.Tk()
window.title('Code Module Generator')
window.geometry('1000x500')
# Show the Title
l = tk.Label(window,
text='Code Module Generator!', # Text of Label
bg=... |
c388a643e1285aa7c0e6dc6db7edcca72e65d1f9 | ianhom/Python-Noob | /Note_2/breakelse.py | 520 | 4.09375 | 4 | #!/usr/bin/python
while True:
a = raw_input("Please input a letter: ");
if not a:
break;
s = "Hello world!!";
for n in s:
print n;
if n == a:
break;
else: # If no break happens, else code will run
print "I didn't find the \"" + a + "\", and I am NOT b... |
eb395278199731d8f9e6ff387cbd975c3525ea7e | ianhom/Python-Noob | /Note_2/file_writelines.py | 267 | 3.640625 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
f = open("Hi.txt","w");
strs = ["Hello 1", "Hello 2"];
f.writelines(strs);
f.close();
f = open("Hi.txt","r");
line = f.readline();
print line;
line = f.readline();
print line;
f.close();
# Result
'''
Hello 1Hello 2
'''
|
cac77ca2e2f724266c78ea5717206e5eb219fcda | ianhom/Python-Noob | /Note_1/fn4.py | 153 | 3.515625 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
add = lambda a1,b1:a1+b1;
mul = lambda a,b,c:a*b*c;
print add(1,2);
print mul(1,2,3);
# result
"""
3
6
"""
|
17b145587238c9692a99a96ab94f3a8f8e2ae5a8 | Ramalingam5g/PythonProgram | /inheritance.py | 933 | 3.90625 | 4 | class employee: #create a class
def employee_name(self):
self.name1="ramalingam"
self.name="gowtham"
print("employee name is:",self.name1)
print("employee name is:",self.name)
class employee1:
def employee_salary(self):#create funcion with default argument
... |
4d4f0c00d086198d3899bce833ed3463c30a5599 | sam-79/Assignment_Submission | /Day1_Assignment.py | 370 | 4.1875 | 4 |
#List sorting in descending order
int_list = [74,4,2,7,55,76,47478,4,21,124,42,4,4,36,6,8,0,95,6]
int_list.sort(reverse=True)
print(int_list)
alpha_list=['t','o','i','q','z','m','v','p','r']
alpha_list.sort(reverse=True)
print(alpha_list)
#User input list sorting
input_list= input("Enter list elements: ").split(... |
c71c2cbfdec6fdf86ffe8c07e3f2205414ac840d | en-ryuu/assignment_II | /11.py | 411 | 4 | 4 | # Name: Abhishek Pandey
# Roll no: 706
# 11. Write a Python program to replace last value of tuples in a list.
# Sample list: [(10, 20, 40), (40, 50, 60), (70, 80, 90)]
# Expected Output: [(10, 20, 100), (40, 50, 100), (70, 80, 100)]
initial = [(10, 20, 40), (40, 50, 60), (70, 80, 90)]
tuple2 = []
for i in ini... |
ac3f19ed2dcd09e970520b1114fa3ac37bd9a3a3 | en-ryuu/assignment_II | /9.py | 472 | 3.8125 | 4 | # Name: Abhishek Pandey
# Roll no: 706
# 9. Write a Python program to combine two dictionary adding values for common keys.
# d1 = {'a': 100, 'b': 200, 'c':300}
# d2 = {'a': 300, 'b': 200, 'd':400}
# Sample output: Counter({'a': 400, 'b': 400, 'd': 400, 'c': 300})
d1 = {'x': 800, 'a': 200, 'd':300}
d2 = {'x': ... |
cec9b861ffaffffd3bb24b90ba7c7987c371a776 | bhumphris/beer-song | /Bottle of beer exercise.py | 770 | 3.828125 | 4 | num_beers = 99
def song(num_beers):
while num_beers > 0:
if num_beers == 1:
print(num_beers)
print(" bottle of beer on the wall,"),
print(num_beers),
print(" bottle of beer.")
print("if one of those bottles should happen to fall,"),
pri... |
db0372c280d5b6263c743ec6095f4b01e34ceccf | trinuxoid/overthewire-bandit | /ROT13.py | 766 | 4 | 4 | """
ROT13
cryptor and decryptor
"""
import string
#Insert the text you want to encrypt or decrypt into the variable.
text = 'Lbh ner n ynml nffubyr jub pna\'g cebtenz fvzcyr tneontr.'
ALPH = string.ascii_lowercase
#cryptor and decriptor
def cryptor(text):
buf = ''
num = 0
for char in text:
flag_up... |
3c996863f96732887e05e363394e966baa2f3006 | MatejKopcik1/pytonik | /vlajka.py | 512 | 3.546875 | 4 | import tkinter
from random import randrange, randint
sirka = 1200
vyska = 800
c=tkinter.Canvas(width=sirka, height=vyska, bg="white")
c.pack()
for _ in range(3000):
x, y = randrange(10, sirka - 10), randrange(10, vyska - 10)
if 300 < x < 400:
farba = "white"
elif 350 < y < 450:
... |
1eba22fb457ea3b67d9bec2ec6bba7823daf1e21 | l15973/LeetCode | /283_Move Zeroes.py | 736 | 3.609375 | 4 | class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
# given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].
# Method 1
count... |
6fcd737451cdbbc220679a15df47285cb8e273ca | aryanbuzz9/BBI-Pushpendra | /Program9/String_is_serie.py | 230 | 3.53125 | 4 | s="bacbcc"
l=[]
a=[]
for i in s:
if(i not in l):
l.append(i)
a.append(s.count(i))
#print(a)
for i in range(1,max(a)+1):
if(i not in a):
print("No")
else:
print("Yes")
break
|
31874ad3ed8de5d26672172a1c54329c5e5f8220 | denyszamiatin/file_server | /main.py | 1,951 | 3.59375 | 4 | """
Entry point for File Server project
"""
import sys
from file_server import File, FileServerError
if __name__ == '__main__':
PROMPT = "------======##########======------"
print ("Welcome to File server v0.1")
print (PROMPT)
try:
CWD = File.chg_dir()
print ("Currentl... |
95ed9186ff429da5cbc7738045b623ef3af6deaa | nhiggins13/leetcode | /house_robber.py | 264 | 3.609375 | 4 | def rob(house_list):
prevMax = 0
currMax = 0
for num in house_list:
temp = currMax
currMax = max(prevMax + num, currMax)
prevMax = temp
return currMax
h_list = [3, 1, 2, 5, 4, 2]
print(rob(h_list))
print(h_list[0:-1]) |
d1832e2f6df2d20c6c0a9082ec4d4f36e0a6d95a | kantord/cx | /src/cx/common/currency.py | 365 | 3.53125 | 4 | from cx.common.exceptions import UnknownCurrencyError
VALID_CURRENCIES = {"EUR", "USD", "CZK", "PLN"}
BASE_CURRENCY = "EUR"
assert BASE_CURRENCY in VALID_CURRENCIES
def validate_currency(currency):
"Verifies the validity of a currency"
if currency not in VALID_CURRENCIES:
raise UnknownCurrencyError(... |
77d0abff90b9d55b3328177e719ebbd14ab7ad86 | KrutikaKothawale/Market-Basket-Analysis-Recommendation | /Pipeline/featureengg.py | 12,219 | 3.640625 | 4 |
import pandas as pd
import numpy as np
def feature_engineering():
# ## Loading Datasets:
# ##### List of files imported and loaded
#
# * Aisles.csv – This contains the names of the aisles based on the products in them.
# * Departments.csv – It has the names of department categorized by pro... |
b4846f40d65c2f8720d13146b79afcb2c8ab9d12 | agmontserrat/Ejercicios_Python_UNSAM | /Clase07/ej79.py | 878 | 3.578125 | 4 | # Ejercicio 7.9
# Modificá el siguiente código para reproducir el gráfico que se muestra.
# Prestá atención a cómo se numeran los subplots.
import matplotlib.pyplot as plt
fig = plt.figure()
plt.subplot(2, 1, 1) # define la figura de arriba
plt.plot([0,1,2],[0,1,0]) # dibuja la curva
plt.xticks([]), plt... |
b68e7cd455c23630cae9c80094108316a5f3683d | agmontserrat/Ejercicios_Python_UNSAM | /Clase07/documentacion.py | 1,155 | 4.125 | 4 | #Para cada una de las siguientes funciones:
#Pensá cuál es el contrato de la función.
#Agregale la documentación adecuada.
#Comentá el código si te parece que aporta.
#Detectá si hay invariantes de ciclo y comentalo al final de la función
def valor_absoluto(num):
'''Devuelve el valor absoluto de un número... |
176270d51ddb0c363da7734b0c789732a7f101b5 | agmontserrat/Ejercicios_Python_UNSAM | /Clase01/inclusivo.py | 736 | 3.921875 | 4 | # Traductor (rústico) al lenguaje inclusivo
# Queremos hacer un traductor que cambie las palabras masculinas de una frase por su versión neutra.
# Completá el siguiente código para reemplazar todas las letras 'o' que figuren en el último o anteúltimo caracter de cada palabra por una 'e'.
# Por ejemplo 'todos somos p... |
00aaf676e9b3e1465c35acef2931f518ac4871fa | agmontserrat/Ejercicios_Python_UNSAM | /Clase01/esfera.py | 357 | 3.96875 | 4 | # esfera.py
# Escribí un programa llamado esfera.py que le pida al usuario que ingrese por teclado el radio r de una esfera
# y calcule e imprima el volumen de la misma.
import math
radio = input("Ingrese el radio r de una esfera:")
volumen = (4 * math.pi * (int(radio) ** 3)) / 3
print("El volumen de una esfera... |
939e145f39f9d6afb4e5cf8a2a0e5c020d69320c | oildo/Cookie-Clicker | /cookieClicker/auto_clicker.py | 2,393 | 3.53125 | 4 | import pygame
class AutoClicker(object):
"""docstring for AutoClicker."""
def __init__(self, fenetre, x, y):
self.fenetre = fenetre
self.x = x
self.y = y
self. height = 50
self.width = 50
self.marge = 8
self.marge_d = int(self.marge*2) # marge [D]oublée... |
eb2317f6272c5cbdc7f394eadfa6ed6141e48826 | ajkinder/snake_game | /main.py | 1,477 | 3.875 | 4 | # Snake
# Snake - the Game = developed in Python
# Author: Alexander Kinder
from turtle import Screen
from snake import Snake
from food import Food
from scoreboard import Scoreboard
import time
WALL = 290
DISTANCE_TO_FOOD_FOR_SCORE = 15
screen = Screen()
screen.setup(width=600, height=600) # Setup screen
screen.bgc... |
493ab72cf70beff879e89e01a190c05d72d6a2e6 | Kimyehoon/python | /src/chap06/p279.py | 172 | 4.03125 | 4 | #1
numbers = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
reversed = numbers[::-2]
print(reversed)
#2
numbers = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
numbers[1:] = [ ]
print(numbers)
|
a13193bb6057fd44d4050784f6d53c0a3a6e5c5d | Kimyehoon/python | /src/chap05/p222_bisection.py | 693 | 3.96875 | 4 | ##
# 이 프로그램은 이분법을 구현한다.
#
# 함수를 정의한다.
def f(x):
return(x**2-x-1)
def bisection_method(a, b, error):
if f(a)*f(b) > 0:
print("구간에서 근을 찾을 수 없습니다.")
else:
while (b - a)/2.0 > error: # 오차를 계산한다.
midpoint = (a + b)/2.0 # 중점을 계산한다.
# print(midpoint)
if f(m... |
b74dfd0e84bdf858e8a1a6fb9c7de042101c3ec0 | Kimyehoon/python | /src/chap06/p257.py | 330 | 3.8125 | 4 | #1
temps =[28,31,33,35,27,26,25]
for i in range(len(temps)):
print(temps[i], end=', ')
#2
temps =[28,31,33,35,27,26,25]
for element in temps:
print(element, end=', ')
#3
questions =['name','quest','color']
answers =['Kim','파이썬','blue']
for q, a in zip(questions, answers):
print(f"What is your {q}? It is {a}"... |
0708e6f1472e57397b2bbb39810faa1baec976fe | Kimyehoon/python | /src/chap06/p281_salary.py | 224 | 3.53125 | 4 | salaries = [200, 250, 300, 280, 500]
def modify(values, factor) :
for i in range(len(values)) :
values[i] = values[i] * factor
print("인상전", salaries)
modify(salaries, 1.3)
print("인상후", salaries)
|
a64af36da2d9cc6195c21b9021e3ef56f08ce958 | Kimyehoon/python | /src/chap03/p126_conditional.py | 188 | 3.9375 | 4 | x = int(input("첫 번째 수 ="))
y = int(input("두 번째 수 ="))
max_value = (x if x > y else y)
min_value = (y if x > y else x)
print("큰 수=", max_value, "작은 수=", min_value) |
6e42b68e432282c635a4d156bef2a56e365de4fa | Kimyehoon/python | /src/chap06/p283.py | 537 | 3.734375 | 4 | #1 가격이 저장된 리스트가 있는 경우, 가격이 음수이면 0으로 바꾸는 코드
prices = [135, -545, 922, 356, -992, 217]
mprices = [i if i > 0 else 0 for i in prices]
print(mprices)
#2 단어의 첫글자만을 추출하여 리스트로 만드는 코드
words = ["All", "good", "things", "must", "come", "to", "an", "end."]
letters = [ w[0] for w in words ]
print(letters)
#3 x와 y 인수를 동시에 사용하여... |
961f6ea0dd82d541774cb0ae2c5f9fae73452fda | zois-tasoulas/DailyInterviewPro | /p22/p22.py | 366 | 3.765625 | 4 | def gridTraversal(n, m):
grid = [[0] * m] * n
for i in range(n):
grid[i][0] = 1
for i in range(m):
grid[0][i] = 1
for i in range(1, n):
for j in range(1, m):
grid[i][j] = grid[i][j - 1] + grid[i - 1][j]
return grid[n - 1][m - 1]
if __name__ == '__main__':
n... |
9d6d8eabdfaba18632119ff1908401934dcdbaf6 | zois-tasoulas/DailyInterviewPro | /p40/p40.py | 822 | 3.828125 | 4 | class Solution:
def buddyStrings(self, string1, string2):
length = len(string1)
if length != len(string2):
return False
if string1 == string2:
return length > len(set(string1))
differences = 0
for i in range(length):
if string1[i] != string... |
5c83dc46feb85ab90829d73bd7db8b3c1a2a6036 | zois-tasoulas/DailyInterviewPro | /p58/p58.py | 294 | 3.984375 | 4 | class Solution:
def reverseWords(self, string):
"""
:type string: str
:rtype: str
"""
return " ".join(x[::-1] for x in string.split())
if __name__ == '__main__':
sentence = "I'd need to study harder"
print(Solution().reverseWords(sentence))
|
470cdf5c0846a808c75c5738a26d01fd803ff264 | zois-tasoulas/DailyInterviewPro | /p55/p55.py | 444 | 3.796875 | 4 | from collections import defaultdict
class Solution:
def groupAnagrams(self, lst):
"""
:type lst: List[str]
:rtype: List[List[str]]
"""
d = defaultdict(lambda: [])
for word in lst:
d[tuple("".join(sorted(word)))].append(word)
return list(d.values()... |
854dcc17b4c865bcade927923b5d71fdcff56bbf | zois-tasoulas/DailyInterviewPro | /p38/p38.py | 1,289 | 3.84375 | 4 | class TreeNode:
def __init__(self, value, leftChild=None, rightChild=None):
self.val = value
if leftChild is None:
leftChild = []
if rightChild is None:
rightChild = []
self.left = leftChild
self.right = rightChild
def printTree(self):
sel... |
672974f5ddc4e92c57da3a4bdabe5f7ce9e4e42d | zois-tasoulas/DailyInterviewPro | /p57/p57.py | 680 | 3.734375 | 4 | from heapq import heappush, heappop
class Solution:
def roomScheduling(self, classes):
"""
:type classes: List[(int, int)]
:rtype: int
"""
maxRooms = 0
rooms = 0
heap = []
classes.sort()
for start, end in classes:
while heap and he... |
695893500bf78aa83749b086488216ad5c3bc29f | zois-tasoulas/DailyInterviewPro | /p11/p11.py | 1,605 | 3.671875 | 4 | class treeNode:
def __init__(self, val=0, left=None, right=None):
self.value = val
self.left = left
self.right = right
def solution(self, k):
return (self.findFloor(k), self.findCeiling(k))
def findFloor(self, k):
if self.value == k:
return k
eli... |
459f1b0cd118927d9439139c834a73355de2d56e | mohamedelshorbagy/Tiny-parser-python | /parser_class.py | 16,074 | 3.90625 | 4 | from scanner_class import Scanner
from syntaxtree_draw import SyntaxTree
class Parser(object):
"""
Defines the parser class implementation follows the recursive descent approach
The flow is as the following
1. Invoke the parser scan()
2. Get the parser array of tokens
3. Using recursiv... |
d69bc0b38c3eca233f70ae59ef4b148ef314411b | Aashishparajuli/Day_2_bootcamp | /file_handling.py | 189 | 3.625 | 4 | with open('sample.txt','w+') as file:
#pass
content = file.readlines()
for line in content:
print(line.strip().capitalize())
file.write(line)
# print(content) |
abe09679ba4b45d0a77443bc81126cf7f16dfd36 | farahzuot/madlib-cli | /madlib_cli/madlib.py | 1,152 | 3.625 | 4 | import re
print('WELCOME! you are going to play madlib with me .. \nI wall ask you for a list of words to substitute for blanks in a story before showing it to you.\nWell, just answer on the command line and press ENTER')
def read_template(path):
with open(path,'r') as file:
text = file.read()
ret... |
dfefd5d7cf0f851d20d608b745b9c8ae77c353f0 | Crawbyte/Personal_Projects | /Hangman_Game/hangman.py | 1,642 | 3.90625 | 4 | import random
import os
def read_data(filepath="data.txt"):
words = []
with open(filepath, "r", encoding="utf-8") as f:
for line in f:
words.append(line.strip().upper())
return words
def run():
name = input("Please, tell me your name ")
print("Welcome " + name + "! Good luck and ... |
b62431d3727372751bad5da56d2326fd4b3f7b72 | GITMCode/GITM | /srcPython/solar_rout.py | 7,541 | 3.53125 | 4 | #!/usr/bin/env python
#-----------------------------------------------------------------------------
# $Id: solar_rout.py,v 1.1 2013/12/23 15:53:07 agburr Exp $
# solar_rout
#
# Author: Angeline G. Burrell, UMichigan, Dec 2013
#
# Comments: Routines to calculate the solar terminator, subsolar point
#-------------------... |
ee978ade96a8582fa7cbf52e8561582a6c26e2e3 | StephKua/glowing-journey | /iris_classifier_model/iris_classifier_model.py | 1,622 | 3.5625 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Tutorial 1
# ## In this exercise, we are comparing 3 different types of classification model on the given dummy dataset.
#
# 1. SGD
# 2. Linear SVC
# 3. Random Forest
# In[1]:
import numpy as np
import pandas as pd
from sklearn import datasets
from sklearn.cross_validati... |
8e2d23fbea965bd4c894e193685b45c2f24e6d7c | antoniofranciscoandrade/data-structures-algorithms | /data_structures/stack.py | 950 | 3.78125 | 4 | class Node:
def __init__(self, val):
self.next = None
self.prev = None
self.val = val
class Stack:
def __init__(self):
self.head = Node(None)
self.len = 0
def push(self, val):
if self.len == 0:
self.head.val = val
else:
n... |
760a59227a7c8757ac49c2a4ff78b36810da3cfc | luiz158/brutils-python | /brutils/cnpj.py | 2,475 | 3.984375 | 4 | from itertools import chain
from random import randint
# FORMATTING
############
def sieve(dirty): # type: (str) -> str
"""
Filters out CNPJ formatting symbols. Symbols that are not used
in the CNPJ formatting are left unfiltered on purpose so that
if fails other tests, because their presence indica... |
1a9362c74cf56b8d9a23009d129550b3f493b2dd | thaistanaka/POOA | /TrabalhoDois/argParser.py | 249 | 3.53125 | 4 | import argparse
# função que organiza os argumentos passados por linha de comando
def argParser(listArgs):
parser = argparse.ArgumentParser()
for arg in listArgs:
parser.add_argument("--"+arg)
return parser.parse_args() |
43421be41f9561c21ba30bc1cab4eb7d4d67bc5d | zingpython/Intro_python_1 | /area_of_room.py | 388 | 3.828125 | 4 | # Write a program that asks the user to enter the width and
# length of a room. Once the values have been read, your program should compute
# and display the area of the room. The length and the width will be entered
# as floating point numbers. Include units in your prompt and output message;
# either feet or mete... |
b0a0c92a8c045850c3a995bd66cf54f0c1564666 | rheadsz/small-projects-and-stuff | /project_euler/fibsq.py | 179 | 3.5 | 4 |
f1 = 1
f2 = 1
count = 3
while True:
c = str(f1 + f2)
if len(c) == 1000:
print(c, " the pos is :", count)
break
count +=1
f1 = f2
f2 = int(c)
|
e60d1d29e10422a69b0b867be7f849f4030e51fa | baishuai/leetcode | /algorithms/p151/151.py | 300 | 4.125 | 4 | # Given an input string, reverse the string word by word.
# For example,
# Given s = "the sky is blue",
# return "blue is sky the".
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
return ' '.join(reversed(s.split()))
|
433f7c3bddd3a8b3c769c00016d905bdfe9ff965 | Kmerck88/RandompasswordGenerator | /main.py | 590 | 3.65625 | 4 | import random, string
def password(length, num=False, strength='weak'):
"""length of password, num if you want a number,
and strength(weak, strong, very)"""
lower = string.ascii_lowercase
upper = string.ascii_uppercase
letter = lower + upper
dig = string.digits
punct = string.punctuation
... |
491d243180c9947fd28c2c29bfacbeb9b00ee18c | Saumil13/Python-Learning | /TweetParser.py | 2,097 | 3.640625 | 4 | # cell 0
# cell 1
# import Twython library
# Twython library information is available here
# https://twython.readthedocs.io/en/latest/
from twython import Twython
# cell 2
# setup a Twitter developer account and get API access settings
# define the parameters that are required
api_key = "XXXX"
api_secret = "XXXX"
... |
a76df15691e3ac4a1b5bd030078d2f3a533e4cf9 | picozzimichele/blockchain-protocol | /picoin.py | 9,177 | 3.796875 | 4 | # Module 2 - Create a Cryptocurrency
# To be installed:
# python3 - venv venv (everything runs within this vitual env)
# Flask==0.12.2: pip install Flask==0.12.2
# Postman HTTP Client: https://www.getpostman.com/
# requests==2.18.4: pip install requests==2.18.4
# Importing the libraries
import datetime
import hashli... |
f3f27a65591e4c7f57aeead373651f210e8d8e6f | skossor/FinalProject18 | /magnet_clue.py | 14,346 | 4.1875 | 4 | import random
#create a list of choices the player and computer can choose from
weapons = ['drill', 'laser cutter', 'White Tardis', 'wrench', 'soldering iron', 'computer']
rooms = ['Mrs. Gersteins Room', 'the MakerSpace', 'Sanservinos Room', 'the Auditorium', 'the Main Office', 'Dr. Guptas Room']
suspects = ['Amanda',... |
17fd1c22103dd367ed6e6488eff4330f2928d0e7 | xieguoyong/shiyanlou | /cases/python_captcha/sort_test.py | 772 | 4.3125 | 4 | dic = {'a': 31, 'bc': 5, 'c': 3, 'asd': 4, 'aa': 74, 'd': 0}
print("打印出字典的键和值的列表:", dic.items())
# sorted 方法中 key指定按什么排序
# 这里的 lambda x: x[1] 即指定以列表的x[1] 即value来排序,x[0]则是以key排序
print("指定以value来排序:", sorted(dic.items(), key=lambda x: x[1]))
# sorted 默认从小到大排序,加上reverse=True 参数则翻转为从大到小排序
print("指定从大到小排序:", sorted(dic.i... |
1db60d6388780ecf89fa8763ae825bc3a6cea333 | c0y0te-git/PenTesting-Toolkit | /network_arp_scanner.py | 684 | 3.546875 | 4 | #!/usr/bin/env python3
from scapy.all import *
''' A network ARP scanner, which uses the Scapy module to ARP ping an entire network.
- c0y0te 9/28/2021 '''
# Getting interface and IP range to scan.
interface = input("[*] Please enter network interface (ex. eth0): ")
ip_range = input("[*] Please enter IP range (ex. 192... |
181f19fec56913372b5aa480dfea3e5d3c4c91b8 | senseiakhanye/pythontraining | /section5/ifelseif.py | 246 | 4.21875 | 4 | isFound = True
if (isFound):
print("Is found")
else:
print("Is not found")
#else if for python is different
num = 2
if (num == 1):
print("Number is one")
elif (num == 2):
print("Number if two")
else:
print("Number is three") |
8be1cbde17682fd0ced3771d591bc426aa282670 | DavitIspiryan/final-project-json | /hotel_oop-3.py | 6,123 | 3.65625 | 4 | import json
class Node:
def __init__(self):
self.left = None
self.right = None
def insert_price(self, data):
if self.data:
if data["single_room_price"] < self.data["single_room_price"]:
if self.left is None:
self.left = Nod... |
20c7a15ad772bd5a0b26f202d824ef54ab658a49 | Ajitesh13/Python-OOP | /numpy/1_numpy.py | 456 | 3.984375 | 4 | import numpy as np
#creating array object
arr = np.array([[1,2,3],[4,5,6]])
#printing the array type
print("Array of type: " + str(type(arr)))
#printing array dimension
print("Array dimension: " + str(arr.ndim))
#printing shape of array
print("Shape of array: " + str(arr.shape))
#printing size(no. of elements of... |
6fffceed1ff0148680aa6977d387650141e354da | astrorice2018/skyengine | /skyengine/gpsdata.py | 913 | 3.90625 | 4 | class GPSData(object):
"""
Object representing data read back from the GPS sensor.
"""
def __init__(self, lat=None, lon=None, alt=None, alt_abs=None):
"""
Create a container describing the current drone location.
:param lat: Latitude (float)
:param lon: Longitude (float... |
2807acd7534a4f8302fa221a28889015026bf3d0 | namnamir/21-Card-Game | /config.py | 2,921 | 3.8125 | 4 | class Default:
ACE_VALUE = 11
JACK_VALUE = 1
QUEEN_VALUE = 2
KING_VALUE = 3
class Messages:
ERROR_TXT = ' {}{} "{}" is not a natural number. Please ' \
'enter a valid natural number like 1 or 23! {}'
PLAYER_INPUT_TXT = ' {}{} {}! How many players are going to play? {} '
PL... |
a64221a01de337a734c1e17f2905f50fa3d707fc | caseyprogramming/Intro-to-Python-Programming | /NQueensA.py | 831 | 3.609375 | 4 | # NQueensA.py
# Write a brief Python program to randomly generate a solution to the N-Queens problem
import random
# ask the user for an N value
N = int(input("Please give me a value for N: "))
nq = list(range(N))
# generate a candidate NQ solution
def NQ_solution( NQ ):
NQ = [random.randint(0,N... |
65b7238abf15c72fb7dff76e47dc6481c416bb14 | Jda21/Funcion-RegEx | /regex.py | 285 | 3.546875 | 4 | import re
#Revisar si la cadena contiene nombre principal y apellido paterno
nombre = "John Davis Alvarez Martinez"
str = nombre
reg = re.findall("John|Alvarez", str)
print(reg)
if (reg):
print(" Si, hay coincidecia en nombre y apellido ")
else:
print("No hay coincidencias")
|
8e1ec337b708c1fcd638cd53902afee2737542bb | SSInimgba/scripts | /Regex_validate_PIN_code.py | 451 | 4.09375 | 4 | """
ATM machines allow 4 or 6 digit PIN codes and PIN codes cannot contain anything but exactly 4 digits or exactly 6 digits.
If the function is passed a valid PIN string, return true, else return false.
Examples
"1234" --> true
"12345" --> false
"a234" --> false
"""
def validate_pin(pin):
#return true o... |
1cc39e9fe4dfa9676ff0c409dc37f248ef5fb9b1 | rafaelarcangel/risarcangel | /arq2p2.34.py | 3,430 | 3.6875 | 4 | print("Welcome to Ramzi Food and Tapsi\n")
print("Main Dish\nTapsilog\tP75\nBacsilog\tP79\nTocilog\tP70\nHotsilog\tP70\nLongsilog\tP70\nBangsilog\tP75\n")
print("Drinks\nCoke\tP25\nSprite\tP25\nIced Tea\tP30\nMango Shake\tP50\nChocolate Shake\tP45\nSago't Gulaman\tP15\n")
print("Desserts\nLeche Flan\tP20\nHalo-halo\... |
d23ee50df0360e95f159291ce00b91e14004595d | rafaelarcangel/risarcangel | /arl04p2.39.py | 2,892 | 3.890625 | 4 | """R. IÑIGO S. ARCANGEL
DATALOG Lab04
Feb. 12, 2020
I have neither received nor provided any help on this (lab) activity, nor
have I concealed any violation of the Honor Code."""
from abc import ABC, abstractmethod
class Polygon(ABC):
def __init__(self, lengths_of_sides):
self.nu... |
cf346ff264dae824b0e4e9ec249580811d62d8e3 | terezaklasterecka/Asteroids | /distance.py | 889 | 3.671875 | 4 | import math
from pyglet import gl
def draw_circle(x, y, radius):
iterations = 20
s = math.sin(2*math.pi / iterations)
c = math.cos(2*math.pi / iterations)
dx, dy = radius, 0
gl.glBegin(gl.GL_LINE_STRIP)
gl.glColor3d(255,0,0)
for i in range(iterations+1):
gl.glVertex2f(x+dx, y+dy)
... |
db6a12913edb05852ebc930751422ad4559984d9 | luizxx/Projeto-de-exercicios | /exercicio 30_06.py | 721 | 4.09375 | 4 | continua = 'p'
valores = []
cinco = 5
while continua != 'n' or continua !='s':
valores.append(int(input('Digite um numero')))
continua = input('Deseja continuar? [S/N]').lower().strip()[0]
if continua =='n':
print('Fechando programa')
break
if continua =='s':
print('Continuando o ... |
d7cec42f5ba20c3107bf8ac84589521b9325b4a0 | luizxx/Projeto-de-exercicios | /listas exercicios 2 mundo3.py | 1,176 | 3.953125 | 4 | valores = list()
v = 0
valores_d = ''
continua = 'p'
cont = 0
permissao = True
original = valores[:]
while True:
if permissao == True:
v = int (input('Digite algum valor')) # ele pede um valor mais ainda sem adiciona a lista
if v not in valores: # aqui dei o criterio pra ele só adicionar a list... |
e63e66c5ea81c54e5ad0aea07210dd0d14194c62 | luizxx/Projeto-de-exercicios | /banco do luiz while.py | 776 | 3.65625 | 4 | l = 'Bem vindo ao banco do Luiz.'
ll = len(l)
print('='*ll)
print('Bem vindo ao banco do Luiz.')
print('='*ll)
valor = int (input('Digite o valor que você deseja sacar (inteiros)'))
total = valor
cedulas = 50
cont_cedulas = 0
c50 = 0
c20 = 0
c10 = 0
while True :
if total >= cedulas:
total -= cedulas
... |
9af1fbe7db55c6bff6bca61c8e98b888934dfb23 | luizxx/Projeto-de-exercicios | /exercicio 14_07.py | 1,058 | 3.953125 | 4 | Lista1 = list()
pares = list()
impares = list()
Lista = list()
Permissao = True
while True:
if Permissao ==True :
Lista1 = int(input('DIGITE UM VALOR'))
if Lista1 % 2 == 0 :
pares.append(Lista1)
elif Lista1 % 2 >0:
impares.append(Lista1)
Lista.append(Lista1) ... |
8e16de6df5c983ba11e55cc01fa7d3ae04437e8c | vktrbucci/projects-bootcamp | /week_1_guessing_game.py | 615 | 3.828125 | 4 | from random import randint
from IPython.display import clear_output
computer_number = randint(0, 100)
guesses = 0
guessed = False
while not guessed:
player_number = int(input('In what number am I thinking? '))
guesses += 1
clear_output()
if player_number == computer_number:
print('You took {}... |
f646007fc72ed8edf33668ee26328d24629a3dc3 | ChengduDriftKing/PythonLeetcode | /TencentSelect.py | 20,793 | 3.703125 | 4 | import re
import math
import itertools
import collections
import heapq
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 2.两数相加
# 给出两个非空... |
c3069847b7fe32e44c982878002dd6ebf32245ec | za419/adventofcode2020 | /day-6/program.py | 1,007 | 4.03125 | 4 | #!/usr/bin/env python3
values=[]
# Read string inputs into values
with open('input', 'r') as file:
values=file.readlines()
# Trim each line
values=[value.strip() for value in values]
# Assemble groups
groups=[]
group=[]
for value in values:
if len(value)==0:
groups.append(group.copy())
g... |
b872c0896b9b863c7cf9301e521708ab1ab05a9c | HCHIEND/computational-Thinking-And-Program-Design | /hw6.py | 315 | 4.03125 | 4 | # 1. 用input()函數取得姓名、年紀與體重的資訊
## 用變數儲存資料
# 2. 用print()函數螢幕列印特定內容
name = input("請問貴姓大名? ")
print("你好,", name)
age = input("請問年紀?" )
print("原來你", age , "歲")
weight = input("請問體重?")
print("體重為", weight) |
722330253388e3220c4c5dae00ac9bd984df8dfe | sandeshpokhrel54/Chaos-Game | /cantor.py | 367 | 3.609375 | 4 | import matplotlib.pyplot as plt
x = [2,8]
y = [8,8]
def plot(x,y,counter):
if (counter) > 1 :
plt.plot(x,y,'b')
plot([x[0],x[0]+(x[1]-x[0])/3] , [y[0]-0.5,y[1]-0.5],counter/3)
plot([2/3*(x[1]-x[0])+x[0],x[1]] , [y[0]-0.5,y[1]-0.5],counter/3)
print(counter)
... |
64d26f1df5375601cf83643178b457c8378bd51a | pintti/Koodia | /Tietokannat ja algoritmit/loppuv8_routealgo.py | 5,046 | 3.640625 | 4 | import time
INF = float('inf')
class City:
"""Luokka johon tallennetaan seuraava kaupunki sekä näiden kahden kaupungin välisen reitin korkeus.
next_city = Seuraavan kaupunhin numero
city_height = Tien korkeus"""
def __init__(self, city, height):
self... |
77826036a86fb91143cf3d8c09cdd71bde470eaf | Donearm/data-structures-and-algorithms | /algorithms/python/bst/bst.py | 5,177 | 3.921875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
#
# Copyright (c) 2019, Gianluca Fiore
#
###############################################################################
__author__ = "Gianluca Fiore"
class Node(object):
def __init__(sel... |
ff79426298f29308d0f506d93705ce086baf7bcd | JRChow/Reversi | /reversi_logic.py | 9,554 | 3.578125 | 4 | """Adversarial Search. Logic for the Reversi game."""
from collections import namedtuple
infinity = float('inf')
GameState = namedtuple('GameState', 'to_move, utility, board, moves')
# ______________________________________________________________________________
# Alpha-beta cut-off search
def alphabeta_cutoff_s... |
77599f7b0649f0d349b6058b74050223e50d9d68 | monsterchan/DeepLearning.ai | /Part1Week2Home1/work1.py | 8,330 | 3.75 | 4 | import math
def basic_sigoid(x):
return 1/(1+math.exp(-x))
print(basic_sigoid(3) )
import numpy as np
def sigmoid(x):
return 1/(1+np.exp(x))
x = np.array([1,2,3])
print(sigmoid(x))
# [0.26894142 0.11920292 0.04742587]
#练习:创建函数sigmoid_grad()计算sigmoid函数相对于其输入x的梯度。 公式为:
# sigmoid\_derivative(x) = \sigma'(x) = ... |
76eab31fb851000fd2884b2ca88822943b84e08a | Jack-Flynn/01_lucky_unicorn | /pythonProject/rounds_and_statements.py | 2,762 | 4.09375 | 4 | # Functions go here
def yes_no(question):
valid = False
while not valid:
response = input(question).lower().strip()
if response == "yes" or response == "y":
response = "yes"
return response
elif response == "no" or response == "n":
response = "no"
... |
8cb650c34b4b45ce1541f8d2dc540ebd0d6d5a3e | bunnyDrug/relue | /problem5.py | 444 | 3.71875 | 4 | #2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
#What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
numbers = range(20,2,-1)
test_num = 2
iterator = 0
while iterator < len(numbers):
if test_num % numbers[it... |
311830cd4517627eb56037884a60700d11464dab | HendricksJudy/Modular-programming | /Recursive pratice-factorial.py | 635 | 3.65625 | 4 | # 实现阶乘
# def jiecheng(n):
# if n == 1:
# return 1
# else:
# return n*jiecheng(n-1)
#
# res = jiecheng(7)
# print(res)
'''
递归函数的效率并不高,能不用尽量不用
一个函数如果调用后,没有结束,那么在栈空间就一直存在,直到这个函数运算结束后才销毁
'''
# 斐波那契数列
# 求第n位上的数是多少
num = 0
def feibona(n):
global num
num += 1
if n == 1 or n==2:
... |
95a0565e33b1c536857d8489b07c1867563422ad | hacker96suki/InteligenciaArtificial | /4Caballos.py | 1,064 | 3.609375 | 4 | #Esquivel Macías Erick Xavier 16590461
#Gómez Olvera Jacob Misael 16590474
import json
with open ("caballos.json","r") as read_file:
data = json.load(read_file)
Arbol = data['Arbol']
TableroI = data['TableroI']
TableroF = data['TableroF']
def caballos(Mat,fin,op):
Tablero=[
[0,0,0],
[0,0,0],
[... |
baca925b539e5fcc04be482c5fc8b27a6ff355eb | johnstinson99/introduction_to_python | /course materials/b05_matplotlib/d_sankey/sankey_example_1_defaults.py | 1,070 | 4.34375 | 4 | """Demonstrate the Sankey class by producing three basic diagrams.
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.sankey import Sankey
# Example 1 -- Mostly defaults
# This demonstrates how to create a simple diagram by implicitly calling the
# Sankey.add() method and by appending finish() to ... |
385e580231bd8ad03756efaa5845ee105e41be8a | johnstinson99/introduction_to_python | /course materials/b02_matplotlib_introduction/example_1_simple.py | 214 | 4 | 4 | import matplotlib.pyplot as plt
x_list = [1, 2, 3, 4, 5]
y_list = [1, 2, 3, 4, 5]
plt.plot(x_list, y_list)
plt.show()
# add color, linestyle, marker
# add second line
# add labels
# see example 5 for tick labels |
23e736a696e98d7555ffc32f376bf81492c440e4 | gblack686/UCI_Data_Analytics | /UCI_Data_HW/Python/GB_PyBank.py | 1,223 | 3.625 | 4 | import csv
import os
file = "budget_data.csv"
outputfile = "budget_analysi.csv"
with open(file) as budget_data:
reader = csv.reader(budget_data)
header = next(reader)
firstrow = next(reader)
net_start = int(firstrow[1])
monthtracker = 1
netprofit = net_start
lastnet = 0
netchangelist = []
prevnet = net_star... |
1b1039ca38aeb47c12976a4f5317c09fe55f3426 | anuragpatilc/anu | /Task10_Money_Counting_Game.py | 697 | 3.828125 | 4 | # Money Counting Game
# Information or manual of the game foll this to win all tha best
# 100 pennies = 1 dolor
# 20 nickels = 1 dolor
# 10 dimes = 1 dolor
# 4 quarter = 1 dolor
pennies = int(input('Enter the PENNIES: '))
nickels = int(input('Enter the NICkELS: '))
dims = int(input('Enter the DIMS: '))
quarte... |
5ccd13317a720920ab61ce9654db229983dfc6c2 | anuragpatilc/anu | /a_kilometer_converter.py | 351 | 3.953125 | 4 | # This program is going to convert the kilometer to miles
def main():
miles = in_put() * 0.6214
print('\t\t\t\t', format(miles, ',.2f'))
def in_put():
kilometer = int(input('Enter the kilometer: '))
print('kilometer \t\t miles')
print('----------------------')
print(kilometer)
... |
ce13793f597a0bc2530c66a66309bf11a80f7765 | anuragpatilc/anu | /Task17_Wi-Fi_Diagnostic_Tree.py | 748 | 3.828125 | 4 | # Program to Diagnostic the wifi rooter
# Variables declaration
a = 'no'
b = 'yes'
print('If the rooter is not working properly do the following steps to solve the problem')
print('Reboot the computer and try to connect.')
c = input('Did that fix the problem?: ')
if c == a:
print('Reboot the router and try ... |
128535fd36296aa4647f4f631764006b5104ba4c | anuragpatilc/anu | /Population.py | 446 | 4.03125 | 4 | # Program to calculate the population
s = int(input('Enter the starting number of the organisms: '))
a = int(input('Enter the average daily increase in percentage: '))
n = int(input('Enter the number of days to multiply: '))
per = a / 100
print('Day Approximate \t\t Population')
print('___________________________... |
1fc9ba256d1201e878b76e6d9419d162d0e9cd59 | anuragpatilc/anu | /TAsk9_Rouletle_wheel_colors.py | 992 | 4.375 | 4 | # Program to decides the colour of the roulette wheel colour
# Ask the user to select the packet between 0 to 36
packet = int(input('Enter the packet to tell the colour of that packet: '))
if packet < 0 or packet > 36:
print('Please enter the number between 0 to 36')
else:
if packet == 0:
print('... |
83ccf65950e90bd1cf095c29e5b1c61b1d7a75d9 | zeus911/sre | /leetcode/Search-for-a-Range.py | 1,062 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'liuhui'
'''
Given an array of integers sorted in ascending order, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
... |
bcbf7cc023ecc59c1840c95a1c928646cb5c7627 | mimichen226/GirlsWhoCode_SIP2018 | /TeamRelay/example.py | 248 | 3.859375 | 4 | food = {"asparagus": {"type": "veggie", "PLU": 3079},
"pistachio": {"type": "nut", "PLU": 4941},
"avocado": {"type": "fruit", "PLU": 3354}
}
for food_name, food_info in food.items():
print("{} is a {}".format(food_name, food_info["type"]))
|
479025c7299271c376ac1e8a71cc7cb990339f87 | mimichen226/GirlsWhoCode_SIP2018 | /Python/Libraries/mult_return_values.py | 397 | 4.09375 | 4 | def cool_math(number):
sqrt = number**(1/2)
square = number**2
mod3 = number % 3
return sqrt, square, mod3
magic_number = 5
square_root, square, modulus_3 = cool_math(magic_number)
print("The square root of {} is {}".format(magic_number, square_root))
print("The square of {} is {}".format(magic_number,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.