blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
cfc71e45c6b18c31b3a9b6f027712a435f144ac8 | AntoRojo16/Ejercicio7Unidad2 | /ClaseHora.py | 473 | 3.53125 | 4 | class Hora:
__hora=0
__min=0
__seg=0
def __init__ (self,hora=0,min=0,seg=0):
self.__hora=hora
self.__min=min
self.__seg=seg
def getHora (self):
return self.__hora
def getMin (self):
return self.__min
def getSeg (se... |
1f40c6364681d06e4ec705bb29b64a86b61438a8 | corsantic/resize-to-icon | /icon-process.py | 1,063 | 3.8125 | 4 | from PIL import Image
import os
class imageSize:
def __init__(self, name, width, height):
self.name = name
self.width = width
self.height = height
print("Please copy for file in the directory and give its name")
image_file = input("enter your file name for resize: ")
image1 = Image.open... |
5c29ce10f97dd5f71206ea9016da2f0ebe344305 | wangweikang/XiaoGua | /class001/homework.py | 964 | 3.890625 | 4 | import socket
"""
作业 1
8.10
请参考上课板书内容
"""
# 1
# 补全函数 parsed_url
def parsed_url(url):
'''
url 可能的值如下
g.cn
g.cn/
g.cn:3000
g.cn:3000/search
http://g.cn
https://g.cn
http://g.cn/
NOTE:
没有 protocol 时, 默认协议是 http
在 http 下 默认端口是 80
在 https 下 默认端口是 443
:return : tuple... |
2f66df4ca2a027bf1b6647fddb035262a0f8d9ed | skazurov/python | /lab_2_turtle/ex_8.py | 304 | 4 | 4 | import turtle
turtle.shape('turtle')
def make_square(s:int):
turtle.forward(s)
turtle.left(90)
turtle.forward(s)
turtle.left(90)
turtle.forward(s + 5)
turtle.left(90)
turtle.forward(s + 5)
turtle.left(90)
s = 0
for i in range(10):
make_square(s)
s += 10
|
c56a9ececdccb538b941462ee512dc6443a85db6 | jelares/6.006 | /ps-7-template/ship_server_stats.py | 5,130 | 4.0625 | 4 | def ship_server_stats(R, s, t):
'''
Input: R | a list of route tuples
s | string name of origin city
t | string name of destination city
Output: w | maximum weight shippable from s to t
c | minimum cost to ship weight w from s to t
'''
w, c = 0, 0
###########... |
a402404001bba8070b3f98bd9ac871ba7366fce1 | don2101/APS_problem | /SWEA/python/Stack/4869.py | 306 | 3.609375 | 4 | tc = int(input())
def cal(n) :
k = 1
for i in range(2, n+1) :
if i&1 :
k = k*2 - 1
else : k = k*2 + 1
return k
for t in range(1, tc+1) :
ans = 0
width = int(input())
n = width // 10
ans = cal(n)
print("#{} {}".format(t, ans)) |
9ea65904b327393d79869f357f0dd1d66562c4af | DBA-Andy/Python_Training | /playingWithMutiThreading.py | 1,556 | 3.6875 | 4 | #!/usr/bin/python3
#Import Modules
from multiprocessing import Pool
def while_loop(limit, counter=0):
numbers = []
while counter <= limit:
''' Iterate through a meaningless list, at the end of which we'll print how long it took, and the contents of an arbitrary list we created '''
#print ("Th... |
0155e86b5f774fe88fb2d378f455e91a5e41dbe3 | Crbrodeur/NG_Senior_Project | /NG_Senior_Project-master/send_email.py | 1,541 | 3.640625 | 4 | import os
import sys
from email.headerregistry import Address
from email.message import EmailMessage
import smtplib
def create_email_message(from_email_address, to_email_address, subject, body):
"""Creates a message
Args:
from_email_address: (obj) the address sending the email
to_email_addr... |
8dae4e8687e9a00f44092924134e68ae01ae3ed0 | Bassield/pdsnd_github | /src/bikeshare_2.py | 7,538 | 4.28125 | 4 | import time
import sys
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv'}
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) cit... |
c4feded3e35a64c9f921f36aa59fcf421d3a6ca7 | Cherpomm/DataStructure | /5-4.py | 4,929 | 4.03125 | 4 | class Node:
def __init__(self, value):
self.value = value
self.next = None
self.previous = None
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
self.listsize = 0
def __str__(self):
if self.isEmpty():
return ""
... |
17282e64236469d2f5e77d3dc13da88a0bf743c6 | minekoa/til | /deeplearning/zero/4_4_1_gradient/src/gradient.py | 2,728 | 3.921875 | 4 | #!/usr/bin/env python3
#-*- coding: utf-8 -*-
import numpy as np
import matplotlib.pylab as plt
def numerical_gradient(f, x):
'''
# 数値勾配
## 定義
すべての変数の偏微分をまとめたものを勾配(gradient)という。
'''
h = 1e-4
grad = np.zeros_like(x) # xと同じshapeで要素がall0の配列を生成
for idx in range(x.size):
tmp_v... |
597f039ca439ba069fc549b4dfe2dfa1249baf3b | LRS4/mit-6.00.1x | /ps2c.py | 1,017 | 3.5625 | 4 | """
Bisection search:
Write a program to search for the smallest monthly payment such that we can pay off the entire balance within a year
"""
"""
Monthly interest rate = (Annual interest rate) / 12.0
Monthly payment lower bound = Balance / 12
Monthly payment upper bound = (Balance x (1 + Monthly interest rate... |
30be945b07081eecdc143c8c2f192a119e61fe26 | davidericossa/PiacentiniCattaneo | /main.py | 301 | 3.609375 | 4 | from polynomial import Polynomial
x=Polynomial([1,1,1])
y=Polynomial([0,1,2])
print(x.plus(y).coefficients)
x=Polynomial([1,1])
y=Polynomial([1,-2])
z=x.multiplied(y)
print(z.coefficients)
# 1 -x -2x^2
# D=1 + 8 =9
# x_1,2= 1 #3 /-4
#(x+1)*(-2x+1)=-2x^2-x+1=-2(x+1)(x-0.5) |
6c21f5a1c563589e798dd271f682243c2076d26b | traplordpanda/pythonUMBC | /python/pythonlabs/solutions/basics/basics_ex04.py | 733 | 4.125 | 4 | #!/usr/bin/env python3
""" A Solution For basics_ex04
Write a program that asks the user to enter a sentence.
• The program should determine and print the following information:
• The first character in the string of text and the number of times it
occurs in the string.
• The last character in th... |
6179792bbdc11c9ad9f81b82ea701c17b42b1992 | OsvaldoSalomon/PythonCourses | /02SecondCourse/RegEx.py | 241 | 4.4375 | 4 | import re
# Check if the string starts with "The" and ends with "Spain"
txt = "The rain in Spain"
x = re.search("^The.*Spain$", txt)
if x:
print("YES!, We have a match!")
else:
print("No match")
y = re.findall("ai", txt)
print(y) |
42aa7db12b4042bb0c349f0835b4c926515d8d93 | TesterCC/Python3Scripts | /kaiyuanyouce/otherpractice/compare_use_singleton.py | 1,905 | 3.921875 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'MFC'
__time__ = '2019-03-01 10:18'
"""
REF:https://www.cnblogs.com/shenbuer/p/7724091.html
方法三、使用python的装饰器(decorator)实现单例模式,这是一种更Pythonic的方法;
单例类本身的代码不是单例的,通过装饰器使其单例化
"""
def singleton(cls):
'''定义一个装饰器,它返回了一个内部函数getinstance(),该函数会判断某个类是否在字典instances中。
... |
b540518c11cd131bcabc2a3ab3d1fa897e2ce2da | raphaelscandura/python | /Python Collections parte 1 - Listas e tuplas/array-numpy.py | 232 | 3.703125 | 4 | import array as arr
import numpy as np
# Evitamos usar array, se precisamos de eficiência com números usamos o numpy
array = arr.array('d', [1,3.5])
print(array)
numeros = np.array([1,3.5])
print(numeros)
print(numeros + 7)
|
2e8e7591ef08edbcad487aa9b2b14a8af153cd3f | lijiale0625/lijiale-zuoye1 | /python_basic/100_examples/061.py | 776 | 3.546875 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
# if __name__ == '__main__':
# a = []
# for i in range(10):
# a.append([])
# for j in range(10):
# a[i].append(0)
# print a
# for i in range(10):
# a[i][0] = 1
# a[i][i] = 1
# for i in range(2, 10):
# for ... |
cf7a28148434cb32f41d2b76864d90c48a40777e | Devaaron7/Loan_Calculator | /Source Files/Calculator_Week2.py | 3,293 | 4.15625 | 4 | ## Changes to Discuss
# 1. Using Rounding Floats to get simple answers ( example 3.083212 ---> 3.01)
# 2. Let use a static input when testing code so we're working with the same numbers
## Ex: loan amount = 10,000 , rate = 4 , years = 30 , hoa = 100
## Using this online calculator to compare our coutput - https:... |
37afe8fa4cb86819da95f0a383b384409e5bd7ab | Joana666/Cybers3c | /Exercício4.Aula.py | 1,707 | 3.96875 | 4 | from pathlib import Path
p = Path('.')
import os, sys
#Criar diretorios
def makeDir():
print("Criar diretorio")
nome1 = input ("Introduza o nome para o diretorio: ")
if os.path.exists(nome1):
print("ERRO: Este nome já existe. Atribua outro.")
else:
print("Diretorio criado com sucesso!\n... |
9866441966dc7ab0da81eaaf59261cec2c36d2fa | joeyhuaa/Texas-Hold-Em | /poker/Poker.py | 6,333 | 3.78125 | 4 | # This program simulates poker hands
# No betting involved
# Purely mathematical outcomes
# Can run as many simulations as user inputs
# deal random hands to all players (2)
# simulate run out till showdown
# keep win counter for all players
# display win % at the end
# sort hands in ascending order from left to right... |
d9d7a5fd2489ac4940f3dd6db3783b86c3c36aab | Exodus111/Infinite-Adventure | /Test/raytest.py | 5,243 | 3.515625 | 4 | """
This is a test program for the Raycasting.py program I made for pygame.
The program performs a basic test of all three types of Rays with visual representation.
"""
import os, pygame
from raycasting import Raycasting
from pygame.locals import *
from vec2d import vec2d
class Main(object):
def __init__(self, si... |
b23113bf2f80af1efb37542ac066fadb3843582a | SamuelMiller413/Python_301 | /02_Classes_Objects_Methods/02_classes-objects-methods/try_class.py | 389 | 3.609375 | 4 | class Planet:
def __init__(self, name, system, size) -> None:
self.name = name
self.system = system
self.size = size
def __str__(self) -> str:
return f"\nPlanet: {self.name}\nSystem: {self.system}\nSize: {self.size}\n"
# test:
from try_class import Planet
pl... |
a0e7e88edc33bd179fbee1829150b9388e3aa83b | nhutphong/python3 | /_argparse/fromfile.py | 1,065 | 3.796875 | 4 | import argparse
from utils import design
#run: python3 fromfile.py @args.txt
my_parser = argparse.ArgumentParser(
description='doc args tu args.txt',
epilog='ban thich program khong!!!',
fromfile_prefix_chars='@'
)
#line1 ben file args.txt
my_parser.add_argument('name',
... |
bd5b1710a587f3bc386c24d480c1d388731a86b0 | DoosanJung/effective_python_study | /Chap3_Class/item25.py | 3,597 | 4.4375 | 4 | #!/usr/bin/env python
'''
* Brett Slatkin, 2014, "effective Python"
* Brett Slatkin's example code([GitHub](https://github.com/bslatkin/effectivepython))
* I modified the example code a bit to confirm my understanding.
Initialize parent classes with super
'''
# 1. Old way to Initialize a parent classd
class MyBaseCla... |
3c02e620430bc16be96d1cd92967efa7400c5210 | WojciechMula/gtkcrop | /dialog/SelectionView.py | 1,766 | 3.5 | 4 | OUTSIDE = 'outside'
INSIDE = 'inside'
LEFT = 'left'
RIGHT = 'right'
TOP = 'top'
BOTTOM = 'bottom'
LEFT_TOP = 'lt'
RIGHT_TOP = 'rt'
LEFT_BOTTOM = 'lb'
RIGHT_BOTTOM = 'rb'
class SelectionView(object):
def __init__(self):
self.se... |
4937f38223d2d83d6ead446c4a7e66ec7c3e285b | DongXiangzhi/working | /for.py | 245 | 4.28125 | 4 | print('My name is')
for i in range(5):
print(str(i))
print('My name is')
for i in range(5, 20):
print(str(i))
print('My name is')
for i in range(5, 20, 2):
print(str(i))
print('My name is')
for i in range(5, 2, -1):
print(str(i)) |
5e8eb704bb1069b94ca4340b92c732c9721741ed | talathom/Summer2019Extra | /Sport/Game.py | 3,860 | 3.578125 | 4 | import random
class Game:
def __init__(self, home, away):
self.home = home
self.away = away
self.awayScore = 0
self.homeScore = 0
def fieldGoal(self, kickingTeam, yard):
fg = random.randint(1, 100)
yard += 17
fgMade = False
if yard < 20:
... |
03f9477d7710b688b35867edbaf2e857a32ace05 | PrathapReddy456/SeleniumPython | /PythonBasics/IfandFor.py | 421 | 3.96875 | 4 | #If condition
name = "Prathap";
if name == "Reddy":
print("It's False")
else:
print("It's True")
# For Loop
val = [2,3,4,5,6]
for i in val:
print(i*3)
# Sum of 5 natural numbers
sum = 0
for j in range(1, 6):
sum = sum + j
print(sum)
# when have to jump 2 index ex: in Java i+2 (i++)
for k in range(1,... |
0b5a312181e15d561268f6b07a2b43851d014694 | yuuuhui/Basic-python-answers | /梁勇版_6.25.py | 1,176 | 3.796875 | 4 | def isprime(n):
isp = True
divisor = 2
while divisor < n:
if n % divisor == 0:
isp = False
break
else:
isp = True
divisor += 1
return isp
"""def isprime(x):
c... |
ba7d49f11d722ef9bf311dbec96acb8f8cda05cf | Chocological45/CS50 | /pset6 Python/dna/dna.py | 1,752 | 3.890625 | 4 | import csv
import sys
import re
def main():
# Check the arguments passed for errors
if len(sys.argv) != 3:
# Exit if missing arguments
sys.exit("Usage: python dna.py data.csv sequence.txt")
# Read the Data file
fData = open(sys.argv[1])
data = list(csv.reader(fData))
# Read ... |
f97d0d7e045923feaa2c98cfc0397a522a525e43 | pwang867/LeetCode-Solutions-Python | /1017. Convert to Base -2.py | 932 | 3.671875 | 4 | # time/space log(N)
# this method can be generated to any K-base
class Solution(object):
def baseNeg2(self, N):
"""
:type N: int
:rtype: str
"""
if N == 0 or N == 1:
return str(N)
res = []
while N != 0:
res.append(N%2) # res.append(N... |
e0fcb6431b14a5af453ef8619c9f37e6f9697e20 | fndalemao/Python | /Aulas/aula08a.py | 214 | 4.0625 | 4 | from math import sqrt
import emoji
num = int(input('Digite um número: '))
raiz = sqrt(num)
print('A raiz quadrada de {} é {:.2f}'.format(num, raiz), end=' ')
print(emoji.emojize(':sunglasses:', use_aliases=True)) |
9923b153c39d61be19fd26ff5512b6da7630fdca | ttommytrinh/Codewars-Kata | /IQ_Test.py | 1,035 | 4.53125 | 5 | """
Bob is preparing to pass IQ test. The most frequent task in this test is to
find out which one of the given numbers differs from the others. Bob observed
that one number usually differs from the others in evenness. Help Bob — to check
his answers, he needs a program that among the given numbers finds one tha... |
2219c24f40926cfd7a8cff0512936403de779f8a | yskang/AlgorithmPractice | /leetCode/minimum_height_trees.py | 1,329 | 3.78125 | 4 | # Title: Minimum Height Trees
# Link: https://leetcode.com/problems/minimum-height-trees/
from typing import List
from collections import defaultdict
class Problem:
def __init__(self) -> None:
self.graph = defaultdict(lambda: set())
def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> Lis... |
96cf3b772123fea2fea179b231e8675bd4d74ef9 | shabidkhan/python_files | /debugging.py | 1,606 | 4.09375 | 4 | # print("we will leatn debugging by removin all the error from this python file by removin all the error from this python file")
# year = str(2016)
# name = 'NavGurukul'
# print(name+', '+year+" mein start hua tha!")
# a=(int(input("enter the no.")))
# b=(int(input("enter another no.")))
# print(a+b,a-b,a*b,int(a/... |
13af3e0a4c02f02f7897321cd8709bb79abacfbf | AkashSDas/python_code_snippets | /Socket/Sending-and-Receiving-Python-Objects/Server.py | 1,171 | 4.125 | 4 | # ###### Server Side ######
# ==========================
# ### Serialization in python ###
# Pickling or Serialization or Flattening in Python is we are converting the python object that we want to send into bytes
# We can send and receive things we pickled in python via sockets. We can pickle objects in python and o... |
c008e9f276fd5130a997aa49d280298ddd89cf74 | Boorneeswari/GUVI_PROGRAMS | /range.py | 118 | 3.640625 | 4 | inp=int(input())
lis=[]
for i in range(1,11):
lis.append(i)
if inp in lis:
print("yes")
else:
print("no")
|
4bfeb4a8b9ea9050f4fe2a797dde085255412800 | ElliottSRose/Socrates | /SocratesSpeaker.py | 1,515 | 3.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 11 09:39:05 2020
@author: elliott
"""
import pyttsx3
import threading
class Speaker():
def __init__(self):
self.engine = pyttsx3.init()
self.thread = None
def speak(self,text):
self.engine.setProperty('voice','com.a... |
7c5936847a4e48eca8a44867302186a7fc7e7513 | Wasylus/lessons | /lesson35.py | 5,463 | 3.765625 | 4 | class Fighter(object):
def __init__(self, name, health, damage_per_attack):
self.name = name
self.health = health
self.damage_per_attack = damage_per_attack
def __str__(self):
return "Fighter({}, {}, {})".format(
self.name, self.health, self.damage_per_attack... |
bc0be1ebca49dfb3f6e96618d7792d8dc0e3e253 | nurulsyfiqah/algorithmVivaMerged | /VivaMerged/2aRabinKarb.py | 1,142 | 3.515625 | 4 | def Rabin_Karp (pattern,text, q,d):
P = len(pattern)
T = len(text)
i=0
j=0
hashP = 0
hashT = 0
hash = 1
mark = False
for i in range(P-1):
hash = (hash*d) % q
for i in range(P):
hashP = (d*hashP+ord(pattern[i])) % q
hashT = ... |
61ec8c8bab33ff9d24d9bfce0b34fc1eae2d6c2b | AdamZhouSE/pythonHomework | /Code/CodeRecords/2064/60763/275565.py | 802 | 3.59375 | 4 | def toInt(a):
if a == 'I':
return 1
elif a == 'V':
return 5
elif a == 'X':
return 10
elif a == 'L':
return 50
elif a == 'C':
return 100
elif a == 'D':
return 500
elif a == 'M':
return 1000
def toInt1(b,a):
if a == 'V':
retu... |
1a3046006fcd3e3336d68e0110d5a3a78d5b84ef | max1mka1/text_analysis_tasks | /Project_2/main.py | 2,643 | 3.546875 | 4 |
'''
2. Напишите программу, которая считывает содержимое текстового файла
и выводит на экран слова, сгруппированные по первой букве. Слова в файле
разделены пробелами. Предложения разделены точками.
Реализация должна быть основана на принципах ООП.
'''
import re
class MainApp():
# функция инициализации... |
4ec0475ea928e4c57f2bcd3bb374cdab7900ebfe | PlumpMath/DesignPatternsWebProgramming | /library/library.py | 827 | 3.8125 | 4 | class MyOrder(object):
def __init__(self):
self.__order_list = []
#have an array to hold order info
#have some way to add to order
#Generate order total at the end
#Calcualte order total and pickup time
def addOrder(self, m):
self.__order_list.append(m)
... |
0e3896d888ef8626c2f240cc58238c4532b9e5d6 | Ghong-100/Python | /Practice/file_IO.py | 2,802 | 3.5625 | 4 | # score_file = open("score.txt", "w", encoding="utf8")
# print("수학 : 0", file=score_file)
# print("영어 : 50", file=score_file)
# score_file.close()
# score_file = open("score.txt", "a", encoding="utf8")
# score_file.write("과학 : 80\n") # 이건 자동 줄바꿈을 안해줌
# score_file.write("코딩 : 100\n")
# score_file.close()
# score... |
59224a935f0277dfa73189f20cfaa1f1f843df48 | umeshahp/coredatastruct | /coredatastruct/BST.py | 3,262 | 3.734375 | 4 |
templist = []
class Node:
def __init__(self, value):
self.data = value
self.right = None
self.left = None
class BST:
def __init__(self):
self.root = None
def create_newnode(self, value):
node = Node(value)
return node
def find2insert(self,root, node)... |
615504ee0a2c3df72b500a79a0f885b9334c5818 | rew0809/python-challenge | /PyBank/main.py | 2,284 | 3.578125 | 4 | import os
import csv
csvpath = os.path.join("Resources","budget_data.csv")
with open(csvpath) as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
print(csvreader)
csvheader = next(csvreader)
#Define variables for scanning csv and counting
numMonths = 0
profitLoss = 0
avgDi... |
75d701ad4f5d02ab040ebc0741340e85d106a7f3 | Rizky1202/TUGAS-UAS-Linear-Regression | /UAS-Rizky-Febriansyah.py | 1,308 | 3.984375 | 4 | # Simple Linear Regression
# Import Library
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import sklearn
# Memanggil dataset
datasets = pd.read_csv('Salary.csv')
#Sumbu X adalah Pengalaman Kerja dan Sumbu Y adalah Gaji
X = datasets.iloc[:, :-1].values
Y = datasets.iloc[:, 1].v... |
5c2c016c8598ea965da3a0017c287820cc170a3a | Simon-Lee-UK/blackjack-game | /blackjack/blackjack_main.py | 8,416 | 4.21875 | 4 | """
This module defines the flow of actions required to play a game of blackjack.
Classes that define game objects are imported from supporting modules. The 'run()' function is called when the
module is executed as a script. This function initiates a game of blackjack and loops through the required flow of
actions to ... |
2fca88a44e7157cdd1638e0e7dcef5645a0ff3ff | Lykaos/Programming-Under-Pressure | /Python/Graphs/George/Dijkstra.py | 5,330 | 3.921875 | 4 | ############################################################
# #
# DD2458 Problem Solving and Programming Under Pressure #
# Lab 2 - Non Negative Weights #
# Eduardo Rodes Pastor (9406031931) #
# ... |
ad4266809a2696ca8a0ac2ff65efcbef3117b920 | pranavmodx/DS-Algo | /Python/singlyLinkedList.py | 7,385 | 4.0625 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class singlyLinkedList:
def __init__(self):
self.head = None
def isEmptyList(self):
if self.head is None:
return True
return False
def createList(self):
print('Ente... |
750bb81815316e86c492e3f044ed18d396953374 | dataOtter/CodeFights-Python3 | /challenge10_obfuscation.py | 2,600 | 4.21875 | 4 | def codeObfuscation(data, program):
"""Input: array.integer data. A data list that stores the type of each data cell,
represented as integer. For the exact type, see the chart in the description above.
Guaranteed constraints: 0 ≤ data.length ≤ 255.
[input] string program. A string that represents the pr... |
79f244e7729ceebb56aacb5b32c531943243276c | ramadhanriandi/web-scraper | /src/scraper.py | 2,652 | 3.53125 | 4 | from selenium import webdriver # for web driver
from bs4 import BeautifulSoup # for scraping
import time # for delaying
import json # for converting to json
driver = webdriver.Firefox(executable_path='/home/riandi/Projects/py/web-scraper/src/geckodriver') # using geckodriver as web driver
driver.get('https://www.fif... |
289a611fd14dc3eda24a676fcf78735d43815ef9 | oc0de/pythonEpi | /chap9/5.py | 469 | 3.890625 | 4 | def setJumpOrder(l):
if not l: return None
order = 0
s = [l]
while s:
cur = s.pop()
while cur and cur.order == -1:
cur.order = order
order += 1
s.append(cur.next)
s.append(cur.jump)
def setJumpOrder(l, order):
if l and order != -1:
... |
aae3b21f3b0c1f198475989c24defdd19704e482 | rritec/Trainings | /01 DS ML DL NLP and AI With Python Lab Copy/02 Lab Data/Python/Py29_6_Create_Generators.py | 416 | 4.15625 | 4 | # Create a list of strings
std = ['Ram Reddy', 'Rabson', 'Robert', 'Nancy']
# Define generator function get_lengths
def get_lengths(input_list):
"""Generator function that yields the
length of the strings in input_list."""
# Yield the length of a string
for person in input_list:
yield len(pers... |
e66f9743e565418b37d150c0e83a54e902a5d208 | benjdj6/LeetCode | /Algorithms/344-ReverseString.py | 264 | 4.03125 | 4 | # In python the -1 element of a list is the last element
# So to reverse a string you can simply go from -1 backwards
class Solution(object):
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
return s[-1::-1] |
2c9199c70166b7bc72bb1cbe6aca5dd03d7385a7 | patthrasher/codewars-practice | /kyu7-19.py | 564 | 4.09375 | 4 | # A Tidy number is a number whose digits are in non-decreasing order.
# Given a number, Find if it is Tidy or not .
def tidy_number(n) :
# first solution
s = str(n)
i = 1
for each in s :
if i == len(s) :
return True
elif int(s[i]) < int(each) :
return False
... |
2a084717d49432d51d289b22de010a51401dc22e | urvishvasani/Sync-Ends | /src/parser.py | 2,602 | 3.515625 | 4 | import argparse
import json
class Parser:
"""
A class to represent the parser object which parses the command \
line input arguments.
Attributes
----------
parser : Instance of Parser class, needed to fetch CLI arguments
The design of the CLI is:
$ SyncEnd --api_key <key> --c... |
8746535c1e87d33ceeaf0dd88f0d9928ba2a5c77 | DaHuO/Supergraph | /codes/CodeJamCrawler/16_2_1/volodinmd/phone_number.py | 1,666 | 3.53125 | 4 | from __future__ import print_function
__author__ = 'volodin'
import re
prime = {'Z': ('ZERO', 0), 'W': ('TWO', 2), 'U': ('FOUR', 4), 'X': ('SIX', 6), 'G': ('EIGHT', 8)}
secondary = {'O': ('ONE', 1), 'T': ('THREE', 3), 'F': ('FIVE', 5), 'S': ('SEVEN', 7)}
def replace(line, word):
for char in word:
... |
2ad17666e60864d911f5ead6635c33cf71c0a04c | jherskow/intro2cs | /intro2cs/ex2/bmi.py | 620 | 3.984375 | 4 | ##########################################################################
# FILE : bmi.py
# WRITER : Josuha Herskowitz , jherskow , 321658379
# EXERCISE : intro2cs ex2 2016-2017
# DESCRIPTION: A non-biased solution to "Do i look fat?"
##########################################################################
def is_... |
dab00ac155c9f1e05c27cc02e8e69aba3de76786 | KajalSanjaySonawane/PythonPrograms | /Program_6.py | 2,781 | 4.09375 | 4 | """1.Write a program which accept number from user and display its digits in reverse order.
Input : 2395
Output : 5
9
3
2
def reverse(no):
r = 0
while no > 0:
r = r * 10
r = r + (int(no % 10))
no = no // 10 #floor opeartor //
return r
num = int(input("enter a numbe... |
15ff1538f9796f47bd16e4b062161c00a9b9cd2f | chuganghong/Python | /20140319/func_param.py | 240 | 3.640625 | 4 | # Filename:func_param.py
def printMax(a,b):
if a > b:
print a, 'is maxinum'
else:
print b, 'is maxinum'
printMax(3,4) #directly give literal value
x = 5
y = 7
printMax(x,y) #give variables as arguments
|
facd395750ca04718b0763131e317941c79b252f | abisheksudarshan/HackerRank | /Problem Solving/Algorithms/Greedy/Sherlock and The Beast.py | 387 | 3.78125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the decentNumber function below.
def decentNumber(n):
a, b = divmod(n,3)
while b%5:
b+=3
a-=1
print("5"*a*3+"3"*b if a>-1 else -1)
if __name__ == '__main__':
t = int(input().strip())
for t_itr in r... |
941db0e72d1567aa682acf38312b0386f30f8e47 | GaoFuhong/python-code | /study6/inherit.py | 1,297 | 4.40625 | 4 | # Author:Fuhong Gao
#继承
# class People: 经典类
class People(object): #新式类
def __init__(self, name, age):
self.name = name
self.age = age
self.friends = []
def eat(self):
print("%s is eatting..."%self.name)
def talk(self):
print("%s is talking..."%self.name)
def sleep... |
9ecd4b95023b62b8affdf11fbade4ccb048be802 | Valken32/small-projects | /dicerollercode.py | 604 | 4.15625 | 4 | import random
print ("Welcome to Alexander's Advanced Dice Roller! \n In this program, you will be able to input two numbers. a minimum and a maximum, and I will roll them for you!")
answer = input("What is your minimum?")
x = answer.lower().strip()
answer = input("What is your maximum?")
y = answer.lower().strip(... |
36e0bdf70da5363499a8bd56dba42d82e780d1ec | shiannn/Phys4009-Numerical-Analysis-Kakix | /5-6.py | 535 | 3.796875 | 4 | class Vector3D(object):
def __init__(self, x,y,z):
self.x = x
self.y = y
self.z = z
def __str__(self):
return ('(%g,%g,%g)' % (self.x,self.y,self.z))
def outer(self, input):
return Vector3D(self.y*input.z-self.z*input.y, self.z*input.x-self.x*input.z, self.x*input.y... |
b0211c20821b13e84055557e0ab0983fdbe58a6a | rahultc26/python | /tuple.py | 885 | 4.125 | 4 | #tuple
#creating Tuple
tup=(10,20,30,'rc')
print(tup)
#eg
tup=(20,) #if your creating tuple for one value you
#must put comma after value otherwise it will consider as integer type
print(tup)
#eg
tup=(40)
print(tup) #it displays int value 40 now
#finding
print(type(tup)) #displays class int;
... |
129dd7890099320c5e2c5f49d1a92d4b8d8f477c | htmlprogrammist/kege-2021 | /Bariants/statgrad-ov-03-21/task_6.py | 629 | 3.953125 | 4 | """
Определите, при каком наименьшем введённом значении переменной S
программа выведет число 13. Для Вашего удобства программа представлена
на четырёх языках программирования.
"""
s = int(input())
s = 10 * s + 7
n = 1
while s < 2021:
s += 2 * n
n += 1
print(n)
number = 0
answer = 13
while number < 1000:
s ... |
89eedfc22a53eb476370deb655240cac54216e6f | ivanvladimir/soluciones_count_words_2017 | /main.py | 1,691 | 3.5 | 4 |
import re
import operator
import sys
dir_file = sys.argv[1]
n_words = int(sys.argv[3])
try:
isLower = sys.argv[4]
except IndexError:
isLower = ''
pattern_www = re.compile(r'www')
pattern = re.compile(r'\W*')
n_words_repeated = 0
dictionary = {}
list_common_words = []
file = open("common.txt", en... |
96242c3d525ad28ccbec1fcfe2a69b1f9f2fc352 | He1LBoy34/Egoroff_tutorial | /venv/include/Lesson 24/Factorial.py | 152 | 3.828125 | 4 | n = int(input("Введите число для поиска факториала: \n"))
pr = 1
for i in range(1, n + 1):
pr = pr * i
print(pr)
|
008099ef6f6f533c869c6c552183861263f686ea | revanth96/coding | /noofwordoccuring.py | 155 | 3.578125 | 4 | mystring =input()
result={}
value=mystring.split(" ")
for i in value:
if i in result:
result[i]+=1
else:
result[i]=1
print(result)
|
b6590c05506f995f1e2e074012cfa25e9f05bd59 | sharifulislam21/python-tutorial | /power.py | 70 | 3.546875 | 4 | #sqaure of a number
import math
p = math.pow(3,2)
print ("power" , p) |
e4e25349714db906dbccfb1f14254d37aceb3a74 | Rishabh1501/learning-tkinter | /3-Basics_2/2-image_viewer.py | 2,617 | 3.828125 | 4 | import os
from tkinter import *
from PIL import ImageTk, Image
root = Tk()
#adding a title
root.title("Image-Viewer")
#adding a favicon/icon
root.iconbitmap("3-Basics_2\\favicon.ico")
# #adding an image
# my_img = ImageTk.PhotoImage(Image.open("3-Basics_2\\images\\picture.png"))
# #creating a label for the image
# m... |
d35b9e53d552f140f0c59882d9b2bdd1860a3a1e | Lwq1997/leetcode-python | /primary_algorithm/array/containsduplicate.py | 793 | 3.625 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/4/10 23:02
# @Author : Lwq
# @File : maxProfit.py
# @Software: PyCharm
"""
给定一个整数数组,判断是否存在重复元素。
如果任何值在数组中出现至少两次,函数返回 true。如果数组中每个元素都不相同,则返回 false。
示例 1:
输入: [1,2,3,1]
输出: true
示例 2:
输入: [1,2,3,4]
输出: false
"""
class Solution:
@staticmethod
def containsduplicat... |
76844a685679df39f26008db114e440f927e2cc6 | sanyam912/Python-Course | /swapping.py | 164 | 3.84375 | 4 | x=int (input('enter x number - '))
y=int (input('enter y number - '))
x=x-y
y=y+x
x=y-x
print("after swapping x became - ",x)
print("after swapping y became - ",y)
|
ca4769028b376e925a248e8c879b750e16b27794 | sharabao13/mypython_t | /prime_number.py | 208 | 3.75 | 4 | ###判断一个数是否是质数
num = input("请输入一个数:")
num = int (num)
for i in range(2,num-1):
if num % i == 0:
print ("不是质数")
break
else:
print ("是质数") |
f14b0230b58764c9b96e93cc71f6427ba49cdb90 | dedickinson/quickcert | /quickcert/cli/cli_util.py | 1,068 | 4 | 4 | from getpass import getpass
def prompt_for_password(prompt: str = 'Enter a password: ',
verify_prompt: str = 'Re-enter the password: ',
validate: bool = True) -> str:
""" Utility for password prompts
Allows for password validation. If the passwords don't match,... |
e93fae1ebf88e7507c312fb8064f14a484a92187 | ZhongXinWang/python | /generator.py | 1,874 | 3.8125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#Author:Winston.Wang
from collections import Iterable
print("---------使用生成器替换列表生成式节约空间----------");
#列表生成式
print([v for v in range(10)])
#[]替换为()变成生成器
g = (v for v in range(10));
print(g)
#获取生成器的值
print(next(g))
print(next(g))
print(next(g))
print(next(g))
#判断generator是否式... |
e59952bf91f05e07824e968994f6e694079ae6eb | 00009815/seminar-5 | /main.py | 102 | 3.640625 | 4 | for i in range(0, 7):
if i == 0 or i == 6:
print("****")
else:
print("* *")
|
fce756eaf898c16fde8ccd953e32566daa8a695a | gudiausha/Data-Structures-and-Algorithms | /arrays.py | 3,058 | 4.28125 | 4 | # author: Pratyusha
# array is a list of homogenous elements. It is a linear data structure
# we are creating an array on top of inbuilt datastructure 'lists' in python
# so we can make use of most of its methods
# By default, the array type == int, it can be changed to any other datatype
# The following operati... |
4202cc98b5cc043dc9285dee5e55259fa3238f44 | Botany-Downs-Secondary-College/password_manager-felix-s | /passwordManager.py | 3,970 | 4.15625 | 4 | #passwordManager
#creates and displays passwords
#variables and lists
masterAccountsList = [["test", "12345"], ["test2", "123456"]]
accountDetailsDict = {"test":{"testa":["aa","aaa"], "testb":["bb","bbb"]}, "test2":{'t1':['11','111'], 't2':['22','222']}}
def options(mode):
print("Choose a mode by entering... |
9131d590dfe787c0ef1beed0db64c54658e4609c | tyralek/python_basics | /lab/02/test_containers.py | 2,407 | 3.71875 | 4 | '''
@author: ltyrala
Container exercise
'''
import unittest
class SomeMagic:
def __init__(self, x):
self.x = x
class Test(unittest.TestCase):
def setUp(self):
self.list = [1, 2, 3, 4]
self.flight_rating = {'batman': 4,
'superman': 10,
... |
2a1fb420503ef960992135b45724a8813571ec0b | chingdrop/Python-practice | /gasMileage.py | 4,726 | 4.25 | 4 | # Craig A. Hurley
# 2017/10/27
# gasMileage.py
def distance(mileInt, mileage):
# The distance is calculated
dist = mileInt - mileage
return dist
def totalDistance(dist, totalDist):
# calculates the total distance.
totalDist = totalDist + dist
return totalDist
def totalGas(gasUse... |
c57939bce9f0221dcff9b51a633cff8fba61bfb6 | TomoyukiEguchi/100_Days_of_Code | /Mail Merge Project Start/main.py | 1,054 | 3.796875 | 4 | #TODO: Create a letter using starting_letter.txt
#for each name in invited_names.txt
#Replace the [name] placeholder with the actual name.
#Save the letters in the folder "ReadyToSend".
#Hint1: This method will help you: https://www.w3schools.com/python/ref_file_readlines.asp
#Hint2: This method will also hel... |
8bbd3a78f4575c29ab92d8b18b5bae3c5d70bf92 | JonhFiv5/aulas_python | /aula_44_combinations_permutations_product.py | 1,543 | 4.28125 | 4 | from itertools import combinations, permutations, product
# Combinations, permutations e product - itertools
# Combinação - Ordem não importa
# Permutação - Ordem importa
# Ambos não repetem valores únicos
# Produto (arranjo com repetição) - Ordem importa e repete valores únicos
# É aquele assunto de matemática, cons... |
44f5f20c78f74c0b1f2ca9a66e09703576f0c5d5 | Olliehughes987/binary-boarding | /day5.py | 1,499 | 3.796875 | 4 | # --- Day 5: Binary Boarding --- #
# https://adventofcode.com/2020/day/5
# I managed to solve part 1 pretty easily, working out the max ID was 913.
# The second half of the question took a bit of tweaking, however I managed to come up with the
# solution.
import math
takenSeats = []
def calculateSeatID(c... |
20a0a711a4bcaafbd652b70ed679bbf8b1af2d8e | Pycone/Python-for-Beginners | /src/ch11/test_calculator.py | 830 | 3.671875 | 4 | import unittest
from calculator import Calculator
class CalculatorTest(unittest.TestCase):
def setUp(self):
self.calc = Calculator()
def tearDown(self):
self.calc = None
self.answer = None
def test_plus(self):
self.answer = self.calc.plus(1, 2)
self.assertEqual(se... |
15df5a8b00366b2e4a75ccc4aab4e617a1301410 | Sillinesser/Sillinesser | /HW.4Les.2.py | 1,317 | 3.890625 | 4 | #1. Роздрукувати всі парні числа менші 100
# (написати два варіанти коду: один використовуючи цикл while,
# а інший з використанням циклу for).
#a)
#print(list(range(0,100,2)))
# b)
# i = 0
# while i < 100:
# if i % 2 == 0:
# print(i)
# i = i + 1
#c)
# for i in range(100):
# i... |
7c2a115fef368c1124806fd561501bef175b17a6 | yangmyongho/3_Python | /chap02_Control_lecture/step03_for.py | 5,278 | 3.6875 | 4 | '''
제어문 : 반복문(for)
for 변수 in 열거형 객체 :
실행문
실행문
열거형 객체(iterable) : string, list, tuple, set/dict
제너레이터 식 : 변수 in 열거형 객체( 원소 순회 -> 변수 넘김)
'''
# 1. string 열거형 객체 이용
string = "나는 홍길동 입니다."
print(len(string)) # 11
for s in string : # 11회
print(s, end='/') # 나/는/ /홍/길/동/ /입/니/다/./
for s in s... |
67c0ffdf5092270ae6b9a4b60373e2afa30aff3f | emerisly/python_learn | /python_learn/MagicSquare_John.py | 2,492 | 3.84375 | 4 | import re
# creating square
def createSquare(size):
for i in range(size):
new = []
for j in range(size):
new.append(1)
square.append(new)
# returns the sum of a given row
# row -> which row
def sumRow(row):
return sum(square[row])
# returns the sum of a given column
def su... |
9811fe6ea85c8095f37d8c6af22779e574656efd | anjan111/001_raj_shalu | /001_Python Operators/002_rectangler.py | 388 | 4.15625 | 4 | # wap for area of rectangle
L = input("enter L : of rectangle in meters : " ) # str int in python 3
L = int(L)# we don't required in python 2
W = input("enter w : of rectangle in meters : " ) # str int in python 3
W = int(W)# we don't required in python 2
area = L * W
print("Area of Rectangle is : ",... |
3fbcacd25b2c4e707be404076bc71f568be198f3 | AtulRajput01/Data-Structures-And-Algorithms-1 | /Geeks For Geeks Solutions/python/max_winning_score.py | 2,138 | 4.15625 | 4 | """
This problem was asked recently in Geeksforgeeks Interview Series Morgan Stanley
Problem - In an online game, N blocks are arranged in a hierarchical manner. All the blocks are connected together by a total of N-1 connections.
Each block is given an ID from 1 to N. A block may be further connected to ... |
fd005dc974ddced112690be1018441610d75e0e6 | dincaz2/uncertain_obs | /circuits/structures/trie.py | 971 | 3.78125 | 4 | def make_trie():
return {True:False}
def add_to_trie(trie, diagnose):
if not diagnose:
trie[True] = True # special representation for the empty diagnose
curr = trie
for comp in diagnose:
curr = curr.setdefault(comp.name, {})
def check_trie_for_subsets(trie, diagnose, i=0, root=True):
... |
379a0eeba541ae6db6068de3b8136a1d4775de62 | AlexeyMartynov91/Python | /lesson_5/homework_5_6.py | 1,231 | 3.578125 | 4 | '''
Необходимо создать (не программно) текстовый файл, где
каждая строка описывает учебный предмет и наличие лекционных,
практических и лабораторных занятий по этому предмету и их
количество. Важно, чтобы для каждого предмета не обязательно
были все типы занятий. Сформировать словарь, содержащий
... |
77691c164c1bde0870d0a3130cf1b127633373b8 | komalupatil/Leetcode_Solutions | /Easy/Symmetric Tree.py | 1,505 | 4.09375 | 4 | #Leetcode 101. Symmetric Tree
#DFS
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution1:
def isSymmetric(self, root: TreeNode) -> bool:
if root == None:... |
1c4dbd2e90899077a98926ea75b3df71762fb941 | coolsync/todo | /other-space/py/py-start/08-comprehensions/01-comprehension-list.py | 411 | 4.125 | 4 | # 1. 循环实现;2. 列表推导式(化简代码;创建或控制有规律的列表)
"""
1.1 创建空列表
1.2 循环将有规律的数据写入到列表
"""
# nil list
l1 = []
# while
# i = 0
# while i < 10:
# l1.append(i)
# i += 1
# print(l1) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# for
# for i in range(10):
# l1.append(i)
# print(l1)
# comprehension
l1 = [i for i in range(10)]
print(l1... |
8148531358ad096c9d1b9070f1b0165175468655 | icebowl/python | /ed1/2.3.3.py | 357 | 4.125 | 4 | # your code goes here
hours = int(input("Enter the hours: "))
minutes = int(input("Enter the minutes: "))
totalminutes = (60*hours) + minutes
totalminutes = totalminutes + 15
newhour = int(totalminutes / 60)
newminute = int(totalminutes % 60)
if(newhour > 12):
newhour = newhour - 12;
print("Hours: "+str(newhour... |
60103fe6e238321ee84c88c398781a539f7e1975 | zoox101/TSPAlgorithm | /Topology/Closest_TSP.py | 756 | 3.53125 | 4 | import random
import math
def generate_point(max=10):
return (random.random()*max, random.random()*max)
def distance(point1, point2):
dx = math.pow(point1[0] - point2[0], 2)
dy = math.pow(point1[1] - point2[1], 2)
return math.sqrt(dx + dy)
points = []
for x in xrange(10):
points.append(generate_p... |
9bc446d52f4e4f04ab8312c7c1c5b6dfb4e54091 | BhargavReddy461/Coding | /Binary Tree/check_if_all_leafs_are-at_same_level_recursive.py | 1,460 | 4.25 | 4 | # Python program to check if all leaves are at same level
# A binary tree node
class Node:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Recursive function which check whether all leaves are at
# same lev... |
21e91a2d3a4e1e7bc14c55a97a97b8d96b6f09e2 | will-jac/CS5473-PDN | /HW1/UDP_Multiplier_Server.py | 1,172 | 3.5 | 4 | # UDPPingerServer.py
# We will need the following module to generate randomized lost packets
import random
from socket import *
# Create a UDP socket
# Notice the use of SOCK_DGRAM for UDP packets
serverSocket = socket(AF_INET, SOCK_DGRAM)
# Assign IP address and port number to socket
serverSocket.bind(('', 12000))
pr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.