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 |
|---|---|---|---|---|---|---|
484fdb72be152019168cdf842edc31148ce5eb85 | RiqueBR/refreshed-python | /Monday/basics.py | 1,157 | 4.53125 | 5 | # You can write comments using a # (hash) or a block with """ (three double quotes)
# Module is a different name for a file
# Variables are also called identifiers
a = 7
print(a)
"""
Python won't have major issues with differentiate whole interger and floats
"""
b = 9.3
print(int(b)) # Take the interger of a float (... |
631f7ab72e7de0e9a241d0b8ef0f2514aff453a3 | RiqueBR/refreshed-python | /Tuesday/exercise-folder/module_sum.py | 632 | 3.8125 | 4 | # Handles main adding function
from random import randint
guessed_number = randint(0, 100)
my_list = [n for n in range(1, 101)]
print(my_list)
def guessNumber(value):
# print(value)
# while value in my_list:
# print(value)
guess = int(value)
while guess != guessed_number:
if guess > g... |
3ab4819362e9466615a16299efa638c56e5c42a6 | FarhanRah/Pomodoro-Timer | /main.py | 3,201 | 4.125 | 4 | import tkinter
reps = 0
time = None
def start_timer():
global reps
reps += 1
if reps % 8 == 0:
countdown(1200)
label.config(text="Break", fg="#DF0C36")
elif reps % 2 == 0:
countdown(300)
label.config(text="Break", fg="#DC8899")
else:
countdown(1500)
... |
d41209c8d3f6a4984bf96d7de511889b22982177 | yasinallahdev/python-test-programs | /02_km-to-miles.py | 119 | 3.90625 | 4 | km = float(input("Type the number of Kilometers: "))
miles = round(km / 1.609344, 4)
print(km, "km =", miles, "miles.") |
37d72783c433aadaaeb98bc1b85a7c4d9ae75f67 | Noelierx/defis_turing | /isn.py | 3,969 | 3.515625 | 4 | # -*- coding: utf8 -*-
from tkinter import Tk,Frame,Button,Canvas,LEFT,RIGHT,TOP,BOTTOM,BOTH,YES,E
import re
root = None
application = None
canvas = None
btnQuitter = None
def initDrawing(titre,x,y,largeur,hauteur):
"""Définition d'une fenêtre graphique"""
global root,application,canvas,btnQuitter
root = Tk(... |
038227dd7a9c9257c5aed7a1a94bd814b4aca69a | romanPashnitskyi/PythonProjects | /task6_2.py | 508 | 3.546875 | 4 | #! /usr/bin/env python3
import sys
import math
def fun(sumUAH, procStav, timeDep):
summa = sumUAH * math.pow((1 + (procStav / 100)), timeDep)
return summa
sumUAH = int(input("Введіть наявну суму: "))
procStav = float(input("Річна процентна ставка: "))
timeDep = int(input("Тривалість депозиту в роках: "))
print("Су... |
a092b1273accd648d829f7b7f8321e3469d75f66 | romanPashnitskyi/PythonProjects | /task3_3.py | 281 | 4.125 | 4 | #! /usr/bin/env python3
import sys
weight = input("Введіть Вашу вагу в кг: ")
height = input("Введіть Ваш зріст в метрах : ")
weight = float(weight)
height = float(height)
print('Індекс Маси Тіла - ', + weight / height** 2)
|
91ad16309eacc71cfcf30783e4bf1b01e715ce3f | romanPashnitskyi/PythonProjects | /task8_1.py | 430 | 3.546875 | 4 | #!/usr/bin/env python3
import sys
import collections
def f(seq, n):
assert n > 0
dq = collections.deque(seq)
r = n - 1
while len(dq) > 1:
dq.rotate(-r)
dq.popleft()
return list(dq)
myPeople = int(input("Введіть кількість людей: "))
step = int(input("Введіть крок: "))
print("Сам... |
b0183d0cfd1d66d5a1feceba95bc19c624674273 | Pydeveloper07/gsmarena_scraper | /writer/writer.py | 3,695 | 3.5 | 4 | from abc import ABC, abstractmethod
import xlsxwriter
class ExcelWriter(ABC):
def __init__(self, file_name, data):
self.file_name = file_name
self.data = data
@abstractmethod
def write(self):
pass
class ExcelBrandWriter(ExcelWriter):
def __init__(self, file_name, data):
... |
fef96a18bc991ca4f1dc7b243cefcdef2552f1f0 | alaabenfatma/Edit_Distance | /branch_and_bound.py | 4,084 | 3.734375 | 4 | '''
Things to keep in mind:
- lowerBound will NEVER surpass the length of the longest string
- if the currentDistance reaches, somehow, the length of the longest string, we break out of the function.
'''
'''
k = max(len(str1), len(str2))'''
'''
-the first 3 table are here for the sake of understanding the pro... |
83206d51cbcbda09bf69afb1e650a860c2d7eedd | alaabenfatma/Edit_Distance | /recursive.py | 2,295 | 3.71875 | 4 | import generator
import numpy as np
str1 = 'x'
str2 = 'y'
print(f'Calculating edit distance between "{str1}" and "{str2}"')
# replace can cost either 1 (insert a character on top of another) or 2 (remove a character and then insert the new one)
replace_add_cost = 0 # case where replace is 1 operation (= 1 otherwise... |
1dfaabfd6df3603dc7cbd320f0e096fe8d4ce091 | neeraj2681/InterviewBit-Practice | /programming/linked_lists/Kth_node_from_middle/Solution.py | 584 | 3.59375 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param A : head node of linked list
# @param B : integer
# @return an integer
def solve(self, A, B):
temp = A
n = 0
while... |
7689ba570dbe7cc695c085ed636c1eff3cbc6a9a | neeraj2681/InterviewBit-Practice | /programming/linked_lists/from_sorted_list/Solution.py | 678 | 3.734375 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param A : head node of linked list
# @return the head node in the linked list
def deleteDuplicates(self, A):
if (A == None):
return A
... |
43904c6f70fb5bd8e8ab46b380304884edd64788 | neeraj2681/InterviewBit-Practice | /programming/hashing/two_out_of_three/Solution.py | 848 | 3.5 | 4 | class Solution:
# @param A : list of integers
# @param B : list of integers
# @param C : list of integers
# @return a list of integers
def solve(self, A, B, C):
ans = []
mapper = {}
for num in A:
mapper.update({num: 1})
#print(mapper)
for num in B:... |
787b4efc9f50bc1d758a4dc041418ac5d6dc35eb | neeraj2681/InterviewBit-Practice | /programming/heaps_and_maps/merge_K_sorted_lists/Solution.py | 871 | 3.90625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
import heapq
class Solution:
# @param A : list of linked list
# @return the head node in the linked list
def mergeKLists(self, A):
head = ListNode(0)
temp = h... |
64ec4a19d43a56a1a94fd7d411717df8ba2402a8 | ChongjinChua/ECE364-Software-Engineering-Tools | /Prelab08/listmod.py | 346 | 3.84375 | 4 | #! /usr/bin/env python3.4
from math import floor
def find_median(list1,list2):
comb_list = list1 + list2
comb_list.sort()
comb_len = len(comb_list)
if (comb_len-1) % 2 != 0:
median = comb_list[floor((comb_len - 1) / 2)]
else:
median = comb_list[int((comb_len - 1) / 2)]
return... |
e0823871630fd9f14e6a5ca2ad65f0f923115629 | Adam-School/SchoolWork | /6.2.py | 398 | 3.90625 | 4 |
# make a main function
def main():
with open("numbers.txt", "r") as ins:
#create variables to keep track of total and how many numbers were counted
count = 0
total = 0
for line in ins:
total += int(line)
count += 1
print('The average of the numbers in the... |
a77f354c3cc2054f625a133dcab6b5aa2ce93849 | Adam-School/SchoolWork | /Trivia.py | 8,368 | 3.859375 | 4 | class questions():
#init statement to make the basic variables
def __init__(self):
self.questions = []
self.answers = []
def setQuestion(self, quest):
self.questions.append(quest)
def setAnswer(self, ans):
self.answers.append(ans)
def getQuestions(self, quest):
... |
57cb3b9fd30f23e2abf5a02d5f79c180db9ffae3 | Adam-School/SchoolWork | /11.1.py | 2,095 | 3.890625 | 4 | # make a office class
class office():
# a place to hold all vars
def base(self, category, material, length, width, hight, price):
self.c = category
self.m = material
self.l = length
self.w = width
self.h = hight
self.p = price
def __str__(self):
retu... |
f45aa98e5010666f1b0b16da119452b43db0de09 | chgeo2000/Turtle-Racing | /main.py | 2,104 | 4.28125 | 4 | import turtle
import time
import random
WIDTH, HEIGHT = 500, 500
COLORS = ['red', 'green', 'blue', 'cyan', 'yellow', 'black', 'purple', 'pink']
def get_number_of_racers():
"""
This function asks the user for the number of racers
:return: int, number of racers
"""
while True:
... |
86ef7ccb8036a89271054cf8f2b35b08db30cc69 | kisanzxy/Cracking-the-interview-learning-note | /1.5 One Away.py | 1,057 | 4.0625 | 4 | """
There are three types of edits that can be performed on strings: insert a character,
remove a character, or replace a character. Given two strings, write a function to check
if they are one edit (or zero edits) away.
EXAMPLE
pale, ple true pales, pale -> true pale, bale -> true pale, bae -> false
"""
def one_aw... |
79cf7337fac563e777f1e91470bc7551c9ebfff2 | zipho/marsrover | /tests/grid_test.py | 950 | 3.71875 | 4 | """Test module for the Grid class"""
from marsrover.src.grid import Grid
from marsrover.src.roverpoint import RoverPoint
class TestGrid:
"""TestGrid class tests when the rover's position is within a grid area,
and outside of the grid.
"""
def test_position_within_grid_area(self):
"""This i... |
d0b34c95d37f1589f0c9a1e5753d9f2dbfe460c4 | dpringlewood/student_score_prediction | /student_score_prediction.py | 2,872 | 4 | 4 | """
Beginners level Machine Learning (ML) project to build my skills.
The aim here is to predict a students final score (G3) based on a number
of factors. This will be a regression based ML project using sklearn.
"""
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklea... |
96f05f387b5f7b6af102371ad1510e84e6626c45 | pavankalyan-c/pk2 | /palin.py | 149 | 3.765625 | 4 | n=input()
t=n
s=0
while n!=0:
r=n%10
s=s*10+r
n=n/10
if t=s:
print "THE NO IS A PALINDROME IS NO"
else:
print "THE NO IS NOT A PALINDROME"
|
d7340ec989ef985666dd274993fc27469e1445d7 | jasperjbonghi/python | /test.py | 431 | 3.609375 | 4 | from datetime import datetime
import random
import time
odds=[1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,]
for ch in "Hi!":
print(ch)
for x in range(5):
right_this_second = datetime.today().second
if right_this_second in odds:
print("this minute seems a little odd.")
... |
e01b0dc7ea7f24e819793cac8c8f6dc276982bf6 | vatsyashh/Stagnography | /code.py | 3,774 | 3.59375 | 4 | from tkinter import *
import stegano_encrypt as se
import stegano_decrypt as sd
import cv2
import numpy as np
import RSA
# loading Python Imaging Library
from PIL import ImageTk, Image
# To get the dialog box to open when required
from tkinter import filedialog
# Create a windoe
def open_img_encrypt... |
0556186e9a2581f0479dd827a02cf2a57622e8e2 | DimitrisBovasianos/LPTHWexercises | /ex18.py | 333 | 3.53125 | 4 |
def print_two(*args)
arg1, arg2=args
print "arg1: %r, arg2: %r " (arg1, arg2)
def print_two_again(arg1, arg2):
print "arg1: %r, arg2: %r" % (arg1, arg2
def print_one(arg1):
print :"arg1: %r" % arg1
def print_none():
print "i got nothin'."
print_two("zed","shaw")
print_two_again("zed","shaw")
print_one("first!")
... |
7f556aa8e6c7899fea45340eb9eae32087b17b6b | revatidixit/class-work | /Assignments/Assignment5.py | 10,650 | 3.890625 | 4 | # Write a function called chop that takes a list and modifies it,
# removing the first and last elements, and returns None.
#x = [1,2,3,4,5]
''' def chop(x):
del x[0]
del x[-1:]
print (x)
return None
print (chop(x)) '''
# Then write a function called middle that takes a list
# and returns a new list t... |
59a128a9bc1c36b3246037b2fbf196867c40edbf | NearHuscarl/Advanced_Algorithm | /PascalTriangle/PascalTriangle.py | 456 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Tham khảo:
- https://en.wikipedia.org/wiki/Pascal_triangle
"""
def PascalTriangle(k):
L = []
for i in range(k + 1):
L.append([0] * (k + 1))
L[0][0] = 1
for i in range(1, k + 1):
L[i][0] = 1
for j in range(1, i):
L[i][j] = L[i - 1][j ... |
dbcac2da37a1975a5832ef3bed9678bcd4c86fb3 | dkleptsov/small_projects | /basics/oop.py | 3,142 | 3.515625 | 4 | from random import randint
def main():
class Toolbox:
@staticmethod
def add5(x):
return x+5
class Habbit:
def __init__(self, name:str, description:str="Empty"):
self.name = name
self.description = description
self.days =... |
8038d3bb5128bc0ddd477d33f3fd7d61b670f22a | JorgeSchelotto/practica3 | /Ejercicio5.py | 777 | 3.96875 | 4 | """Dado el archivo que detalla la cantidad de mujeres que estudian carreras tecnológicas,
recorrerlo e imprimir la cantidad total por universidad."""
import csv
csvreader = csv.reader(open("Todas_las_carreras.csv", "r"))
dic_unis = {}
for fila in csvreader:
if fila[2] != 'Institución' and fila[10] != '':
dic_unis... |
0401f3a35e5d7eb678dfdc4a25c47bb5fc783c72 | CeciliaYSui/Sudoku_Solver | /TSP/Graph.py | 1,315 | 3.796875 | 4 | class Graph:
# use python dictonary to represent the graph
def __init__(self, graph = {}):
self.graph = graph
def connect(self, vertex, adj, distance):
if vertex not in self.graph.keys():
self.graph[vertex] = {}
if adj not in self.graph.keys():
self.graph[ad... |
dd71e540a12f94277cb9234597141a10849e5029 | dgrevino/Intro-to-Compu | /tp2.py | 7,166 | 3.640625 | 4 | #!/usr/bin/env python
import sys
#Integrantes del grupo 5: Bonardi, Grevino, Robles.
# -------------------------------------------
#FUNCION 1
#--------------------------------------------
#Devuelve si el texto input es un mapa o no.
def es_mapa(texto):
#lee y lista el archivo
archivo = open(texto)
lista_de_fi... |
c84d5d1185eaa37f01a4fc5c97970b275fb90ff7 | daltons8444/Learning-how-to-write-python-sctipts | /Setup_test.py | 230 | 3.734375 | 4 | a = 'Dalton'
b = 'Tanner'
print('Welcome, Who are you?')
a = input()
b = input()
a1 = 'DPassword'
b1 = 'TPassword'
if a == 'Dalton' or b == 'Tanner':
print ('What is your password')
else: print ('Access Denied')
|
28b4020cbd612ffc2b7f16ac2ba44e39f5ff4ab8 | tomatchison/CTI | /P4LAB1_Atchison.py | 661 | 4.40625 | 4 | # Write a program using turtle to draw a triangle and a square with a for loop
# 25 Oct 2018
# CTI-110 P4T1a: Shapes
# Tom Atchison
# Draw a square and a triangle using turtle.
# Use a while loop or a for loop.
# Start turtle.
import turtle
# See turtle on screen.
wn=turtle.Screen()
# Give turtle optio... |
4a4300f301d976b8bb1b7a96e6727f12c501ec83 | tomatchison/CTI | /P4LAB3_Atchison.py | 737 | 4.1875 | 4 | # Create my initials using turtle
# 25 Oct 2018
# CTI-110 P4T1b: Initials
# Tom Atchison
# Start turtle.
import turtle
import random
# See turtle on screen.
wn=turtle.Screen()
wn.bgcolor("green")
# Give turtle optional name.
sid=turtle.Turtle()
sid.speed(20)
# Give turtle shape.
sid.shape ("turtle... |
9c9a481a6f2cd2b6d600c0598a2a3d84b8abf5dd | olaolu-adigun/Classification-of-CALTECH-256 | /Preprocessing/label2onehot.py | 350 | 3.53125 | 4 | import numpy as np
def label2onehot(Y, num_class):
'''
This function aim to convert label to one hot matrix.
Arguments:
Y -- label vector (m, 1)
num_class -- (int) number of class
Returns:
Y_onehot -- one hot matrix
'''
m = Y.shape[0]
Y_onehot = np.zeros((m, num_class))
for i in range(m):
Y_onehot[i, ... |
857dc63e84fbd2a30cc1047baa4ea71f6cf03920 | pardinn/selenium-python-training | /base/webdriver_factory.py | 1,326 | 3.609375 | 4 | """ @package base
WebDriver Factory class implementation
It creates a webdriver instance based on browser configurations
Example:
wdf = WebDriverFactory(browser)
wdf.get_web_driver_instance()
"""
from selenium import webdriver
from webdriver_manager.firefox import GeckoDriverManager
from webdriver_manager.chr... |
1b9b0665ae9b440d2f93f803140ea6cb2d3733e9 | ditadewindita/AICE-ACSL | /Triangles.py | 1,162 | 3.703125 | 4 | def isTriangle(tri):
if (tri[0] + tri[1] <= tri[2]) or (tri[1] + tri[2] <= tri[0]) or (tri[0] + tri[2] <= tri[1]):
return False
return True
def makeInt(a):
ret = []
for b in range(0, 3):
ret.append(int(a[b]))
return ret
def getSimilar(s ,a, b):
st = ["DE", "EF",... |
54290f9350ad833ee6165b2715d5fdcca2e61b8c | mvanorder/forecast-forecast_old | /overalls.py | 1,095 | 4.125 | 4 | ''' general use functions and classes '''
def read_list_from_file(filename):
""" Read the zip codes list from the csv file.
:param filename: the name of the file
:type filename: sting
"""
with open(filename, "r") as z_list:
return z_list.read().strip().split(',')
def key_list(... |
ddb0ddf8e31037471bafa83c20506711fdd3c739 | xotonic/netconfessor | /gen/tools/jnc_plugin/java_value.py | 6,904 | 3.671875 | 4 | import collections
import context
import util
from .ordered_set import OrderedSet
class JavaValue(object):
"""A Java value, typically representing a field or a method in a Java
class and optionally a javadoc comment.
A JavaValue can have its attributes set using the optional keyword
arguments of the... |
ccd272a1069c2015aa5deec34cc0afbe5ab40dd3 | xotonic/netconfessor | /gen/tools/jnc_plugin/method.py | 7,760 | 3.515625 | 4 | import util
from .java_value import JavaValue
from .ordered_set import OrderedSet
class JavaMethod(JavaValue):
"""A Java method. Default behaviour is public void."""
def __init__(self, exact=None, javadocs=None, modifiers=None,
return_type=None, name=None, params=None, exceptions=None,
... |
538cee76f468a26d30792430d3bf51e73c80845d | pradeepdevloper1/Learn_Python_CN | /patternchar2.py | 174 | 3.609375 | 4 | n=int(input())
i=1
while i<=n:
j=1
startchar=chr(ord('A')+i-1)
while j<=n:
print(chr(ord(startchar)+j-1),end='')
j+=1
print()
i+=1 |
70aefdd05d8e38d8a3d50f97b5ce78237484fd96 | pradeepdevloper1/Learn_Python_CN | /patternbinaryforloop.py | 187 | 3.5625 | 4 | n=int(input())
i=1
while i<=n:
j=n
while j>=i:
if i%2==0:
print(0,end=' ')
else:
print(1,end=' ')
j-=1
print()
i+=1 |
ba12888506bd65acf5f3f1f4745e45bf2cfcc3e8 | pradeepdevloper1/Learn_Python_CN | /pattern1.py | 206 | 3.859375 | 4 | ## Read input as specified in the question.
## Print output as specified in the question.
n=int(input())
i=1
while i<=n:
j=1
while j<=i:
print(1,end='')
j+=1
print()
i+=1 |
953ec53e1d50a6b3ca25605d7224b575b4d08a75 | yihuichen/FACTOR_MYSQL | /Other_function/some_function.py | 1,658 | 3.625 | 4 | # -*- coding: utf-8 -*-
def format_date(x):
try:
return x.strftime('%Y%m%d')
except TypeError:
print('wrong input of {}'.format(x))
# 对pandas中dataframe的列按照指定顺序重新排列
def sort_df_columns(df, columns):
import pandas as pd
if not isinstance(df, pd.DataFrame):
raise TypeError('df is ... |
f2d03a02a7e8c0beeb5ebdf2448a95c6d3cbc18a | zzzzzzzlmy/MyLeetCode | /125. Valid Palindrome.py | 440 | 4.125 | 4 | '''
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.
'''
class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype:... |
667a846115159dcdc7c9aae571c6b7827ee0ffd2 | zzzzzzzlmy/MyLeetCode | /67. Add Binary.py | 863 | 3.765625 | 4 | '''
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
'''
#1
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
return bin(int(a, 2) + int(b, 2))[2:]
#2
... |
621fac49fbb3ad73fca9bef27ceeb513ca144d73 | hanseonghye/baek-joon | /1181.py | 211 | 3.59375 | 4 | num=int(input())
result=[]
for i in range(0,num):
temp=input()
result.append(temp)
result=list(set(result))
result=sorted(result,key=lambda x:(len(x),x))
for i in range(0, len(result)):
print (result[i])
|
747c94e4c6f96fad006c46238b4889967d6a460e | hanseonghye/baek-joon | /1427.py | 125 | 3.875 | 4 | num=input("input number");
str_num=[]
str_num=list(str(num))
str_num.sort(reverse=True)
for i in str_num:
print (i, end='') |
ecbeb9b5568bf31dd0b1cdc7bb911bb526e3bba9 | Kgolakot/Leetcode | /roman.py | 329 | 3.703125 | 4 | roman_map = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000 }
print("Please enter the string values :\n")
string = str(input())
value = 0
s_big = roman_map['I']
for s in string[::-1]:
if(s_big > roman_map[s]):
value = value - roman_map[s]
else:
value = value + roman_map[s]
s_big = roman_map[s]
print(valu... |
5ceef64824fc6949781cbcb1b9fef385f1d170fd | toberge/network-programming | /exercises/04 TCP Sockets/calculator.py | 859 | 3.703125 | 4 | from collections import deque
operators = {
'+': lambda x, y: y + x,
'-': lambda x, y: y - x,
'*': lambda x, y: y * x,
'/': lambda x, y: y / x
}
def process(expression):
"""Parse and calculate an expression in RPN"""
if expression.strip() == '': raise Exception('Empty expression')
stack = ... |
a4fd4b4d3834632fd0c6659a52e9d29b12a211d7 | azkrebs/python_for_ethical_hacking_2021 | /packet_sniffer.py | 1,813 | 3.8125 | 4 | #! usr/bin/env python
#a packet sniffer is basically a program that reads packets or data that flow through an interface
import scapy.all as scapy
from scapy.layers import http
def sniff(interface): #sniffing function
scapy.sniff(iface=interface, store=False, prn=process_sniffed_packet) #store=False is telling sc... |
fbba5bd459ad5833033e2e71b567780650ff9561 | xiaoxue11/02_python_multi_task | /02_python核心编程/多任务/进程/06_use_pool_create_process.py | 724 | 3.640625 | 4 | from multiprocessing import Pool
import os, time, random
def worker(msg):
t_start = time.time()
print('{} starts to execute, the process id is {}.'.format(msg, os.getpid()))
time.sleep(random.random()*2)
t_stop = time.time()
print('{} is already finished, the total time is {:.2f}.'.format(msg, (t_... |
992492d3815b5fc286f5a0de5767afe0eb56223d | xiaoxue11/02_python_multi_task | /02_python核心编程/多任务/协程/迭代器1.py | 902 | 3.953125 | 4 | from collections.abc import Iterable, Iterator
class Friends(object):
def __init__(self):
self.names = []
def add(self,name):
self.names.append(name)
def __iter__(self):
return Friends_Iterator(self)
class Friends_Iterator(object):
def __init__(self,obj):
self.... |
828c08e44c3955106dde0ed821e9861e3f1104d1 | battubanyan/Code-test | /First/hello.py | 1,027 | 3.984375 | 4 | print('hello ravi')
message = 'welcome to coding'
print(message)
message1 = 'ravi\'s editor'
print(message1)
message2 = """my "first" program code"""
print(message2)
print(len(message), len(message1), len(message2))
print(message[5], message1[0:6], message2[8])
j = len(message2)-1
print(message2[0:j])
a = len... |
b180b006787fc8a3695f3f7ff60d3036adf1244c | reuelrds/PrettyPrinter | /Special/If.py | 852 | 3.703125 | 4 | # If -- Parse tree node strategy for printing the special form if
import sys
from Special import Special
class If(Special):
def __init__(self):
pass
def print(self, t, n, p):
sys.stdout.write(' ' * n)
sys.stdout.write("(if ")
condition = t.getCdr().getCar()
truth... |
01cba4133aa51d9ea489f78966aaee44974acdf0 | martinegeli/TDT4110 | /studas/rekursjon.py | 1,204 | 3.90625 | 4 |
def recursive_sum(n):
if n == 1:
return 1
return n + recursive_sum(n-1)
#print(recursive_sum(5))
def fakultet(n):
if n == 1:
return 1
return n * fakultet(n-1)
#print(fakultet(5))
def find_smallest_element(numbers, mini = float('inf')):
if numbers[0] < mini:
mini = numbe... |
69db57fd6d66311c4efad733fbeaf99cb89ad595 | martinegeli/TDT4110 | /øving3/øving3-9.py | 641 | 3.796875 | 4 | hemmelig_ord=input('Skriv inn ditt hemmelige ord: ')
antall_liv=int(input('Skriv inn antall liv: '))
løsning="*"*len(hemmelig_ord)
while True:
bokstav=input('Gjett en bokstav: ')
if bokstav in hemmelig_ord:
print('Stemmer, bokstaven', bokstav, 'er i ordet')
elif bokstav not in hemmelig_ord:
print('Feil, bokstave... |
5130ec4e0f1f2231cf18995887b6e13d67b77f56 | martinegeli/TDT4110 | /øving6/øving6-5.py | 363 | 3.640625 | 4 | number_list = [i for i in range(1,101)]
summer = []
for i in number_list:
if i%3==0 or i%10==0:
summer.append(i)
print(sum(summer))
#One-line sum
result = sum([x for x in range(1,101) if x % 3 == 0 or x % 10 == 0])
print(result)
number_list[::2], number_list[1::2] = number_list[1::2], number_list[::2]
print(numbe... |
79f0172bed180384887fea4f025b641695ec3acd | martinegeli/TDT4110 | /øving5/øving5-7.py | 605 | 3.8125 | 4 | from math import *
def f(x):
return (x-12)*e**(5*x)-8*((x+2)**2)
def g(x):
return -x-2*(x**2)-5*(x**3)+6*(x**4)
print(g(1))
print(f(0))
def derivate(h, x, func):
return (func(x+h/2)-func(x-h/2))/h
print('Derivate: ', derivate(0.000001, -2, f))
def newtons_method(h, x, func, tol):
xold=x+2*tol
while fabs(x-x... |
bfb12b03d495b1febaae0e3e75d02af9b469b4b2 | martinegeli/TDT4110 | /øving3/øving3-2.py | 280 | 3.78125 | 4 | for x in range(1,6):
print(x)
count=1
while count<6:
print(count)
count=count+1
#teller ned fra 15 til 1 med en for-løkke
for x in range(15,0,-1):
print(x)
#teller ned fra 15 til 1 ved en while-løkke
count=15
while count>0:
print(count)
count=count-1
|
83895f637218c2bfb7c47f0990292e8e1f64ad17 | martinegeli/TDT4110 | /øving2/øving2-2.py | 328 | 3.828125 | 4 | a=int(input('Skriv inn et tall: '))
b=int(input('Skriv inn et til: '))
if a*b > a+b:
print('Det minste av a*b og a+b er a*b og det er: ', a * b)
else:
print('Det minste av a*b og a+b er a+b og det er: ', a + b)
tall = int(input('Hva er 3*4? : '))
if tall == 12:
print('Det stemmer')
else:
print('Du tok... |
50abfc53edeb131cbd64dcfca42baca644c3b9c5 | Joshcosh/AutomateTheBoringStuffWithPython | /Lesson_15.py | 1,665 | 4.40625 | 4 | # %%
# 1 | methods and the index method
spam = ['hello', 'hi', 'howdy', 'heyas']
spam.index('hello') # the index method
spam.index('heyas')
spam.index('asdfasdf') # exception
# %%
# 2 | in the case a value apears more than once - the index() method returns the first item's index
spam = ['Zophie', 'Pooka', 'Fat-tail', ... |
0b045e9342c11328c37b611a97113532f63a4f45 | Joshcosh/AutomateTheBoringStuffWithPython | /Lesson_28.py | 1,492 | 3.703125 | 4 | # %%
# 1 | The sub() method
import re
namesRegex = re.compile(r'Agent \w+')
namesRegex.findall('Agent Alice gave the secret documents to Agent Bob.')
namesRegex.sub('REDACTED', 'Agent Alice gave the secret documents to Agent Bob.')
# %%
# 2 | Substitute just a part of the text using the original text
import re
nam... |
768c2aabdca4bd8ce2380a71e960589e2fd0a1d3 | Joshcosh/AutomateTheBoringStuffWithPython | /Lesson_05.py | 747 | 4.09375 | 4 | # if exalmple
# name = 'Bob'
# if name == 'Alice':
# print('Hi Alice')
# print('Done')
# else example
# password = 'swordfish'
# if password == 'swordfish':
# print('Accedd granted.')
# else:
# print('Wrong password.')
# if / elif example
# name = 'Bob'
# age = 3000
# if name == 'Alice':
# print('H... |
aab6765d7322ea87b0296033a7f761aea2053dc4 | adi-varshney/TicTacToe | /UdemyObject.py | 851 | 4.03125 | 4 | class Dog:
species = 'mammal'
def bark(self, age):
return "WOOFs! My name is {}. I am {} years old".format(self.name, age)
def __init__(self, breed, name):
self.breed = breed
self.name = name
class Circle:
pi = 3.14
def __init__(self, radius=1):
self.radius = rad... |
39629ce760dc9f089ba7566febb9c1bfb2c60921 | Some7hing0riginal/lighthouse-data-notes | /Week_1/Day_2/challenge2.py | 1,305 | 4.3125 | 4 | """
#### Rules:
* Rock beats scissors
* Scissors beats paper
* Paper beats rock
#### Concepts Used
* Loops( for,while etc.)
* if else
#### Function Template
* def compare(user1_answer='rock',user2_answer='paper')
#### Error Handling
* If the user_answer input is anything other than 'rock','paper' or 'scissors' re... |
58e97c2d90347752e8512d9c3e56c00f7e266ecd | agoering/sci_prog | /hw3/h3_jordan.py | 2,925 | 3.75 | 4 | import re
from collections import Counter
#define a storm object with method for pressure minimum
class storm:
def __init__(self, id, name, year):
self.id = id
self.name = name
self.pos = []
self.speed = []
self.pressure = []
self.year = year
self.hr = []
self.descrip = []
def press... |
1d1aa3b73b85cd317a005971e5b3f760d1c9c701 | gsahadevan/python-bits | /refactoring.py | 879 | 3.734375 | 4 | colors = ['red', 'yellow', 'blue', 'green']
for color in colors:
print(color)
print('--------------------------------------------')
for i, color in enumerate(colors):
print(i, '-->', colors[i], '-->', color)
print('--------------------------------------------')
for color in reversed(colors):
print(colo... |
54aac287c768e680709f0adedcd29d05084ceeba | KennyTzeng/Python-Apps | /binascii/binascii_demo.py | 549 | 3.625 | 4 | import binascii
str = 'abc'
b_str = str.encode('ascii')
# b'abc'
print(type(str), str)
# <class 'str'> abc
print(type(b_str), b_str)
# <class 'bytes'> b'abc'
print(type(b'abc'), b'abc')
# <class 'bytes'> b'abc'
print(type(b_str.decode('ascii')), b_str.decode('ascii'))
# <class 'str'> abc
print(type(binascii.hexlif... |
10851a3ef7a19639260ce009a02371349e95591a | KennyTzeng/Python-Apps | /itertools/itertools_demo.py | 243 | 3.9375 | 4 | import itertools
# map applies a function to all the items in an input_list
# type(m) = map
m = map(str, range(1,10))
for i in itertools.product(m, repeat = 3):
# type(i) = tuple
print("".join(i))
"""
111
112
113
...
997
998
999
""" |
5446096f8e3cc11720a7d8bda44899bd4291ce54 | JAYAROSHINI2112/dart-batch-2 | /control_structures_dart/list.py | 502 | 3.640625 | 4 | import time
start = time.time() # nano seconds
list = []
for i in range(100000):
list += [i]
end = time.time() # nano seconds
print('shorthand operator: ', end-start)
start = time.time() # nano seconds
list = []
for i in range(100000):
list.append(i)
end = time.time() # nano seconds
print('append functio... |
eb223face9518f359ba6fec640f0d913dd039f0a | SouravShrestha/PythonPrograms | /Basic Programs/Factorial.py | 101 | 3.828125 | 4 | n = int(input("Enter A Number : "))
f = 1
for i in range(1,n+1):
f = f * i
i += 1
print(n,"! = ",f) |
db7ad605cc0fef1e0ab7557944d2e045502337a7 | MartinHarvey/MedalsAnalyser | /findPop.py | 1,177 | 4.0625 | 4 | import requests # requests is used to fetch the wikipedia pages we scrape for population data
def findPop(countryN):
countryWiki = requests.get('http://en.wikipedia.org/wiki/' + countryN, params={'action': 'raw'})
countryWiki = countryWiki.text #The requests object at countryWiki is translated into plaintext a... |
a50bdb71f0b44af003b78081ce33dd16886a06e1 | Chidi-nwachukwu/Youverify_assessment_test | /Question2/check_permutation.py | 380 | 3.875 | 4 | def check_permutation(data: str, data2: str) -> bool:
if len(data) != len(data2):
return False
str1 = "".join(sorted(data))
str2 = "".join(sorted(data2))
for index in range(len(data)):
if str1[index] != str2[index]:
return False
return True
if __name__ == "__main__... |
c6e9022dd26952e59d8fe538fb61bfdcf4341d4e | vchatchai/python101 | /python_tutorial/MyClass.py | 522 | 3.75 | 4 | class MyClass :
"""A simple example class"""
i = 12345
def __init__(self) :
self.data = []
def f(self) :
return 'hello world'
x = MyClass()
print(x.f())
class Complex:
def __init__(self, realpart, imagpart) :
self.r = realpart
self.i = imagpart
c = Complex(... |
ada17b307edf60a7e7e788d8ce92f40a29eccafb | vchatchai/python101 | /exercise406.py | 222 | 3.84375 | 4 |
values = input("Please fill value:")
result = []
for value in values :
if str(value).isdigit() :
dec = int(value)
if dec % 2 != 0 :
result.append(dec)
print(result)
print(len(result)) |
ad3f8f93ba02a920a50bc42b1e737ac10ae6600b | vchatchai/python101 | /exercise108.py | 134 | 3.71875 | 4 | import math
values = [ float(e) for e in input("Input value: ").split()]
result = sum(values)/len(values)
print("result", result) |
704f448b81b6efb65069f40a364f9b29617c09be | vchatchai/python101 | /isbn.py | 253 | 3.84375 | 4 |
values = str(input('Please insert value: '))
print(values)
result = 0
length = len((values))
for x in range( length ):
print(str(x) + " " + values[x])
result += ( 10 - x ) * int(values[x])
print(result)
print(values + str(11-(result%11))) |
ea999b98e08ba32bebdcb3dd96e035d0269ad842 | vchatchai/python101 | /exercise612.py | 234 | 3.890625 | 4 |
# filename = input("please fill the file name:")
filename = 'usernames.txt'
with open(filename, 'r') as file :
for line in file :
words = [line.split()]
words.insert(0, words[0].pop(0))
print(words)
|
c522db8f0dba297b75b24e80b7ff696c5f49da10 | vchatchai/python101 | /python_tutorial/generator.py | 383 | 3.875 | 4 | def reverse(data):
for index in range(len(data)-1, -1, -1) :
yield data[index]
for char in reverse('golf') :
print(char)
#generator expression
print(sum(i*i for i in range(10)))
xvec = [10,20,30]
yvec = [7, 5, 3]
result = sum(x*y for x,y in zip(xvec, yvec))
print(result )
data = 'golf'
result = ... |
1e7499929fdbe5b458524329ec9b45230a0b31ac | zhast/LPTHW | /ex5.py | 635 | 4.46875 | 4 | name = 'Steven Z. Zhang'
age = 18
height = 180 # Centimeters
weight = 175 # Pounds
eyes = 'Dark Brown'
teeth = 'White'
hair = 'Brown'
# The f character in the function lets you plug in a variable with curly brackets
print(f"Let's talk about {name}.") # In this case, its name
print(f"He's {height} centimeters tall")
... |
eb650c6d3f6be2f44d913a0fba56bea8065daa04 | zhast/LPTHW | /ex6.py | 655 | 4.0625 | 4 | types_of_people = 10
x = "There are {} types of people."
binary = "binary"
do_not = "don't"
y = f"Those who know {binary} and those who {do_not}."
print(x.format(types_of_people))
print(y)
print(f"I said: {x.format(types_of_people)}")
print(f"I also said: '{y}'")
# Python recognizes that the variable is of type bo... |
ded042c1e3ee72758dc1afd9173f1663802261cd | vinismarques/codigos-python | /funcao_fatorial.py | 201 | 3.703125 | 4 | def fatorial(N):
fat = 1
if N > 1:
for i in range(N, 0, -1): # start (inclusivo), stop (exclusivo), step
fat = fat * i
return fat
N = int(input())
print(fatorial(N))
|
00362f31a7495f96b91ce7f69a13a3832b12d025 | Eradch/-2 | /4.py | 154 | 3.796875 | 4 | string = input('Ведите слоа через пробелы - ').split()
for i, word in enumerate(string, 1):
print(f'{i}, {word[:10]}')
|
24f2002cf8b309626799996a6350b84f8768fdd6 | MaleehaBhuiyan/pythonBasics | /notes_and_examples/g_tuples.py | 362 | 4 | 4 | #Tuples
#type of data structure that can store different values
#KEY DIFFERENCES FROM LISTS:
# * a tuple is immutable, the tuple cant br changed or modified
#how to make a tuple
coordinates = (4, 5)
#can access the entries in a tuple but cannot change them
print(coordinates[1])
#list of tuples
coordinates = ... |
ff13fde0d24c6d8b175496fe127cdee185588557 | MaleehaBhuiyan/pythonBasics | /notes_and_examples/o_two_d_lists_and_nested_loops.py | 1,053 | 4.125 | 4 | #2d lists and nested loops
number_grid = [
[1,2,3],
[4,5,6],
[7,8,9],
[0]
]
#selecting individual elements from the grid, this gets the number 1, goes by row and then column
print(number_grid[0][0])
#nested for loop to print out all the elements in this array
for row in number_grid: #this will o... |
20d57d8eab474dac7e2c0b4e79713cfea581dadc | MaleehaBhuiyan/pythonBasics | /notes_and_examples/c_strings.py | 791 | 4.28125 | 4 | #Working with strings
print("Giraffe Academy")
print("Giraffe\nAcademy")
print("Giraffe\"Academy")
print("Giraffe\Academy")
phrase = "Giraffe Academy"
print(phrase + " is cool")
phrase = "Giraffe Academy"
print(phrase.lower())
phrase = "Giraffe Academy"
print(phrase.upper())
phrase = "Giraffe Academy"
print(phr... |
1c4d5f869227534de6a1bb1a0a5a098937d1297f | mnalevanko/backup-manager | /older-versions/170501-selective-backup.py | 2,872 | 3.90625 | 4 | # Adapted from Automate the Boring Stuff
'''
Selective Copy
Write a program that walks through a folder tree and searches for files
with a certain file extension (such as .pdf or .jpg). Copy these files
from whatever location they are in to a new folder.
Modifications
-The subfolders in the file directory are mirror... |
d8a1dd84e6b2eb03983838a9d4e9ff53ce5c9ca0 | prateekrk/DSA_C_Python | /Stacks/stack.py | 867 | 3.9375 | 4 | class Node:
def __init__(self,data):
self.data=data
self.next=None
class Stack:
def __init__(self):
self.top=None
def push(self,data):
newNode=Node(data)
newNode.next=self.top
self.top=newNode
def isEmpty(self):
return self.top==None
def pop(se... |
7069a4eb9d0b63be4c0e7dafd4f9b0165cb50a98 | rynoschni/python_oop | /vehicle_class.py | 358 | 3.796875 | 4 | class Vehicle:
color = "blue"
#constructor
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def __str__(self):
return "My vehicle is a %d %s %s %s." % (self.year, self.color, self.make, self.model)
betsy = Vehicle(... |
e76afe86418c782f16baf1d54a22b66254bb9fd7 | kjmjr/Python | /python/prime2.py | 513 | 4.25 | 4 | #Kevin McAdoo
#2-1-2018
#Purpose: List of prime numbers
#number is the variable for entering input
number = int(input('Enter a number and the computer will determine if it is prime: '))
#the for loop that tests if the input is prime
for x in range (2, number, x - 1):
if (number % x != 0):
print (nu... |
cf5de27304a6ae16c9219c902bba602979340412 | kjmjr/Python | /python/list_processing.py | 807 | 4.25 | 4 | #Kevin McAdoo
#2-21-2018
#Chapter 7 homework
print ('List of random numbers: ')
#list of random numbers
myList = [22, 47, 71, 25, 28, 61, 79, 57, 89, 3, 29, 41, 99, 86, 75, 98, 4, 31, 22, 33]
print (myList)
def main():
#command for the max function
high = max(myList)
print ('Highest number: ',... |
6b461d8563f05832a796b79b4a84999447d98436 | kjmjr/Python | /algorithm_workbench_problems.py | 860 | 4.40625 | 4 | #Kevin McAdoo
#Purpose: Class assignment with if/else statements/ the use of and logical operators
#1-24-2018
#3. The and operator works as a logical operator for testing true/false statements
#where both statements have to be true or both statments have to be false
#4 The or operator works as another logical ... |
7300bf857322e6298d6f30e4b15affbcb752afe0 | kjmjr/Python | /python/Test 1.py | 949 | 4.125 | 4 | #Kevin McAdoo
#2-14-2018
#Test 1
#initializing that one kilometer is equal to 0.621 miles
one_kilo = 0.621
#the define main function is calling the def get_kilometers (): and def km_to_miles(): functions
def main():
#user inputs his number here and float means the number he/she uses does not have to be a w... |
40802f73cc3592f7a29e6a910ca936a83fe4d9ef | vinicius-gadanha/python-courses-cev | /MUNDO 3/ex096.py | 558 | 3.671875 | 4 | def boni():
print('=' * 50)
print('{:^50}'.format('Controle de Terrenos:'))
print('=' * 50)
area(larg=float(input('LARGURA(m): ')), comp=float(input('COMPRIMETO(m): ')))
print('=' * 50)
def area(larg, comp):
ar = larg * comp
print(f'A área de um terreno {larg} x {comp} é de {ar}m... |
d85c5a07cda1ef84efbbd866e34ff73f9719f570 | vinicius-gadanha/python-courses-cev | /MUNDO 3/ex081.py | 768 | 3.875 | 4 | lista = []
n = 0
while True:
lista.append(int(input('Digite um número: ')))
son = str(input('Quer continuar? [S/N] ')).upper().strip()[0]
while son not in 'SN':
son = str(input('TENTE NOVAMENTE. Quer continuar? [S/N] ')).upper().strip()[0]
if son == 'N':
break
print('=' * 80)
p... |
56b673d9e0a261defcb46d1dd3720a7f1d54416a | vinicius-gadanha/python-courses-cev | /MUNDO 3/ex112/utilidadescev/dado/__init__.py | 298 | 3.671875 | 4 | def leiadinheiro(txt):
valido = False
while not valido:
valor = str(input(txt)).strip().replace(',', '.')
if valor.isalpha() or valor == '':
print(f'\033[0;31mERRO: "{valor}" é um preço inválido!!\033[m')
else:
return float(valor)
|
8fe0ba0dd845065f9c4686777962f9e431bfe717 | vinicius-gadanha/python-courses-cev | /MUNDO 3/ex079.py | 575 | 3.921875 | 4 | valores = list()
while True:
valores.append(int(input('Digite um valor:')))
if valores.count(valores[-1]) == 2:
print('Valor duplicado! Não vou adicionar...')
valores.pop()
else:
print('Valor adicionado com sucesso...')
print('=' * 50)
son = str(input('Quer continuar... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.