blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
44a981d0bb30cc57c6fd15ed98e02993129563cd | sprksh/quest | /recursion/backtracking/backtracking.py | 1,657 | 4.34375 | 4 | """
Backtracking is when you backtrack after recursion
Examples in n_queens in the bottom section
"""
class newNode:
# Construct to create a new node
def __init__(self, key):
self.key = key
self.left = None
self.right = None
self.parent = None
def __repr__(self):
... |
155fa7730534f6bd7eb3974b03e79e7bf047dd0e | sprksh/quest | /graph/dag_traversal.py | 4,981 | 4.25 | 4 | """
Presenting a comprehensive explanation of Graph traversal, BFS & DFS
dag: Directed Acyclic Graph
"""
class Graph:
"""
This is a directed graph.
What happens in a non directed graph?
"""
def __init__(self, graph):
self.graph = graph # defaultdict(list)
def breadth_first_sear... |
a06382da93a97b1c1d24c428b872d7444b622c39 | sprksh/quest | /array_pointer/three_pointer.py | 948 | 3.953125 | 4 | """
sort an array of 0, 1 & 2
[1,2,0,0,0,1,2,1,1,0,2]
^ ^
while mid index < hi index:
if mid == 0: swap with lo, move lo right till it is not 0
if mid == 2: swap with hi, move hi left till it is not 2
if lo < mid: swap; move mid right
"""
def sort_arr012(arr):
lo, mid, hi = 0, 0, len(a... |
39c9c4c2c087c48d7622297e8c5f494d99e8ac99 | os1001/password_en | /password_bfa.py | 401 | 3.765625 | 4 | import random
import string
password = str(input("Enter your password:"))
def get_random(num):
while not None:
rom_onetime = [random.choice(string.ascii_letters + string.digits) for i in range(num)]
onetime = "".join(rom_onetime)
print(onetime)
if password == onetime:
p... |
3467728b8344b54e1b2b4b413396b66738ce7f52 | MarioTuMa/vigenere | /vigenere.py | 525 | 3.734375 | 4 | import sys
args = sys.argv
method = args[1]
msg = args[2].lower()
key = args[3].lower()
alphabet = 'abcdefghijklmnopqrstuvwxyz'
dict = {}
count = 0
for char in alphabet:
dict[char]=count
count+=1
def decode(letter,key,method):
if method == "decode":
return alphabet[(dict[char]-dict[key])%26]
... |
f67d8794561a0234c5dcd65dc5528334b93b6c68 | AlexanderGitHubTest/lesson1_git | /test_git.py | 89 | 3.65625 | 4 | a=2
b=2
def sum_a_b(a,b):
return a+b
print(f"2+2=4 a={a}, b={b}, a+b={sum_a_b(a,b)}") |
b8970e4ce6de9699f47ffe9d934d207d49b7a34c | mariopuebla17/PythonExercicios | /ex005.py | 130 | 3.96875 | 4 | n = int(input('Digite um número: '))
ant = n - 1
suc = n + 1
print('O seu antecessor é {} e o sucessor é {}'.format(ant, suc))
|
061417e2bfbb8032f572f5f385a176ed1b23ca32 | mariopuebla17/PythonExercicios | /ex013.py | 194 | 3.6875 | 4 | salario = float(input('Informe o salário do funcionário: R$ '))
novoSalario = salario * 1.15
print('Com um aumento de 15%, o novo salário do funcionário será de R$ {}'.format(novoSalario))
|
11c7af88e9b921e6e18ee5b0d1c7b6f352957949 | mariopuebla17/PythonExercicios | /ex019.py | 302 | 3.734375 | 4 | import random
a1 = input('Informe o nome do primeiro aluno: ')
a2 = input('Informe o nome do segundo aluno: ')
a3 = input('Informe o nome do terceiro aluno: ')
a4 = input('Informe o nome do quarto aluno: ')
lista = [a1, a2, a3, a4]
s = random.choice(lista)
print('O aluno sorteado é o {}'.format(s))
|
3f4426c47d8474d931954e6189672de6d769bde8 | mariopuebla17/PythonExercicios | /ex016.py | 135 | 3.96875 | 4 | from math import floor
n = float(input('Digite um número: '))
i = floor(n)
print('O número {} tem a parte inteira {}.'.format(n, i))
|
e79aec0071a9ecdba6e773cd8f21a392693f70d2 | akushnirubc/pyneta | /Exercises/week_7_xml_nx-api/exercise1d.py | 627 | 3.515625 | 4 | # Using both direct indices and the getchildren() method,
# obtain the first child element and print its tag name.
from __future__ import unicode_literals, print_function
from lxml import etree
# Using a context manager read in the XML file
with open("show_security_zones.xml") as infile:
# parse string using et... |
6a55c9c131b08c9afd042592d7b3b5db8cec153e | insomnia-soft/projecteuler.net | /004/004.py | 831 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
def palindrome(n):
m = n
p = 0
while m > 0:
mod = m % 10
m /= 10
p = p * 10 + mod
if p == n:
return True
return False
def main():
"""
Largest palindrome product
Probl... |
d8bbd7b6bdb95b21753584ac3605e757289f10b3 | eychcue/CryptoAlexaSkill | /differentFunctions.py | 3,636 | 3.78125 | 4 | # create function for getting the price of
# Volume, price_usd
import requests
import inflect
p = inflect.engine()
#name1 = raw_input("Enter the name of the currency")
def Coin(name):
return requests.get("https://api.coinmarketcap.com/v1/ticker/" + name).json()
#data = Coin("bitcoin")[0]
#print data
#prin... |
15fd0aebc233508f0bae2a3db497d20eb2efe736 | bithost-gmbh/txlwizard | /Patterns/Ellipse.py | 6,459 | 3.859375 | 4 | '''
Implements a class for `Pattern` objects of type `Ellipse` (`ELP`).\n
Renders an ellipse.
'''
import AbstractPattern
import math
class Ellipse(AbstractPattern.AbstractPattern):
'''
Implements a class for `Pattern` objects of type `Ellipse`.\n
Corresponds to the TXL command `ELP`.\n
Renders an elli... |
455740b918b6712a8a6776dcd360e93fe9b4bc1e | Franco-Lobos/bookShopFinder | /utils.py | 163 | 3.71875 | 4 | def listDictionary(file):
listedWords =[]
text = open(file)
for word in text.readlines():
listedWords.append(word[:-1])
return listedWords
|
0a7752c98b0a2039855cfd525e6e119b453769c8 | pixie-lulu/learnpython | /Joseph_ring3.py | 1,390 | 3.578125 | 4 | class Creat_person:
#__init__()函数的一个变量一定是self表示创建的实例,self不需要传参
def __init__(self,num,name,gender,age):
self.number = num
self.name = name
self.gender = gender
self.age = age
persons = []
numbers = [1,2,3,4,5,6,7,8,9]
names = ["Bob","Cindy","Alex","Aira","Michael","James","Jack",... |
8691f56fca4c1ae2e4fabf30bd5ba20f49793896 | YebinK/PracticingAlgorithms | /BaekJoon/11656.py | 266 | 3.90625 | 4 | str = input()
if len(str) <= 1:
print(str)
exit()
suffix = []
for i in range(1, len(str) + 1): #get suffix
suffix.append(str[len(str) - i:len(str)])
suffix = sorted(suffix) #sort suffix
for i in range(len(suffix)):
print(suffix[i]) |
117a182309f83cf5a8f3d234ffae40d7825d94ca | ChristopherDonnelly/Python_Underscore | /Underscore.py | 4,209 | 4.09375 | 4 | '''
Your own custom Python Module!
Did you know that you can actually create your own custom python module similar to the Underscore library in JavaScript? That may be hard to believe, as the things you've learned might seem simple (again, we try to make it look simple... (-: ), but in truth, you know how to create sig... |
b9ac773a1593bb1e4159958318f1935376dd577d | SharonLingqiongTan/pythonSkills | /threadingTest.py | 339 | 3.546875 | 4 | #!/usr/bin/env python
import threading
def main():
# The program shows 1 thread is running, which is this test program!
print threading.active_count() # see how many threads running
print threading.enumerate() # list of threads running
print threading.current_thread() # current thread
if __name__ == '__m... |
38d996f233c95314cfa2339b0e098c9d392a5679 | Linter-8/week2 | /test9.py | 1,359 | 3.890625 | 4 | #找零钱
'''
在柠檬水摊上,每一杯柠檬水的售价为 5 美元。
顾客排队购买你的产品,一次购买一杯。
每位顾客只买一杯柠檬水,然后向你付 5 美元、10 美元或 20 美元。你必须给每个顾客正确找零,也就是说净交易是每位顾客向你支付 5 美元。
注意,一开始你手头没有任何零钱。
'''
fivenumber=0 #拥有五元零钱的数目
tennumber=0 #拥有十元零钱的数目
while True:
x=int(input('顾客付你的钱 5/10/20 :')) #输入客户给的钱
if x == 5 : ... |
82b2be322b316fcfdb20c3bda8cfce97a4e2ab1d | qinshiyin/PyPython | /WinQin/Study/Str2Float.py | 483 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Aug 1 15:07:16 2016
@author: WinQin
"""
from functools import reduce
def str2float(s):
def char2num(s):
d={'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}
return d[s]
def fn(x,y):
return x*10+y
s1,s2=s.split('.')
return ... |
89d3eef1a3545008e06daddb958ac1718c6756c3 | qinshiyin/PyPython | /WinQin/Study/EnumUses.py | 256 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Aug 15 15:15:18 2016
@author: WinQin
"""
from enum import Enum
weekday=Enum('WeekDay',('Mon','Tue','Wed','Thu','Fri','Sat','Sun'))
for key,value in weekday.__members__.items():
print(key,'=>',value.value)
|
d3d12a06a92731ca0b996e239ca3c98dceb02582 | qinshiyin/PyPython | /WinQin/Study/Calc.py | 302 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jul 29 11:17:10 2016
@author: WinQin
"""
import math
def calc(*numbers):
sum=0
for n in numbers:
sum+=math.pow(n,2)
return sum
#Test
if __name__=='__main__':
a=list((1,3,5,7))
b=(1,3,5,7)
print(calc(*a))
print(calc(*b)) |
25f179c281b2454c1b003459e59e72a36024540b | hortonchase/opencv-projects | /command line arguments/command_line.py | 312 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Aug 28 15:27:04 2020
@author: Chase
"""
import argparse
ap = argparse.ArgumentParser()
ap.add_argument("-n","--name", required = True, help = "name of user")
args = vars(ap.parse_args())
print("Hi there {}, it's nice to meet you!".format(args["name"]))
|
4e698e4300e59cf032a304acb62cbacefa1af56f | matt26277/CSC-132-Final-Project | /finalproject.py | 5,103 | 3.609375 | 4 | from Tkinter import *
from random import *
class Item (object):
def __init__ (self, price, seller, location, weight, condition, brand, color, description, type):
self.price = price
self.seller = seller
self.location = location
self.weight = weight
self.condition = c... |
93e4244168a62dfdc01661ad02996ac6ce23d470 | archambers/platformer | /pygame_example.py | 2,813 | 3.5625 | 4 | import pygame
from random import random
from numpy import sin, cos, linspace, pi
#initialize pygame
pygame.init()
#color shortcuts
black = (0, 0, 0)
white = (255, 255, 255)
green = (0, 255, 0)
red = (255, 0, 0)
blue = (0, 0, 255)
size = (700, 500)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("T... |
e1264bf06aaaf887d3e7948547607e3df6be0fd7 | FriendlyVietnamese/PhoHoangVietLinh-Fundamental-C4E19 | /Labs/session8/homework/ex3+4.py | 425 | 3.796875 | 4 | from random import choice
from turtle import *
colors = ["red","yellow","blue","green","pink",'black',"orange","purple"]
pensize(2)
shape = ("turtle")
speed(-1)
def draw_square(x,y):
for edges in range(4):
color(y)
fd(x)
lt(90)
for i in range(30):
dr... |
2992131b77d8cd67901f4f0db59963fa41617a15 | FriendlyVietnamese/PhoHoangVietLinh-Fundamental-C4E19 | /Labs/session8/f-math-problem/freakingmath.py | 612 | 3.78125 | 4 | from random import randint,choice
def generate_quiz():
# Hint: Return [x, y, op, display_result]
a = randint(2,9)
b = randint(2,9)
errors = choice([-1,0,0,1,-2,+2,0])
display_result = a*b + errors
return [a, b, "x", display_result]
print(generate_quiz())
# run whenever click
def c... |
20193240db85949aa46bcbba5034dd9d9d0ec081 | FriendlyVietnamese/PhoHoangVietLinh-Fundamental-C4E19 | /Fundamental/session3/homework/turtle1.py | 315 | 3.65625 | 4 | from turtle import *
shape("turtle")
speed(-1)
pensize(2)
colors = ['red', 'blue', 'brown', 'yellow', 'grey']
cạnh = 3
i = 0
for a in range(10):
for b in range(cạnh):
color(colors[i])
fd(70)
lt(360/cạnh)
i +=1
if i == 5:
i = 0
cạnh = cạnh + 1
mainloop()
|
039a16bb1c5943333949bacaac661b5d9c8bcb6c | FriendlyVietnamese/PhoHoangVietLinh-Fundamental-C4E19 | /Fundamental/session3/bt2.py | 484 | 3.5625 | 4 | # list/ array
# print(*list) để list tất cả mà không có dấu ngoặc vuông, phảy, ngoặc kép
# sep = "" / phân tách các phần tử trong list
# CRUD - Create - Read- Update- Delete
menu = ["Kem", 'Xôi', 'Phở', 'thịt']
# print(*menu, sep = "\e")
# print(len(menu))
# menu.append("Chè")
# print(*menu, sep = "\e")
# print(len(me... |
0150fcfc25185e77f96b2a231a9d4afd4aac4155 | FriendlyVietnamese/PhoHoangVietLinh-Fundamental-C4E19 | /Python/private.py | 1,213 | 3.75 | 4 | so_tien_goc = 0
def gui():
while True:
global so_tien_goc
so_tien_gui = int(input("Moi nhap so tien gui: "))
if so_tien_gui == "x":
print("cam on da su dung dich vu")
chaomung()
so_tien_goc += so_tien_gui
print("TK hien co: %d" % so_tien_goc)
retu... |
85d70c0cbe3867a640f8ff9b0ea548b0368dc794 | Hangguo17/BigData | /importCSV1.py | 13,337 | 3.578125 | 4 | #Jerdon Helgeson
#import from csv 1
from collections import namedtuple
from collections import Counter
import csv
import os
#WILL NOT BE USING NAMED TUPLE AS THE FORMAT CAN'T BE RETURNED FROM A FUNCTION
# &&& NAMEDTUPLES CAN'T HAVE DYNAMICALLY UPDATED ELEMENTS
#WILL INSTEAD USE A LISTLIST OR NESTDLIST
#MUST UPDATE... |
556af80a4110ffc21503557d29b3f850d4af982f | Williamarnoclement/tp-doomsday-rule | /doomsday/transformate.py | 402 | 4.0625 | 4 | def transform_string_in_date(date_input: str)->list[int]:
"""Returb date as array format """
if str(date_input).count('-') != 2:
return []
#Split the date for each number separated by "-"
date_format: list[int] = date_input.split("-")
year: int = int(date_format[0])
month: int = int(dat... |
a79f2b92ad2e12d11c563f7ebfec05971fdafe54 | adithya70/Coursera-ML | /Exercises/Python/machine-learning-ex1/plotData.py | 458 | 3.5625 | 4 | from scipy import linalg, sparse #for linalg
import matplotlib.pyplot as plt #for the graph
import numpy #for lin alg operations
import pandas as pd #for reading in file
data = pd.read_csv('ex1data1.txt', header=None, delimiter=',');
X=data.values[:,0]; #zero based columns
y=data.values[:,1];
plt.title("Plotting");
p... |
29f9c644247e820e9f21d05008850a7d70358e92 | TheSmurfs/pylearn | /test1/day1/guess.py | 169 | 3.875 | 4 | age_of_old = 56
guess_age = int(input("guess age:"))
if guess_age == age_of_old:
print("yes")
elif guess_age > age_of_old:
print("big")
else:
print("small") |
306bead457c9f8c9537955b189667fd2838e0972 | brycemcd/mute-button-video-training | /video/model_generator.py | 4,792 | 3.65625 | 4 | """
Creates models for training. See:
https://github.com/brycemcd/learning_neural_networks/blob/master/training-chain/2017-11-23-model-creator.ipynb
For my scratch work on this.
Model is saved to the filesystem to be used in predictions.
"""
import numpy as np
import keras
from keras.models import Sequential
from ker... |
42196e64b61aa3b2eae29ff4506b10d44d71b93b | MiguelAzevedo2108/University-Projects | /BSc/P1/Fichas/Ficha 3/Ficha3.py | 3,527 | 4.03125 | 4 | #Ex 1
def maior ():
x = int(input("Insira o numero 1 : " ))
y = int(input("Insira o numero 2 : " ))
if (x > y) :
print("1")
if (x==y) :
print("0")
if( x<y):
print("-1")
#Ex 2
import math
def pitagoras():
cat1= float(input("Qual o comprimento do cateto 1... |
60f35d4040d2e959fc556a5c1dc9c611c7cb7873 | MiguelAzevedo2108/University-Projects | /BSc/P1/Trabalho/Together/36975_37913_37555.py | 6,876 | 3.859375 | 4 | import random
####################################
#
# menu qual pode ser escolhido Menu jogador ou Menu Computador
#
####################################
def menu():
op = input('[1] - Menu Jogador \n[2] - Menu Computador \nIntroduza opçao : ')
if op == '1' :
jogo1()
elif op == '2':
j... |
f86b60d56325e40c0fb33db3783e7be904d95dc7 | xtrdnrmnd/python_practice_2 | /Task_Two.py | 607 | 3.890625 | 4 | class Queue:
# Метод инициализации очереди
def __init__(self):
self.items = []
# Метод добавления значения в очередь
def enqueue(self, item):
self.items.insert(0, item)
# Метод поиска простых чисел
def isPrime(self):
i = 0
for itemss in self.items:
i... |
0cd7612c7b03d51629ad96ab94d48b84c7f456e7 | lbovboe/The-Lab-Python-level-1 | /1.01-8.py | 154 | 3.71875 | 4 | x=5
y=6
print("Before swopping : x " , x , " y : ",y)
temp = x # temp = 5
x =y # x =6
y = temp # y =5
print("After swopping : x " , x , " y : ",y)
|
c0a4c35df5d3dc98d6a8d560749f6ff213af0628 | lbovboe/The-Lab-Python-level-1 | /1.06-3.py | 126 | 4.1875 | 4 | num = int(input("Enter an integer: "))
if(num >= 5 and num <= 10):
print("Within the range")
else:
print("Out of range") |
3b23e311c63ab7ecbc0c2bed101f1a9cddb86971 | lbovboe/The-Lab-Python-level-1 | /1.06-5.py | 331 | 4.1875 | 4 | age = int(input("Enter your age : "))
if(age >=10 and age <=16):
ans = input("Are you a student of the lab? : ").lower()
if(ans == "yes"):
print("You must be smart! ")
else:
print("You should join the lab! ")
elif(age < 10 or age >16 and age <20 ):
print("That's the good age!")
else:
print("You are a ... |
584b89899e92eef2319839c9ddc76fed684a2e55 | thefang12/P1 | /main.py | 8,487 | 3.625 | 4 | '''
This module represents how to create an automata
to validate a set of production rules
outputing a file with thre recognized identifiers
'''
import collections
FILENAME = "lex.txt"
AUTOMATAS = {}
CHARRANGE = 127
LEXDICT = [collections.OrderedDict() for x in range(0, CHARRANGE)]
INFILE = "in.txt"
RECTOKENS ... |
ee8d495ac7772109eccd178cb56b5610ec04b1e8 | OkaGouhei/Janken_python | /Janken.py | 825 | 3.921875 | 4 | import random
def judge(player,computer):
if player == computer:
print("あいこです")
elif (player ==0 and computer ==1 ) or (player ==1 and computer ==2 ) or (player==2 and computer ==0 ):
print("コンピューターの勝ちです")
else:
print("あなたの勝ちです")
yourhandmark = int(input('出す手を入力してください 0:パー、1:チョキ、2:グー '))
while you... |
2c98a035aef6667a924a5ee14fbe23718d08055d | charlottetan/Algorithms-2 | /LeetCode 30 Day Challenge/07-counting_elements.py | 319 | 3.65625 | 4 | class Solution:
def counting_element(self, arr):
count = 0
dict = {}
for num in arr:
if num in dict:
dict[num] += 1
else:
dict[num] = 1
for x in arr:
if x + 1 in dict:
count += 1
return count |
a0762324db90de140bcadbbecf9ad44bdb6a3819 | charlottetan/Algorithms-2 | /Sorting/merge_sort.py | 800 | 4.09375 | 4 | def merge_sort(array):
if (len(array) < 2):
return array
halfway = len(array) // 2
left = array[:halfway]
right = array[halfway:]
return merge_sort_helper(merge_sort(left), merge_sort(right))
def merge_sort_helper(left, right):
left_len = len(left)
right_len = len(right)
... |
3390980f8c0818d96b09aee13f57e91562935e31 | charlottetan/Algorithms-2 | /Dynamic Programming/coin_change.py | 326 | 3.53125 | 4 | def coin_change(amount, coins):
num_of_coins = [float("inf")] * (amount + 1)
num_of_coins[0] = 0
for denom in coins:
for i in range(len(num_of_coins)):
if denom <= i:
num_of_coins[i] = min(num_of_coins[i], num_of_coins[i - denom] + 1)
return num_of_coins[amount] if num_of_coins[amount] != float("inf") el... |
7272df22e32f13a9178a345d1b31da1322d6f648 | charlottetan/Algorithms-2 | /Strings/get_longest_palindrome.py | 616 | 3.84375 | 4 | def get_longest_palindrome(string):
current_longest = [0, 1]
for i in range(1, len(string)):
odd = get_palindrome(string, i - 1, i + 1)
even = get_palindrome(string, i - 1, i)
longest = max(odd, even, key=lambda x: x[1] - x[0])
current_longest = max(longest, current_longest, key=... |
18169fdbda80452895edf5c040a49a8e3a82f279 | charlottetan/Algorithms-2 | /Binary Trees/iterative_in_order_traversal.py | 647 | 3.65625 | 4 | def iterative_in_order_traversal(tree, callback):
if not tree:
return
prev = None
current = tree
next = None
while current != None:
if prev == None or prev == current.parent:
if current.left:
next = current.left
else:
callback(... |
f051292b6830024917bdf7e334e888f36cc1e731 | MasterScott/Arcade_Labs | /Meusz-kolakowski-mateusz-arcade-games-work/Lab 04 - Camel/functions.py | 946 | 3.515625 | 4 | import random
def get_started():
print("Welcome to Camel")
print("You have stolen a camel to make your way across the great Mobi desert.")
print("The natives want their camel back and are chasing you down! Survive your")
print("desert trek and out run the natives.")
def menu():
print("A. Drink f... |
d84f2a4e29f67002db6ec8051e830730294145c2 | dnakaj/project-euler | /euler59_brute.py | 1,721 | 4.03125 | 4 | # Converts a string to an array of ints (for use in xorDecrypt)
def stringToIntArray(s):
result = []
for ch in s:
result.append(ord(ch)) # ord converts a character to its ascii equivalent
return result
# Method to decrypt an encrypted array of ints; returns an array of characters
def xorDecrypt(enc... |
b40b7a325c41448200d856cb86c936e1ab3b4eb7 | UrMagicIsMine/LeetCode-Sol | /Python/5_LongestPalindromicSubstring.py | 1,469 | 3.96875 | 4 | # Given a string s, find the longest palindromic substring in s. You may assume
# that the maximum length of s is 1000.
#
# Example 1:
#
# Input: "babad"
# Output: "bab"
# Note: "aba" is also a valid answer.
# Example 2:
#
# Input: "cbbd"
# Output: "bb"
#
class Solution(object):
def longestPalindrome(self, s):
... |
31c2019a419a335dba454aefb11f62735df929ae | seokhyun0220/pythonProject1 | /Ch04/4_1_ List.py | 940 | 4.21875 | 4 | """
날짜 : 2021/04/27
이름 : 김철학
내용 : 파이썬 자료구조 리스트 실습 교재 p84
"""
#리스트 생성
list1 = [1,2,3,4,5]
print('list type :', type(list))
print('list[0] :', list1[0])
print('list[2] :', list1[2])
print('list[3] :', list1[3])
list2 = [5,3.14, True, 'Apple']
print('list2 type :', type('list2'))
print('list2[1] :', list2[1])
print('l... |
daaceeecb07d17362dda653168f0e8654da95a25 | seokhyun0220/pythonProject1 | /Ch05/p142.py | 343 | 3.875 | 4 | # (1) 재귀함수 정의 : 1 ~ n 누적합(1+2+3+4+5=15)
def Adder(n):
if n == 1 : # 종료 조건
return 1
else :
result = n + Adder(n - 1) # 재귀호출
print(n, end=' ') # (4) 스택 영역
return result
# (2) 함수호출1
print('n=1 :', Adder(1))
# (3) 함수호출2
print('\nn=5 :', Adder(5)) |
43be50b95f9781fecb0bcb7a242061af8a8d461c | seokhyun0220/pythonProject1 | /Ch05/5_5_FuctionList.py | 1,764 | 4.375 | 4 | """
날짜 : 2021/04/29
이름 : 김철학
내용 : 파이썬 리스트함수 교재 p88
"""
dataset = [1,4,3]
print('1.dataset :', dataset)
# List 원소 추가
dataset.append(2)
dataset.append(5)
print('2.dataset :', dataset)
# List 정렬
dataset.sort()
print('3.dataset :', dataset) # 오름차순
dataset.sort(reverse=True) # 내림차순
print('4.dataset :', dataset)
# ... |
4fe11c60d3c942787abaaa246818886eba85a476 | marvinstrike/pchqtcRetoS3 | /ejercicio7.py | 150 | 4.21875 | 4 | cadena = input("ingrese dato: ")
print (cadena)
lista =[]
for a in cadena:
if(a not in lista) :
lista.append (a)
print (lista) |
5f5e1483d74e0db139895daae62cc350d13ac1cf | ameya-shukla/Twitter-Bot-using-Tweepy | /tweet_bot.py | 3,180 | 3.5 | 4 | import tweepy
import time
consumer = "----YOUR_KEY----"
consumer_secret = "----YOUR_KEY----"
access_token = "----YOUR_KEY----"
access_token_secret = "----YOUR_KEY----"
auth = tweepy.OAuthHandler(consumer, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth) ... |
2f895c32903b1901b336310574c7ab39290c5ff4 | boyac/pyOptionPricing | /historical_vol.py | 809 | 3.515625 | 4 | from pandas import np
import pandas_datareader.data as web
def historical_volatility(sym, days): # stock symbol, number of days
"Return the annualized stddev of daily log returns of picked stock"
try:
# past number of 'days' close price data, normally between (30, 60)
quotes = web.DataReader(sy... |
6e59a997e220da87a147ec05ee193f9ecd393654 | Vincent-233/Algorithms-Practice-Python | /Chapter04-递归/Code/binary_search_loop.py | 489 | 4.0625 | 4 | def binary_search(data,target):
"""the iterative version of binary search"""
low, high = 0, len(data) - 1
while low <= high:
mid = (low + high) // 2
if data[mid] == target:
return mid
if target > data[mid]:
low = mid + 1
else:
high = mid - ... |
611435cd59852aec4dc3a572eb4d8646444d7b86 | chuck2kill/CoursPython | /chapitre_8/damier.py | 1,482 | 3.71875 | 4 | # programme d'affichage de damier page 86
# import de modules
from tkinter import *
from random import randrange
# ---------- Définition de fonctions ----------
def ligneDeCarre(x, y):
"Fonction permettant d'imprimer une ligne de carrés"
i = 0
while i < 5:
can.create_rectangle(x, y, x + c, y + c,... |
a4d84ad5308ba2089f84dfae5d6c3e3f0bc51cb3 | chuck2kill/CoursPython | /chapitre_5/liste_t3.py | 767 | 3.84375 | 4 | # programme 1 page 45
# ce programme sert à créer une liste à partir de 2 autres listes
# en alternant les termes de chaque liste
# déclaration des variables
t1 = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
t2 = ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet',
'Août', 'Septembre', 'Octobre... |
aea1099923dbe5ef0db93be31c43711ac6f98c01 | chuck2kill/CoursPython | /chapitre_6/nom_sexe.py | 605 | 3.796875 | 4 | ############################################
# programme 2 page 56 #
# permet d'afficher bonjour mr ou mme x #
# en fonction de ce que l'utilisateur #
# a entré #
############################################
# on demande le nom et le sexe de l'utilisateur
n... |
6dd0649d0047f5fb7e2dc8c0db03b42c1e4b5bd8 | chuck2kill/CoursPython | /chapitre_7/fonctions.py | 3,496 | 3.875 | 4 | # import de modules
from math import *
# fonction 1 page 70
# permet d'afficher un nombre n de caractères ca dans une chaine
def ligneCar(n, ca):
i = 0
chaine = ""
while i < n:
chaine = chaine + ca
i = i + 1
return chaine
# fonction 2 page 70
# calcule l'aire d'un cercle de rayon r
def... |
261b5856ac0d957ba1a24454f5c9f71c4e0202bd | chuck2kill/CoursPython | /chapitre_6/pendule.py | 396 | 4 | 4 | # programme 3 page 50
# permet de calculer la période d'un pendule simple
# de longueur donnée
# import du module math
from math import *
# on demande la longueur du pendule
longueur = int(input("Donnez la longueur du pendule en cm: "))
# calcul de la période
periode = (2 * pi) * sqrt(longueur / 2)
# affichage de l... |
b0a2f4ee7a259480c4ea28a8e214cfd8726ab52a | chuck2kill/CoursPython | /chapitre_6/convert_kmh.py | 398 | 3.96875 | 4 | # programme 1 page 50
# sert à convertir des miles par heure en km/h et en mètres par seconde
# on demande la vitesse en mph
mph = int(input("Veuillez indiquer une vitesse en mp/h :"))
# calcul des vitesses
ms = (mph * 1609) / 3600
kmh = mph * 1.609
# affichage des résultats
print("Une vitesse de", mph, "miles par h... |
f527b712da45b8b2e2b65315f7495310ce15157a | chuck2kill/CoursPython | /chapitre_8/serpent.py | 7,763 | 3.703125 | 4 | from tkinter import *
from random import randrange
# === Définition de quelques gestionnaires d'événements : =======================================================
def start_it():
"Démarrage de l'animation"
global flag
if flag == 0:
flag = 1
move()
def stop_it():
"Arrêt ... |
ff559f2393ec5b2e739fd8e5f4af659bbea6c3bb | chuck2kill/CoursPython | /chapitre_9/9_7.py | 526 | 3.546875 | 4 | # A partir de 2 fichiers existants, ce script
# va fabriquer un 3e fichier qui contiendra alternativement
# des éléments du 1er et du 2e
# Si les deux fichiers ne font pas la même taille,
# on remplira le 3e avec le surplus
fichierA = input("Entrez le chemin du premier fichier : ")
fichierB = input("Entrez le c... |
d9056d0586b32f538e004808e8f3ad4986009dbb | chuck2kill/CoursPython | /chapitre_9/9_9.py | 1,876 | 3.625 | 4 | # script permettant de compléter la date de naissance et
# le sexe pour chaque personne créée dans l'exercice précédent
def traduire(ch):
"convertir une ligne du fichier source en liste de données"
dn = "" # chaine temporaire pour extraire les données
tt = [] ... |
65b581b95958dc5235c46657084c643ac942dd54 | Daniel-code666/Programas | /exepciones.py | 1,402 | 3.71875 | 4 |
import msvcrt
MSJ = "Presione una tecla para continuar..."
opt = 1
class DivisionPorCero(Exception):
"""División por cero"""
pass
while opt == 1:
sel = int(input("1. División por cero\n2. Index fuera de la lista\n3. Llave no encontrada\n"
"4. Conversión de string a int\n5. Salir\n")... |
575b6dd24f06300ba6b8dac3e5e1be8319def997 | Daniel-code666/Programas | /ejercicio2.py | 902 | 4.03125 | 4 | numero_magico = 12345679
numero_usuario = int(input())
if numero_usuario < 0 or numero_usuario > 9:
print("Ingrese un número con respecto al rango")
else:
numero_usuario *= 9
numero_magico *= numero_usuario
print("Valor del número mágico {}".format(numero_magico))
# opt = 1
# try:
# numero_usua... |
19f00ca9c4b8a74d198cd97e1187d15eeccbc16a | Daniel-code666/Programas | /diccinarios.py | 1,304 | 3.796875 | 4 | import msvcrt
MSJ = "Presione una tecla para continuar..."
opt = 1
def dicInputVal():
num = int(input("Ingrese número: \n"))
dic = {}
for i in range(1, num + 1):
dic[i] = i**2
return dic
def dicCaracter():
cadena = input("Ingrese cadena de texto:\n")
dicChar = {}
for i i... |
8ee6050fddb052aec08511bc3f0697da65b4bcd6 | Daniel-code666/Programas | /ejerciciosFor.py | 1,331 | 3.75 | 4 | import msvcrt
MSJ = "Presione una tecla para continuar..."
opt = 1
while opt == 1:
print("Ejercicios FOR")
sel = int(input("¿Qué desea hacer?\n1. Suma negativos, promedio positivos\n2. Leap year\n3. Salir\n"))
if sel == 1:
sumNeg, sumPos, cont = 0, 0, 0
for i in range(1, 7):
... |
7bc46f7af93537316ccecb99849eed03cf52054d | Daniel-code666/Programas | /reto5.py | 1,850 | 3.671875 | 4 |
productos = {1:['Mango',7000.0,99],
2:['Limones',3600.0,95],
3:['Peras',2700.0,85],
4:['Arandanos',8300.0,74],
5:['Tomates',8100.0,44],
6:['Fresas',7100.0,99],
7:['Helado',4400.0,98],
8:['Galletas',400.0,99],
9:['Chocolates... |
6ba27e7f7badeda8e158dbd60d872fd280e80cda | subash319/PythonDepth | /Practice25_Generators/Prac25_7_reverse_generator.py | 269 | 4 | 4 | # 7. Write a generator function that accepts a sequence and generates its numbers in reverse order.
def gen_rev(seq):
for rev_index in range(len(seq)-1,-1,-1):
yield seq[rev_index]
x = [1,2,3]
y = 'subash'
for ele in gen_rev(y):
print(ele,end = ' ') |
ea5685aa8343c6c3c3094e29ca337ef2acd9827f | subash319/PythonDepth | /Practice10_Loops/Practice_10_13_check_output.py | 443 | 4.03125 | 4 | # 13. This program is written for creating two lists evens and odds from the list numbers.
# But it does not give the correct output. Can you find what the problem is.
# only Immutable types can have declaration like that, so it forms tuple
evens = []
odds = []
numbers = [10, 2, 3, 41, 5, 7, 8, 9, 62]
for number in n... |
32174de0aa827807607fe35f3a32f7aec1fd7d2a | subash319/PythonDepth | /Practice16_Functions/Prac_16_4_count_vowels_consonants.py | 459 | 4.0625 | 4 | # 4. Write a function that takes in a string and returns number of vowels and consonants in that string.
def count_vowel_consonants(str):
vowel_count,consonant_count = 0,0
vowels = ['a','e','i','o','u']
for ch in str:
if ch.isalpha():
if ch.lower() in vowels:
vowel_count... |
19f2142d863f2105fd453b35dd9832bff8ffb9e5 | subash319/PythonDepth | /Practice16_Functions/Prac_16_10_count_even_odd.py | 374 | 4.28125 | 4 | # 10. Write a function that takes in a list of integers and returns the number of even and odd numbers from that list.
def count_even_odd(list_count):
even_count,odd_count = 0,0
for num in list_count:
if num%2 == 0:
even_count += 1
else:
odd_count += 1
return even_co... |
d7d085b8151e1f95914d9c81a665e2b2b2640e8c | subash319/PythonDepth | /Practice17_Functions_2/Prac_17_8_Is_ther_any_error.py | 594 | 3.78125 | 4 | # 8. Is there any error in the following code.
def subtract(a,b):
print(a-b)
def add(a,b):
print(a+b)
def multiply(a,b):
print(a*b)
def divide(a,b):
print(a//b)
d = {'a':add, 's':subtract, 'm':multiply, 'd':divide}
choice =''
while choice != 'q':
print('a - Add')
print('s - Subtract')
... |
cb5f2cbf5e3051288244c8a57e188804cb2004f2 | subash319/PythonDepth | /Practice8_sets/Prac_8_5_Vowel_Consonants.py | 384 | 4.03125 | 4 | # 5. Enter a string and create 2 sets v and c, where v is a set of vowels present in the
# string and c is a set of consonants present in the string.
text = input("Enter your string please:")
vowel = set('aeiou')
string_c = 'BCDFGHJKLMNPQRSTVWXYZ'
consonats = set(string_c.lower())
print(consonats)
v = set(text)& vowe... |
42e99ec5b61f9ea5debb7e192cd83ff4f47cc7cc | subash319/PythonDepth | /Practice10_Loops/Practice10_1_sum_n_numbers.py | 635 | 4.375 | 4 | # 1. Write code to find sum of first n natural numbers using a
#
# (a) while loop
#
# (b) for loop
#
# (c) without any loop
# a while loop
n = int(input("Enter the 'n' value to find sum of n natural numbers:"))
initial_n = n
sum = 0
while n:
sum += n
n -= 1
print(f"sum of {initial_n} natural numbers:{sum}")
... |
95a335b1ee24194a366d0e8bc596e627f6b4d952 | subash319/PythonDepth | /Practice17_Functions_2/Prac_17_7_what_is_output.py | 139 | 4.15625 | 4 | # 7. What will be the output of this code.
#
M = [ [1,6,2,3],
[7,5,6,9],
[8,9,3,2] ]
T = [list(t) for t in zip(*M)]
print(T)
|
7fd38a5b799709c07579217fa5334f903f9e377e | subash319/PythonDepth | /Practice12_Loops/Prac_12_2_dice_rolling.py | 280 | 3.65625 | 4 | # 2. Write a program that simulates dice rolling. Use randint from random module.
import random
done = True
while True:
roll = random.randint(1,6)
print(roll)
done = bool(input("Do you want to one more role, enter-continue, anything-quit"))
if done:
break |
1d1d098504c2dc9c0aa12f328fa53e9957768183 | subash319/PythonDepth | /Practice12_Loops/Prac_12_1_list_prime.py | 202 | 3.875 | 4 | # 1. Write a program that creates a list of all prime numbers from 100 to 300.
for i in range(100, 300):
for j in range(2, i//2):
if i % j == 0:
break
else:
print(i) |
d09932cb06de963bd0704dedd1d58121c1961c82 | subash319/PythonDepth | /Practice13_LoopingTechniques/Prac_13_12_output_code.py | 211 | 3.609375 | 4 | # 12. What will be the output of this program -
#
L = [1,2,-3,4,-5,-6,8]
# [1,2,4,-6,8]
# 0 1, 1 2, 2 -3, 3 -5, 4 8
i = 0
while i < len(L):
print(i, L[i])
if L[i] < 0:
L.remove(L[i])
i+=1
print(L) |
4041cbcc4d5b7e0cb863c66a577d8ae52bb6c554 | subash319/PythonDepth | /Practice18_Files/Prac18_2_print_only_5lines.py | 230 | 3.921875 | 4 | # 2. Write a program to display only the first 5 lines of a file.
with open('hash.txt', 'r') as f:
count = 0
for line in f:
count += 1
if count > 5:
break
else:
print(line)
|
4410eadec793e5cfb189305a350f91052cc822e6 | subash319/PythonDepth | /Practice14_List_Comprhensions/Prac_14_6_cubes_all_odd.py | 292 | 4.53125 | 5 | # 6. This list comprehension creates a list of cubes of all odd numbers.
#
# cubes = [ n**3 for n in range(5,21) if n%2!=0]
# Can you write it without the if clause.
cubes = [n**3 for n in range(5, 21, 2)]
cubes_2 = [ n**3 for n in range(5,21) if n%2!=0]
print(cubes)
print(cubes_2) |
3687ac68a5e5a98d1972ae671b90d598f2055e84 | subash319/PythonDepth | /Practice17_Functions_2/Prac_17_6_kwargs.py | 493 | 4.125 | 4 | # def display(L, start='', end=''):
# for i in L:
# if i.startswith(start) and i.endswith(end):
# print(i, end=' ')
#
# display(dir(str), 'is', 'r')
# In the function definition of the function display(),
# make changes such that the user is forced to send keyword arguments for the last two parameters.... |
2b5d55b95c8e9387a731ca4b780d64511d243ae8 | subash319/PythonDepth | /Practice14_List_Comprhensions/Prac_14_13_replace_this_code.py | 274 | 3.6875 | 4 | # 13. Write a list comprehension that can replace this code.
# pairs = []
# for n1 in range(4):
# for n2 in range(4):
# if n1!=n2:
# pairs.append((n1,n2))
pairs = []
pairs = [(n1,n2) for n2 in range(4) for n1 in range(4) if n1!=n2]
print(pairs) |
9dc40778cac7f7c94c1b72984d786529f55b3d9c | subash319/PythonDepth | /Practice23_Inheritance/Prac23_1_magicmethod_str.py | 2,064 | 3.921875 | 4 | # 1. Create a class named Course that has instance variables title, instructor, price, lectures, users(list type),
# ratings, avg_rating. Implement the methods __str__, new_user_enrolled, received_a_rating and show_details.
# From the above class, inherit two classes VideoCourse and PdfCourse. The class VideoCourse has... |
8a8e5cc2188d84672aa8f3502c459f5a622e956b | subash319/PythonDepth | /Practice11_Loops/Prac_11_6_Insert_list.py | 469 | 4.3125 | 4 | # L1 = ['China', 'Brazil', 'India', 'Iran', 'Iraq', 'Russia']
# L2 = ['Italy', 'Japan', 'China', 'Russia', 'Nepal', 'France']
# Write a program that inserts all common items of these 2 lists into a third list L3.
L1 = ['China', 'Brazil', 'India', 'Iran', 'Iraq', 'Russia']
L2 = ['Italy', 'Japan', 'China', 'Russia',... |
ac74373acf3d892d37ebfedbbf88110f2b203cac | subash319/PythonDepth | /Practice21_OOP_StaticMethods_ClassMethods/Prac21_5_allowed_domains.py | 961 | 3.9375 | 4 | # 5. In the following Employee class, add a class variable named allowed_domains.
#
# allowed_domains = {'yahoo.com', 'gmail.com', 'outlook.com'}
# Whenever an email is assigned, if the domain named is not in allowed_domains, raise a RuntimeError.
class Employee:
allowed_domains = {'yahoo.com', 'gmail.com', 'outl... |
d5d291ae847a623e6094ebd318240d2fcc5f6b9d | subash319/PythonDepth | /Practice15_Dict_Comprehensions/Prac_15_5_emailid.py | 852 | 3.828125 | 4 | # From this dictionary create another dictionary that contains only those key value pairs where
# email id is on the website xyz.com.
d = {'raj@xyz.com' : {'course':'Algorithms', 'city':'London'},
'dev@abc.com' : {'course':'Painting', 'city':'Delhi'},
'sam@pqr.com' : {'course':'Design Patterns', '... |
1f94ce540590d5d55f993b384830edf78b355425 | subash319/PythonDepth | /Practice18_Files/Prac18_3_print_last_5lines.py | 220 | 4.0625 | 4 | # 3. Write a program to display only the last 5 lines of a file.
with open('hash.txt', 'r') as f:
count = 0
for line in reversed(f.readlines()):
count += 1
if count <= 5:
print(line)
|
b5e96ebf56a4366a1d6d8c490ef6d9bdbc870ccd | subash319/PythonDepth | /Practice14_List_Comprhensions/Prac14_2_construct_list.py | 199 | 3.734375 | 4 | # 2. Use a list comprehension to construct this list
#
# [ '5x’, ’7x’, '9x', '11x', '13x', '15x', '17x' ]
list_comp = [ str(num)+'x' for num in range(5, 17) if num%2 != 0]
print(list_comp) |
a75af2a8d7054d1f3860415df557018919520c0e | subash319/PythonDepth | /Practice20_OOP/Prac20_5_property_price.py | 1,348 | 3.8125 | 4 | # 5. In the Book class, create a property named price
# such that the price of a book cannot be less than 50 or more than 1000.
class Book:
def __init__(self, isbn, title, author, publisher, pages, price, copies):
self.isbn = isbn
self.title = title
self.author = author
self.publis... |
11506ebc9da92d469b83fbe2f261e4a4ce412716 | subash319/PythonDepth | /Practice13_LoopingTechniques/Prac_13_15_zip.py | 1,721 | 4.21875 | 4 | # 15.Write a program that displays the following output from the above data. Use zip in for loop to iterate over the
# lists.
#
#
#
# John
#
# --------------------------------------------------
#
# Physics 100 40 90
#
# Chemistry 80 25 78
#
# Maths 100 40 87
#
# Biology 75 20 67
#
# Tot... |
8fb26e5709a7038ed5c0c9d5cb7937edb59b9569 | subash319/PythonDepth | /Practice14_List_Comprhensions/Prac_14_10_matrices.py | 333 | 3.890625 | 4 | # 10. Write a list comprehension that returns the sum of these two matrices M1 and M2.
M1 = [[1, 4, 8, 3],
[2, 5, 6, 3],
[7, 9, 5, 8]]
M2 = [[3, 5, 2, 3],
[5, 2, 7, 9],
[2, 8, 1, 8]]
sum_two_matrice = [[EleM1 + EleM2 for EleM1, EleM2 in zip(row1, row2)] for row1,row2 in zip(M1,M2)]
print(sum... |
01c2d5fb6c93379691a53709516cc0a767884d18 | kittell/sql-csv-asap | /parse.py | 29,639 | 3.6875 | 4 | from utils import *
from index import *
import string
def get_sql_terms():
# List of SQL terms handled by program
return ['SELECT', 'FROM', 'WHERE', 'ORDER BY']
def get_sql_terms_nospace():
# Replace the space with a dash. This is for parsing functions that are splitting
# on space to not ge... |
ceeb215f431ed30bc0b9f4b6a217f68e26042dc5 | srimaniteja19/python_projects | /band_name_generator_project-one/index.py | 218 | 3.984375 | 4 | print("Welcome to the Band name generator\n")
city_name = input("What is Your City Name?\n")
pet_name = input("What is your pet name\n")
band_name = f'Your band name would be {city_name} {pet_name}'
print(band_name) |
a84debb677dd8a2211a28d96193028f96cc762b8 | CouchNut/Python3 | /function.py | 3,546 | 4.3125 | 4 | #!/usr/bin/python3
def hello():
print("Hello world!")
hello()
# 计算面积函数
def area(width, height):
return width * height
def print_welcome(name):
print("Welcome", name)
print_welcome("Copper")
w = 4
h = 5
print('Width = ', w, "Height = ", h, "area = ", area(w,h))
# 定义函数
def printme(str):
"打印任何传入的字符串"
print(s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.