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 |
|---|---|---|---|---|---|---|
75d6a84146b332ffc7de74b8b5b7aa82719304a9 | juansevargasc/Intermediate-Py | /list_comprehensions.py | 421 | 3.5 | 4 | def run(): # cmd + k + c Comments a block!
# squares = []
# for i in range(1, 101):
# if i % 3 != 0:
# squares.append(i ** 2)
squares = [ i ** 2 for i in range(1, 101) if i % 3 !=0 ]
print(squares)
def reto():
multiples = [ i for i in range(1, 100000) if (i % 4 == 0) and (... |
3b2206df9f7dbe6c238fd1f039d492692a04749b | Hemangi3598/chap-3_p6 | /p6.py | 227 | 3.859375 | 4 | # wapp to find sum of first "n" +ve integers
num = int(input(" enter +ve integer "))
if num < 0:
print("invalid number")
else:
sum = 0
i = 1
while i <= num:
sum = sum + i
i = i + 1
print(" sum = ", sum)
|
65293fcbfb356d2f045eff563083e2b751e61326 | martinkalanda/code-avengers-stuff | /wage calculaor.py | 297 | 4.40625 | 4 | #Create variables
hourly_rate = int(input("what is your hourly rate"))
hours_worked = int(input("how many hours have you worked per week"))
#Calculate wages based on hourly_rate and hours_worked
wages = hourly_rate * hours_worked
print("your wages are ${} per week" .format(wages))
|
26c5dd7fe1ab43d5f6d698a3849fde679c42381a | tcpowers15/CryptoToolbox | /CaeserCipher/Brutus.py | 583 | 3.5625 | 4 | """
This script takes in an encrypted Caeser Cipher and brute forces it
"""
import sys
def ceaser(text, s):
result = ""
for i in range (len(text)):
char = text[i]
if(char.isupper()):
result += chr((ord(char) + s - 65) % 26 + 65)
else:
result += chr((or... |
74e16826f19feaed8cbf95269d3707b07b97d1e5 | Saransh-Khasria/dsad | /DSAD/main.py | 1,963 | 3.78125 | 4 | from Graph import Graph
from Stack import MyStack
# Create Stack => stack = MyStack()
# Functions of Stack => push(int), pop(), top(), is_empty()
def dfs_traversal_helper(g, source, visited):
result = ""
# Stack Implemented since we can't import stack.
stack = MyStack()
stack.push(source)... |
40edbb30bd2c0ad06cf1343cc5c42e7a1246ef23 | AaronGuti/BF-Password-Cracker | /passCrack.py | 10,540 | 4.125 | 4 | import itertools
import math
import os
import time
import platform
# helps separate text visually
from termcolor import colored
# TODO: Shorten character check with regex
def passCrack(password):
string_type = ''
# password = input("Please enter your password: ")
wait(1)
customize = input(
"W... |
e94e6e896df7d50302503db19ceb80714610cc26 | SEPA-17/Web-UI | /webapp/helper.py | 474 | 3.5625 | 4 | from datetime import datetime
def parse_date_to_iso(date_str):
date_str = date_str.replace("/", "-")
datetime_format = (
"%d-%m-%Y %H:%i:%s", "%d-%m-%Y %H:%M:%S", "%Y-%m-%d %H:%M:%S", "%d-%m-%Y", "%Y-%m-%dT%H:%M:%S.%fZ")
for item in datetime_format:
try:
dt = datetime.strptime(... |
5099a6a387436dff52629a0f00f4f1e7291bbe1f | sanil2008/Python-Programs | /Tq1.py | 183 | 4.1875 | 4 | number = int(input())
number = number % 10
if(number % 3 == 0):
print(number)
print('Yes,It is Divisible')
else:
print(number)
print('No,It is not Divisible')
|
3ff3ab58bc2f58e685be26d4e5c1f05bf28efc8a | khud/typedparse | /examples/head.py | 383 | 3.75 | 4 | import typedparse
import typing as ty
def main(file: str, number: ty.Optional[int] = 6):
"""Display first lines of a file.
Args:
file: file to display
number: number of lines to display
"""
with open(file, "r") as f:
for i in range(0, number):
print(f.readline(), e... |
53e4e43abeb67a117652b4004c8337518e572ba3 | julimari125/ju_private | /DAY4/connect_sqlite.py | 682 | 3.78125 | 4 | import sqlite3
import sys
# db_name = 'python_training.db'
# connection = sqlite3.connect(db_name)
# cursor = connection.cursor()
# cursor.execute('INSERT INTO books (name, kind) VALUES ("python入門","プログラミング")')
# connection.commit()
# connection.close()
args = sys.argv
db_name = 'python_training.db'
connection = sqlite... |
dea6e6e882c66bb0a22b0b121fde3bf0b7338c05 | Obed-Ababio/event_planner | /test.py | 531 | 3.765625 | 4 | import datetime
def is_conflict(s1, e1, s2, e2):
"takes start and end times of two events and determines if they overlap"
if s1 == s2 or e1 == e2:
return True
return (s1 < e2) and (e1 > s2)
event1_st = int(input("event 1 start time: ").replace(":", ""))
event1_et = int(input("event 1 end time:... |
be9595c55921393c60295b3c23b4921f33dfeb58 | Python-Club-UO/Fun-Projects | /VirtualDiceChallenge_DéfiDésVirtuels/DésVirtuelsExempleAvancéfr.py | 2,466 | 3.5 | 4 | """Il s'agit d'un exemple plus complexe de dé virtuel qui utilise des matrices de 1s (pixels blancs) et de -1s (pixels noirs) pour
représenter le résultat du lancer de dés. Numpy est utilisé pour créer des matrices, matplotlib est utilisé pour le tracé, et random
est utilisé pour générer des nombres au hasard. Pouvez... |
c2c1f672ee90fdf4cbbda934e6407c8cd0db9322 | jake08bennett/APCSP_Final | /Main.py | 5,162 | 3.875 | 4 | from geopy.geocoders import Nominatim
from geopy.distance import vincenty
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
def flush():
sys.stdout.flush()
system_running = True
while system_running == True:
print '\n---------Welcome to the 7 Wonders of the World distance calculator--------- \n \nWe calc... |
b117d139a49b78fae78f07b10517148c14f065ef | lu15fer/Luis_Avila_1358 | /Array3D.py | 1,356 | 3.5 | 4 | #Array 3D
'''
get_num_rows()
get_num_cols()
get_num_depth()
set_otem(r,c,d,value)
get_item(r,c,d)
clearing(value)
to_string()
'''
class Array3D:
def __init__(self,rows,cols,depth):
self.__data=[]
self.__rows=rows
self.__cols=cols
self.__depth=depth
self.__data=[[[None for... |
835e56e45e0b257864255b6bac0df06420f5372a | nepalisian/practice | /python/append.py | 204 | 3.796875 | 4 | #!/usr/bin/python
a = [1,2,3,4,5]
a.append(0)
length = len(a)
b = [0] * length
index = 0 - length
while (index < 0):
b[index+1] = a[index]
index = index + 1
print("a: %s", a)
print("b: %s", b)
|
b865bacdf21454a40241bfa4f38862318b320237 | AnasJS/Information-Security-Systems--Homework | /hashandsigniture/Server.py | 1,147 | 3.515625 | 4 | from ClientThread import *
from socket import *
class Server:
def __init__(self,host ,port):
self.host = host
self.port = port
#socket.AF_INET, socket.SOCK_STREAM
self.socket = socket()
self.socket.bind((self.host , self.port))
self.socket.listen(10)
... |
1e66ff1ebc0ca6fa4148382269ff0e1725dec07a | franAlba98/Python-Practices | /While && for loop.py | 538 | 3.9375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
while False:
print('hello')
# In[2]:
counter = 0
while counter < 12:
print(counter)
counter = counter + 1
print('hello')
# In[3]:
for i in range(5):
print('hello')
# In[4]:
list(range(5))
# In[6]:
range(5) #Creates a set of five numb... |
d2eb85b3b35d1554b68874acf04db123bceaa6e8 | XiangChenBen/Python-code-when-I-studied-on-MOOC | /身体质量指数BMI值.py | 715 | 3.90625 | 4 | #BMI in domestic and nationaL
height, weight = eval(input("请输入身高(m)体重(kg)用逗号隔开):"))
BMI = weight / pow(height,2)
print("BMI is: {:.2f}".format(BMI))
domestic, internationaL= "",""
if BMI < 18.5:
domestic, international = "little slim", "little slim"
elif BMI < 24:
domestic, international = "normal","nor... |
5acc1e89c0878f1e056b783b566005ec91b284da | XiangChenBen/Python-code-when-I-studied-on-MOOC | /power.py | 204 | 3.546875 | 4 | class powerpo()
def Po(a ,b, c =1):
if b == 0 :
return c
else :
c = Po(a,b-1)*a
return c
x = eval(input("base"))
y = eval(input("power"))
print("{}".format(Po(x,y))) |
c23cbde61ae29961d60473a4264a2ecc60eb8d43 | XiangChenBen/Python-code-when-I-studied-on-MOOC | /100以内素数之和.py | 1,279 | 3.890625 | 4 | '''描述
求100以内所有素数之和并输出。
素数指从大于1,且仅能被1和自己整除的整数。
提示:可以逐一判断100以内每个数是否为素数,然后求和。'''
#自己想的循环模式找prime number
'''x = 0
for i in ra... |
d75f6cb936d96c5d1bbb4dcb84a1afb911fa5766 | Surmalumi/homework5 | /work3.py | 602 | 3.5 | 4 | # оздать текстовый файл (не программно), построчно записать фамилии сотрудников и величину их окладов.
with open('work3.txt', 'r', encoding='utf-8') as my_file:
salary = []
name = []
my_list = my_file.read().split('\n')
for i in my_list:
i = i.split()
if int(i[1]) < 20000:
na... |
697e873b9dce0b54a9340b289dacbdf3e0ff3d0b | seodea/Python-basic | /04.control List, Tuple, Dictionary/06.Dictionary.py | 748 | 3.78125 | 4 | # If you want to control key and value in one value, i recommend the dictionary.
# It use the { and } when you want to make a list.
# Dictionary should have a key and value such as language dictionary.
dic = {}
dic['Python'] = 'www.python.org'
dic['Microsoft'] = 'www.microsoft.com'
dic['Apple'] = 'www.apple.com... |
362d0af27c3fb06e7746e4fa532ee76d93ad4bdf | seodea/Python-basic | /04.control List, Tuple, Dictionary/01.List.py | 902 | 4.03125 | 4 | # If you want to control many date in one value, i recommend the list.
# It use the [ and ] when you want to make a list.
list = ['dom', 'david', 'jack']
list
# You can control the date easier than each value of date.
# For example, if you want to contrl the 3 data, you use the 3 value.
# It is very hard and ... |
750cc69fb13b70c8a0aac5fce6cb2be50adf032b | Llama-Security/password_generator | /passgen.py | 1,437 | 3.828125 | 4 | import random
import sys
pass_dict = ['abcdefghijklmnopqrstuvwxyz','ABCDEFGHIJKLMNOPQRSTUVWXYZ','1234567890',"~!@#$%^&*()_-+={}[]:;<>,.?"]
#pass_len = int(input("Enter the length of the password: "))
#pass_data = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890[];',./!@#$%^&*()_+:<>?"
def getPassLen(... |
ac8f30517c18049d57b9c75d79fbe610bced079f | andronovd/ec441 | /labs/lab_4/mail_client.py | 1,971 | 3.609375 | 4 | from socket import *;
import sys;
#message to be sent
msg = "Subject: Good Luck\n Good luck on your exam!\n".encode();
endmsg = ".\r\n".encode();
#Choose a BU Mail server and call it mailserver
mailserver = "relay.bu.edu";
#Create a socket called clientSocket and establish a TCP connection with mailserver
clientSoc... |
0b0e1d519d2b3865c80eadbf88acd099c4eddc26 | NishadKumar/interview-prep | /leetcode/1004_max_consecutive_ones_3/test_max_consecutive_ones_3.py | 435 | 3.515625 | 4 | import unittest
import max_consecutive_ones_3
#please feel free to contribute more tests
class TestMaxConsecutiveOnes(unittest.TestCase):
def test_longest_ones(self):
self.assertEqual(max_consecutive_ones_3.longest_ones([1,1,1,0,0,0,1,1,1,1,0], 2), 6)
self.assertEqual(max_consecutive_ones... |
d1c8e6df0c2a44e543b879dcfcee89a2f77557ba | NishadKumar/interview-prep | /dailybyte/strings/longest_substring_between_characters.py | 1,874 | 4.21875 | 4 | # Given a string, s, return the length of the longest substring between two characters that are equal.
# Note: s will only contain lowercase alphabetical characters.
# Ex: Given the following string s
# s = "bbccb", return 3 ("bcc" is length 3).
# Ex: Given the following string s
# s = "abb", return 0.
# Approach:
#... |
f72e0d615cff8f4a21c61f0482fc1c7b5f886011 | NishadKumar/interview-prep | /leetcode/767_reorganize_string/reorganize_string.py | 1,883 | 3.765625 | 4 | # Given a string s, check if the letters can be rearranged so that two characters that are adjacent to each other are not the same.
# If possible, output any possible result. If not possible, return the empty string.
# Example 1:
# Input: s = "aab"
# Output: "aba"
# Example 2:
# Input: s = "aaab"
# Output: ""
# No... |
649fb09854bb5c385e3eaff27302436741f09e4f | NishadKumar/interview-prep | /leetcode/1197_minimum_knight_moves/minimum_knight_moves.py | 2,147 | 4.125 | 4 | # In an infinite chess board with coordinates from -infinity to +infinity, you have a knight at square [0, 0].
# A knight has 8 possible moves it can make. Each move is two squares in a cardinal direction, then one square in an orthogonal direction.
# Return the minimum number of steps needed to move the knight to the ... |
15c8db79e04b7a8dff248fbf80e8f6820d5510a3 | eazygoin67/DailyProgrammerChallanges | /MagicSquares/main.py | 1,495 | 3.78125 | 4 | import math
##### VALIDATION #####
def validateSquare( magicSquare ):
# Get Dimensions of the Square
size = int(math.sqrt( len(magicSquare) ))
if ( size < 3 ):
return False
# Get the Magic Sum Constant
magicConstant = ( size * (size**2 + 1) ) / 2
# Validate
for x in range( 0, s... |
8cf3e9b82cd34fcd4c65339fdafb439476c7c64d | Masrt200/WoC2k19 | /enc/substitution_enc.py | 996 | 4.125 | 4 | #substitution cipher encryptor...
def substitute(plaintext):
plaintext=plaintext.upper()
_alphabet_='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
_alphabet_new_=''
keyword=input('Enter Keyword:')
keyword=(keyword.strip()).upper()
key_list=[]
for x in keyword:
ct=1
for y in key_l... |
a802c701a498b265ddf3c306154ff6ee27b3ba56 | Masrt200/WoC2k19 | /alg/Ext_Euclid.py | 1,377 | 3.984375 | 4 | #extended Euclid
import binascii
import math
def Euclid_RSA(a,b):
cn=0
if A>B: #reversing vals in case e>totient
A=A+B
B=A-2*B
A=(A-B)//2
B=A+B
cn+=1
c=A #calling vals of A and B for calcing
d=B
uc=1 #these vars are used for mainta... |
61909a56670814356ce9df4825184c472fe9b2c7 | jayakrishna35/Coding | /seive.py | 267 | 3.578125 | 4 | n=int(input())
s=[i for i in range(n+1)]
print(s)
i=2
while(i*i<=n):
if s[i]==i:
for j in range(i*i,n+1,i):
s[j]=0
i+=1
s[0]=0
s[1]=0
print(s)
if(s[n]==1):
print("prime")
else:
print("not prime")
|
39658a0a2ddd1e51da21b520454624f62a2920d2 | jayakrishna35/Coding | /input.py | 85 | 3.65625 | 4 | a=input("Enter a number:")
b=input("Enter another number: ")
print(int(a)+int(b))
|
603ea0144b44577f6b533f87d8ce8525258b0cf2 | jayakrishna35/Coding | /sp.py | 155 | 3.828125 | 4 | product=0
def solu(num1,num2):
product=num1*num2
if product <=1000:
return product
else:
return(num1+num2)
print(solu(50,30))
|
32d4fe9f80bd1fa4bdedcf8f82c653079bb04a67 | jayakrishna35/Coding | /translate.py | 290 | 3.828125 | 4 | def trans(pr):
trans=""
for let in pr:
if let.lower() in "aeiou":
if let.isupper():
trans=trans+"G"
else:
trans=trans+"g"
else:
trans=trans+let
return trans
print(trans(input("Enter text: ")))
|
1c6ef7dbaf66a1ef8ab8e9afcc790b46e3895f1b | jayakrishna35/Coding | /blast.py | 58 | 3.53125 | 4 | n=5
while n>0:
print(n)
n=n-1
print("blast off")
|
68a2c1e95e8da342e46e79264b9c687c46225a34 | jayakrishna35/Coding | /fibanocii_series.py | 144 | 3.671875 | 4 | n1=0
n2=1
numb=int(input())
print(n1,n2,end=" ")
for i in range(2,numb):
n3=n1+n2
print(n3,end=" ")
n1,n2=n2,n3
|
a37a06678c4fa498526314e0647c8191fb241c87 | aminul788/NSL-RAShip-Programm | /python-basic/Problem-Solving/Sum_and_Prod.py | 432 | 3.5625 | 4 | '''
Date : 11/11/2020
Day : Wednessday
Author : Md. Aminul Islam
Topic : Problem Solving
Problem : Sum and Prod
Problem link : https://www.hackerrank.com/challenges/np-sum-and-prod/problem
'''
import numpy as np
n, m = map(int, input().split())
arr = np.arr... |
ee133643d990c3377af94da9c4c679cfb78b3f5f | aminul788/NSL-RAShip-Programm | /python-basic/Problem-Solving/Concatenate.py | 478 | 3.6875 | 4 | '''
Date : 05/11/2020
Day : Thursday
Author : Md. Aminul Islam
Topic : Problem Solving
Problem : Concatenate
Problem link : https://www.hackerrank.com/challenges/np-concatenate/problem
'''
import numpy as np
N, M, P = map(int, input().split())
arr1 = np.arra... |
da88465733f5a850b860c750f57ff0af3358f53a | aminul788/NSL-RAShip-Programm | /python-basic/Problem-Solving/Dot_and_Cross.py | 424 | 3.65625 | 4 | '''
Date : 16/11/2020
Day : Monday
Author : Md. Aminul Islam
Topic : Problem Solving
Problem : Dot and Cross
Problem link : https://www.hackerrank.com/challenges/np-dot-and-cross/problem
'''
import numpy as np
n = int(input())
a = np.array([input().split() ... |
a1410de09e58c28428ff298f5d74e334e0c355ee | aminul788/NSL-RAShip-Programm | /python-basic/Problem-Solving/stringSplitandJoin.py | 444 | 3.78125 | 4 | '''
Date : 02/11/2020
Day : Monday
Author : Md. Aminul Islam
Topic : Problem Solving
Problem : String Split and Join
Problem link : https://www.hackerrank.com/challenges/python-string-split-and-join/problem
'''
def split_and_join(line):
line = line.split(... |
e7bcb27ae56cdb490a2b00001c4b892c677ec639 | aminul788/NSL-RAShip-Programm | /python-basic/Problem-Solving/triangleQuest.py | 628 | 3.84375 | 4 | '''
Date : 16/10/2020
Day : Friday
Author : Md. Aminul Islam
Topic : Problem Solving
Problem : Triangle Quest
Problem link : https://www.hackerrank.com/challenges/python-quest-1/problem
'''
# ## using mathematical logic
for i in range(1,int(input())):
prin... |
dc52fc66adee3ab27813c4f37e4879f3f422a67a | aminul788/NSL-RAShip-Programm | /python-basic/Problem-Solving/Collections_namedtuple.py | 581 | 3.796875 | 4 | '''
Date : 02/11/2020
Day : Monday
Author : Md. Aminul Islam
Topic : Problem Solving
Problem : Collections.namedtuple()
Problem link : https://www.hackerrank.com/challenges/py-collections-namedtuple/problem
'''
from collections import namedtuple
N = int(inpu... |
31e12c910333999cf5380448a4077acca99e3060 | aminul788/NSL-RAShip-Programm | /python-basic/Problem-Solving/TheMinionGame.py | 1,560 | 3.828125 | 4 | '''
Date : 02/11/2020
Day : Monday
Author : Md. Aminul Islam
Topic : Problem Solving
Problem : The Minion Game
Problem link : https://www.hackerrank.com/challenges/the-minion-game/problem
'''
def minion_game(string):
### using mathemetical equation: n+(n-1)... |
fc9ed25cd6a20860012468865bb5f5d3e677b270 | aminul788/NSL-RAShip-Programm | /python-basic/Problem-Solving/Transpose_and_Flatten.py | 574 | 3.71875 | 4 | '''
Date : 05/11/2020
Day : Thursday
Author : Md. Aminul Islam
Topic : Problem Solving
Problem : Transpose and Flatten
Problem link : https://www.hackerrank.com/challenges/np-transpose-and-flatten/problemTranspose and Flatten
'''
import numpy as np
N, M = ma... |
b2ab628a896565edb6cac8ee7e7831d07866c489 | rick-62/AdventOfCode2017 | /day19/day19.py | 2,704 | 3.609375 | 4 | # day19
import sys
class Puzzle():
directions = {'d':1, 'u':-1, 'r':1, 'l':-1}
def __init__(self, test_flag=False):
if test_flag:
self.map = self.load_into_memory("test.txt")
else:
self.map = self.load_into_memory("input.txt")
self.solution = []
self.st... |
48b2374abb1a091a533c486b391fe308742b809b | rick-62/AdventOfCode2017 | /day08/day08.py | 2,129 | 3.6875 | 4 | # day08
import operator as O
class Puzzle():
arith = {'inc': O.add, 'dec': O.sub}
comp = {'==': O.eq,
'<': O.lt,
'>': O.gt,
'!=': O.ne,
'>=': O.ge,
'<=': O.le}
def __init__(self, test_flag=False):
if test_flag:
se... |
06da4ccf5a86ffb151f986ec178772d8b4ac5cea | oscstr-9/Datorspels-AI---S0006D | /Lab3/Map.py | 1,294 | 3.71875 | 4 | import StatParser
import random
map = 0
r = ((1, 1), (1, 0), (0, 1), (-1, 1), (1, -1), (-1, 0), (0, -1), (-1, -1))
# Reads map from map file and make a 2D array where every index is a square on the map.
def makeMap():
global map
f = open("Maps/Map.txt", "r")
# parse map file
mapLines = f.readlines()
... |
128a837f79d06af4e11fe7f3fb0e3100784c6822 | lzieniew/zero_sum_game_algorithm | /src/python_gui/gui.py | 2,725 | 3.609375 | 4 | import tkinter as tk
board = '''
W - white pawn
B - black pawn
o - empty field
B-----o-----B
| | |
| o---W---o |
| | | | |
| | B-B-W | |
| | | | | |
W-B o W-W-B
| | | | | |
| | W-B-B | |
| | | | |
| o---W---o |
| | |
W-----B-----W
'''
WIN = None
# 0, 1, or 2
CURRENT_PHASE = 0
FIELDS_P... |
2661b53d85e89702599f42bfea07747cbb8ab786 | docsteveharris/paper-spotepi | /share/ccode/python/mypy.py | 1,517 | 3.546875 | 4 | """
This is a docstring.
It marks the beginning of this module file.
Module files are libraries of python code
Don't forget to import other modules that will be needed at the beginning
"""
import sys
import re
def printsyspath():
print 'Your sys.path is ...\n'
print sys.path
def printhello(name):
print "... |
cc5948fdb1642f3d1445e32ec5c195431a4f7665 | hajuxp/python_project | /180406.py | 2,179 | 3.703125 | 4 | """
산술연산과 데이터정렬
pandas에서 중요한 기능은 색인이 다른 객체간의 연술이다.
객체를 더할 때 짝이 맞지 않는 색인이 있다면 두 색인이 통합된다"""
from pandas import Series, DataFrame
import pandas as pd
import numpy as np
s1 = Series([7.3, -2.5, 3.4, 1.5], index=['a','c','d','e'])
s2 = Series([-2.1,3.6,-1.5,4,3.1],index=['a','c','e','f','g'])
print(s1, s2)
print(s1+s2) ... |
68a1e0eb3569826f443b4f2866aa200e247ed898 | chu4/python.exercism | /rna-transcription/rna_transcription.py | 252 | 3.5625 | 4 | def to_rna(text):
new=''
for char in text:
if char == 'G':
new+='C'
elif char =='C':
new+='G'
elif char =='T':
new +='A'
elif char =='A':
new +='U'
return (new) |
a8c403b19b235965af4ad5082b81d6c229dcc79c | littleredtootle/PythonForBeginners | /string_concatenation.py | 230 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Feb 4 20:09:47 2018
@author: Michelle Jump
"""
def string_concatenation(string1, string2):
string = string1 + " " + string2
return string
print(string_concatenation("John", "Smith"))
|
8488da7cb5989c2785a81faf81d9ac7a849c5b0d | Marcus-Mosley/ICS3U-Unit4-02-Python | /product.py | 1,153 | 4.65625 | 5 | #!/usr/bin/env python3
# Created by Marcus A. Mosley
# Created on October 2020
# This program finds the product of all natural numbers preceding the
# number inputted by the user (a.k.a. Factorial)
def main():
# This function finds the product of all natural numbers preceding the
# number inputted by... |
b7da781055fc594e7cc8f53fb75fcb451de717b1 | tien-149/A1_week7_python | /RPSGame.py | 3,396 | 4.125 | 4 | from random import randint
#available weapons => Store this is an array
choices = ["Rock","Paper","Scissors"]
continute = ["Q"]
player = False
playerLives = 1
computerLives = 1
# Make the computer pick one item at random
computer = choices[randint(0, 2)]
#Show the computer's choice in the terminal window
print("Compu... |
9942143754b445b42bb9915c71cbd529ee701f65 | ChaseBosman/chatbot | /modules/horoscope.py | 1,008 | 3.5625 | 4 | import urllib
from urllib.request import urlopen
from bs4 import BeautifulSoup as soup
def get_zodiac_number(sign):
sign = sign.lower()
sign_dict = {'aries':1, 'taurus':2, 'gemini':3, 'cancer':4, 'leo':5, 'virgo':6,
'libra':7, 'scorpio':8, 'sagittarius':9, 'capricorn':10, 'aquarius':11, 'pisces':12}
if... |
2a677e17add6d97515448bb19e84414b00bfd37b | Aravind644/python- | /EXCEPTIONS.py | 4,335 | 4.375 | 4 | # python14
EXCEPTIONS
1.Write a program to generate Arithmetic Exception without exception handling
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d" %c)
#other code:
print("Hi I am other part of the program")
2.Handle the Arithmetic exception us... |
ecdf4080e87e65a7bb0036e31fb70b13ee30de6f | apeironuranium/Python-practice | /randLettersObj.py | 611 | 3.765625 | 4 | import random
from string import punctuation
class Letters(object):
def randomin(self,s):
if len(s)>2 and (s[-1] not in list(punctuation)):
return s[0] + "".join(random.sample(s[1:-1], len(s) - 2)) + s[-1]
elif len(s) > 2 and (s[-1] in list(punctuation)):
return s[... |
845d6abc11a2f6eae857c0bae2e466c0fdc757b5 | Ajaymagar/notes | /python/app.py | 2,055 | 4.28125 | 4 | #optional parameter tutorial
'''
def func(word, freq=3):
op = word*freq
ajay = func('ajay')
#print(ajay)
'''
#static methods
'''
class person(object):
population = 50 #class variable
def __init__(self,name ,age): # Constructor methods
self.name = name
self.age = age
@classmethod... |
e979a01341447f6f2e566b82c92515d3b1eaadc0 | goriver/skinfosec | /DAY04/03_lambda.py | 2,461 | 4.1875 | 4 | # 람다
# • 기능을매개변수로전달하는코드를더효율적으로작성
def increase(value,original):
return original+value
original_list = [10,20,30,40,50]
print("before",original_list)
for index, value in enumerate(original_list):
original_list[index] = increase(5, value)
print("after ",original_list)
"""
# map : function을 매개변수로 받음
# filter :... |
e7dcbe3c17aefd0e261cfb7f520a5b73e55e87c7 | goriver/skinfosec | /DAY01/Day1_08_strin_fuction.py | 3,716 | 3.59375 | 4 | """"
str = " 문자열 함수 알아보기 Hello Python "
print("lower : 소문자로 변경 ", str.lower())
print("upper : 대문자로 변경 ", str.upper())
print("strip : 양쪽 공백문자 제거", str.strip())
print("lstrip : 왼쪽 공백문자 제거", str.lstrip())
print("rstrip : 오른쪽 공백문자 제거", str.rstrip())
# in 연산자
print("안녕"in "안녕하세요")
# split() : 문자열 자르기
# 다른 언어에서 spit은 해당... |
a652d5aad7a80125e2559ee5e94f9e477d885790 | goriver/skinfosec | /DAY02/Day02test.py | 1,816 | 3.84375 | 4 | # 실습 예제 테스트
# def inroll(name,age,major):
# print("수강생 정보를 입력하시오")
# name = input("이름 : ")
# age = input("나이 : ")
# major = input("전공 : ")
# dict_st = {
# "이름": name,
# "나이": age,
# "전공":major
# }
ai_list =[]
while True:
print("------메뉴를 선택하세요-------")
print("1.A... |
9c07032e23949aa2e890ebb6442b0a1c16a0048a | ShallowAlex/leetcode-py | /周赛/5377.py | 486 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Apr 5 10:49:16 2020
@author: Alex
code for windows
"""
#from typing import List
class Solution:
def numSteps(self, s: str) -> int:
p = int(s, 2)
ans = 0
while p != 1:
if p & 1 == 1:
p += 1
else:
... |
5cbad5a501bf435eaac923d8fa5ec530cbfefe89 | ShallowAlex/leetcode-py | /101-200/108.py | 1,141 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Mar 9 15:23:22 2020
@author: Alex
code for windows
"""
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def sortedArrayToBST(self, nums):
def build(start, end):
if sta... |
aa17cb4090e26b955ae402c4f0bb5441217c8924 | ShallowAlex/leetcode-py | /1-100/57.py | 1,302 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 24 14:11:10 2020
@author: Alex
code for windows
"""
class Solution:
def insert(self, intervals, newInterval):
import bisect
if not intervals:
return [newInterval]
index0 = bisect.bisect(intervals,newInterval)
# tmp = []
# ... |
aad0171b05e8320a8631082319d8b4117bf2a677 | ShallowAlex/leetcode-py | /1-100/95.py | 794 | 3.78125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def generateTrees(self, n: int) -> List[TreeNode]:
def trees(head, tail):
if head > tail:
return [Non... |
1d1545b0aef303721ab936f4d292b1cea9ab476a | ShallowAlex/leetcode-py | /101-200/101.py | 734 | 4 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
l = [root]
r = [root]
while l:
p1 = l.pop()
... |
1f315343366d465e71384988e954e6be7d83dad7 | ShallowAlex/leetcode-py | /101-200/129.py | 524 | 3.640625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def sumNumbers(self, root: TreeNode) -> int:
def Numbers(node, s):
if not node:
return 0
... |
50a4b8966dd0e3a8c4be57fc230a8cf7e6e6203f | ShallowAlex/leetcode-py | /1-100/31.py | 664 | 3.5 | 4 | class Solution:
def nextPermutation(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
flag = 0
if len(nums) > 1:
for i in range(len(nums)-2, -1, -1):
if nums[i+1] > nums[i]:
flag = 1
... |
8d20d5c6de920fbba0504a34bc20e22aaf874f42 | ShallowAlex/leetcode-py | /快速排序.py | 1,015 | 3.953125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Mar 31 11:24:44 2020
@author: Alex
code for windows
"""
#from typing import List
class Solution:
def random_partition(self, arr, left, right):
import random
pivot = random.randint(left, right)
arr[right], arr[pivot] = arr[pivot], arr[right]
... |
e7958f906c313378efd5815b81b70b4f5c45c65e | robbyhecht/Python-Data-Structures-edX | /CH9/exercise1.py | 776 | 4.15625 | 4 | # Write a program that reads the words inwords.txtand stores them askeys in a dictionary. It doesn’t matter what the values are. Then youcan use theinoperator as a fast way to check whether a string is in thedictionary.
from collections import defaultdict
f = input("Enter file name: ")
try:
content = open(f)
exce... |
110cf26bf3674b2e5d6aeb1562ac6b569ef160fa | shairanshrawat/Number-guessing-game- | /random number.py | 598 | 3.84375 | 4 | import random
play_game='y'
while play_game== 'y':
answer = random.randint(1,100)
try_number = int(input('Guess a number between 1 and 100:'))
counter =1
while try_number != answer:
if try_number > answer:
print('Your number is too larger. Try again!!!')
if try_n... |
9606a0e44abd8a8a85748ca9fcf07855a2eb9653 | indervirbanipal/deep-neural-networks-with-pytorch | /activation_functions.py | 1,317 | 3.5 | 4 | # Import the libraries we need for this lab
import torch.nn as nn
import torch
import matplotlib.pyplot as plt
torch.manual_seed(2)
# Create a tensor
z = torch.arange(-10, 10, 0.1,).view(-1, 1)
# Create a sigmoid object
sig = nn.Sigmoid()
# Make a prediction of sigmoid function
yhat = sig(z)
# Plot the result
... |
24346e092a53fc76efdbdded64ed77853c8f1461 | Somi-Singh/leetcode_hackathon | /reverse_easy.py | 214 | 3.640625 | 4 | # num=int(input("enter any num"))
# rev=0
# while num>0:
# rev=(rev*10)+num%10
# num=num//10
# print("reverse=",rev)
list=[1,2,3,4,5]
i=len(list)-1
while i>=0:
print(list[i],end=",")
i-=1
|
5322104cdff15476034aa5aa39231e16a699bc0b | MichaelGarber/python-shape-calculator | /shape_calculator.py | 2,015 | 3.703125 | 4 | class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def __str__(self):
string = 'Rectangle(width='+ str(self.width) +', height=' + str(self.height)+')'
return string
def set_width(self, width):
self.width = width
return se... |
f6ccb976a46fc44208f1faad631215d3c0bbe918 | leona0409/hello_turtle | /Hello.py | 612 | 3.890625 | 4 | import turtle
import random
c = turtle.Canvas()
gang = []
for x in range(5):
t = turtle.Turtle()
t.shape("turtle")
gang.append(t)
# change all the turtles' color
for tina in gang:
tina.color("Blue")
# move all the turtles to a random spot
for tina in gang:
tina.penup()
tina.goto(random.ran... |
4a1563d05565349dbc5261e1d48fe00fe8d8e39e | maeve70/intro-data-capstone-musclehub | /MuscleHub_ABTest/musclehub copy.py | 14,456 | 4.1875 | 4 |
# coding: utf-8
# # Capstone Project 1: MuscleHub AB Test
# ## Step 1: Get started with SQL
# Like most businesses, Janet keeps her data in a SQL database. Normally, you'd download the data from her database to a csv file, and then load it into a Jupyter Notebook using Pandas.
#
# For this project, you'll have to... |
ed8ffecbb9de68acb06e8b037fa58a26c7e1dc18 | JimKass/Practicals | /prac_07/play_the_guitar.py | 1,609 | 3.984375 | 4 | """
Let's you collect all of the guitars in the WWWOOORRRLLLDDD!!!
"""
from prac_07.guitar import Guitar
MENU = """A - Add a guitar
D - Display a guitar"""
def main():
print("My guitars!")
guitars = []
print(MENU)
action = get_valid_string(">>> ").lower()
while action != "q":
if action... |
0675bc5888000c2709fd2e97e12bf16be6590bd1 | JimKass/Practicals | /prac_02/files.py | 616 | 3.953125 | 4 | NAME_FILE = "name"
NUMBER_FILE = "numbers"
def add_a_name():
file_out = open(NAME_FILE, "w")
name = input("What is your name? ")
print(name, file=file_out)
file_out.close()
def find_a_name():
file_in = open(NAME_FILE, "r")
name = file_in.readline()
print("Your name is {}".format(name))
... |
f6ff2923833b863fa9462d91716edbd61756634c | JimKass/Practicals | /prac_01/electricity_bill_estimator_v2.py | 759 | 3.984375 | 4 |
TARIFF_11 = 0.244618
TARIFF_31 = 0.136928
tariff = int(input('Which tariff? 11 or 31: '))
while tariff != 11 and tariff != 31:
print('Invalid Input')
tariff = int(input('Which tariff? 11 or 31: '))
if tariff == 11:
tariff_cost = TARIFF_11
else:
tariff_cost = TARIFF_31
daily_kWh = int(input('Enter dai... |
8a1c929bf5c054a057f57931619e6737d10cf99d | Micro-bit-final-project/python-game-pc | /template/template-minigame_files/sprite1.py | 1,438 | 3.78125 | 4 | import pygame, os, utils
class Sprite1(pygame.sprite.Sprite):
"""
This class handles the ? sprite
and its animation.
"""
def __init__(self):
"""
This function initialises the sprite by loading
all the needed sprites for the animation and
by generating the relative re... |
0432f55430f492096d4e4eb87d37cb53774f94f4 | cosmos-sajal/ds_algo | /two_pointers/three_sum.py | 1,248 | 3.578125 | 4 | # https://www.educative.io/courses/grokking-the-coding-interview/gxk639mrr5r
# https://leetcode.com/problems/3sum/
def search_triplets(arr):
arr.sort()
result_arr = []
for i in range(len(arr) - 1):
if i != 0 and arr[i] == arr[i - 1]:
continue
ptr1 = i + 1
ptr2 = len(ar... |
ac07705a2cea96a51f696c5f942adc2ee6e9796f | cosmos-sajal/ds_algo | /sliding_pattern/smallest_subarray.py | 1,478 | 4.125 | 4 | # https://www.educative.io/courses/grokking-the-coding-interview/7XMlMEQPnnQ
def get_sum_between_ptr(sum_array, i, j):
if i == 0:
return sum_array[j]
else:
return sum_array[j] - sum_array[i - 1]
def get_smallest_subarray_size(size, ptr1, ptr2):
if size > (ptr2 - ptr1 + 1):
return... |
a001b4fcc798badcdea67bfab03bced0d61a3df0 | cosmos-sajal/ds_algo | /sliding_pattern/sliding_2.py | 538 | 3.71875 | 4 | # problem - https://www.educative.io/courses/grokking-the-coding-interview/7D5NNZWQ8Wr
# optimized
def find_averages_of_subarrays(K, arr):
ptr, result = 0, []
_total = 0.0
for i in range(ptr, K):
_total += arr[i]
result.append(_total / K)
for i in range(K, len(arr)):
_total = _t... |
5fdf5f13a3bb83a095469aacda1b2e8e3d26824f | webjocke/Advent-of-Code-2019 | /05-Dec/part2.py | 4,304 | 3.578125 | 4 |
print "="*40
print "="*40
print "="*40
print "PROGRAM START"
with open("i") as fp:
steps = [int(x.strip()) for x in fp.read().split(",")]
# Print the starting memory data
print steps
i = 0
while (i <= len(steps)):
param_modes = []
opcode = []
temp = [char for char in st... |
86a31cafe8ae91d292ee291f786a330adb2b969f | PiotrWrobelAGH/Python | /zad2_dane.py | 124 | 3.578125 | 4 | #!/usr/bin/env python
your_name = input('Tell your Name, Surname, Birth year\n')
print(f'Your personal data: {your_name}\n') |
2b6a63781683172cbde6bffdedfb73d8fbc22a91 | PiotrWrobelAGH/Python | /zad10_sorting.py | 479 | 3.703125 | 4 | #!/usr/bin/env python
from random import random
lista = [None]*50
lista_sorted = [None]*50
for i in range(0, 50):
lista[i] = random()
smallest = None
for i in range(0, 50):
for x in range(0, 50):
if(lista[x] == None):
continue
if(smallest == None or smallest>lista[x]):
s... |
67206a461dbbfc59cb803d3eec15aa686548e62a | Vistril/pyproj | /03-coin-flipper/coin_flipper.py | 502 | 3.9375 | 4 | #Seth Camomile
#Period 7
import random
def coin(flips):
if flips < 0:
return 0, 0, 0
count = 0
heads = 0
tails = 0
for i in range(flips):
r = random.randint(0, 1)
if r == 1:
heads += 1
elif r == 0:
tails += 1
count = flips
return cou... |
23be0f08d0b2bf3260c561b270cebc079e5a08dc | boppanaravisastry/Examples-of-python-programs | /datedifference1.py | 571 | 4.0625 | 4 | from datetime import datetime # import datetime Module
starting_date=input('enter date in YYYY-MM-DD:').strip()
ending_date=input('enter date in YYYY-MM-DD:').strip()
format= "%Y-%m-%d" # date format
def datedifference(date1, date2):
try:
starting_date = datetime.strptime(date1,format)
... |
b41cb601f2c3d8edb932c2376241ae34585d8df4 | lenulek/lenulek.github.io | /python/RosetteInput.py | 709 | 3.796875 | 4 |
import turtle
t = turtle.Pen()
t.shape('turtle')
t.speed(0)
turtle.bgcolor('black')
colors=['red', 'cyan', 'magenta', 'seashell', 'orange', 'green',
'white', 'yellow', 'blue', 'pink', 'gray', 'purple', 'brown',
'beige', 'royal blue', 'lime green', 'deep pink',
'deep sky blue', 'lavender', 'or... |
ec4e0fcad8d62536a3a1b64f4520fb872994a8ce | lenulek/lenulek.github.io | /python/KochCurvesUpd.py | 1,054 | 3.875 | 4 | ##рисование линий Коха
import turtle
import random
t = turtle.Pen()
t.speed(0)
t.up()
t.goto(-300,200)
t.down()
turtle.bgcolor('black')
t.color('cyan')
##length of line - заданная длина линии
##l = 90
##с запросом длины линии у пользователя
##quest = input("Введи число - длину линии\n")
##l = int(quest)
##random le... |
3a797c57e614efbd882d6baf8c12c639da0e84ec | annyj211/PythonFeb01 | /12_files.py | 293 | 3.5 | 4 | def read_file(fname):
try:
f = open(fname,'rt') #Genera error
text = f.read()
except FileNotFoundError:
text = f'No existe el fichero{fname} en el directorio'
return text
print(read_file('sample.txt'))
print(read_file('sample2.txt'))
|
442cfc18efc0b44efce4ac2f7617e11899b1d8df | annyj211/PythonFeb01 | /12_clases.py | 1,282 | 3.703125 | 4 | class persona(): #Definicipn de la clase
###similar a constructor, se define de la sgte forma:
#Se debe hacr explicita como los primeros parametros del onstructor
def __init__ (self, nombre, edad):
self.nombre = nombre
self.edad = edad
#self.altura #no quiero definir un valor p... |
566a23e9b7633a9ce17062fad16cb1088e33e155 | TareqJudehGithub/Ardit_Sulce_Udemy | /Python_Mega/sec14_Numpy/numpy_practice.py | 886 | 4.1875 | 4 | """ Numpy
- Numpy is a fundamental package for scientific computing with Python.
- Official page: https://numpy.org/
- Numpy comes installed with Pandas library.
"""
import numpy
# .arange(int) created a new array with the specified int number.
n = numpy.arange(27)
print(n)
print(type(n))
print(len(n))
print(... |
55b6220e1e3711b3e98be23ab0521f965fdb0fce | TareqJudehGithub/Ardit_Sulce_Udemy | /Python_Mega/sec11_File_proc/main.py | 3,024 | 4.3125 | 4 | """
FILE IO
file.read()
- After python finishes reading a file, the cursor will wait AFTER the last
char in that file.
file_a = open('fruits.txt', mode='r')
file_a.read()
pear
apple
orange
watermelon
pomegranate
lemon
strawberries
... |
b43b82640ebf0a8e5a9b3f308aa8368bcb02fcab | TareqJudehGithub/Ardit_Sulce_Udemy | /Python_Mega/sec16_fixing_errors/sec_notes.py | 502 | 3.609375 | 4 | """
Reading and fixing errors in Python.
- An error is bug that causes a progrom to function incorrectly.
- Error types:
- Syntax errors.
- Exceptions.
Python interpretter first checks for syntex errors, then checks for exceptions.
- Syntax errors
Errors are caused by the user.
Typo is a good exam... |
fdb85dd88220653054dc4127e2273885515a9c53 | TareqJudehGithub/Ardit_Sulce_Udemy | /Python_Mega/sec6_Basics_Proc_User_Input/string_formatting.py | 653 | 4.125 | 4 | """
String formatting in Python
- More on:
https://pyformat.info/
"""
def greet_user():
name = input('What is your name? ')
# this is the a string formatting method introduced in Python 2
return "Hello, %s!" %name.title()
# using format()
return "Hello, {}!".format(name.title)
... |
ebdfab2cb3cc75734d4d514005ffbb2bef50fa67 | TareqJudehGithub/Ardit_Sulce_Udemy | /Python_Mega/sec8_build_prog/input_problem.py | 1,092 | 4.25 | 4 | import re
# Write a program, that asks the user for input(s), until
# the user types \end
# user inputs should not include any symbols.
# return all user outputs
def inputs_problem():
inputs = list()
inputs_str = str()
interrogatives = ('how', 'what', 'why', 'where')
input_validator = re.co... |
13d7b372c4881d86f42ca7a0aacff64b73a4ca14 | Rerepower/MH8811-G1901927A | /05/05_C1.py | 952 | 3.765625 | 4 | #import json
#import pickle
#def my_serialize(my_list):
# f = open("a.txt", 'w', encoding='utf-8')
# json.dump(my_list, f, ensure_ascii=False)
#f.close()
#def my_deserialize():
# input a list consisted with integer
# try block to handle the exception
#try:
# my_list = []
# while True:
# ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.