blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
a7a804d1518142aefb7a29cea9b717875be88506 | 5t0n3/advent-of-code-2020 | /day05binary.py | 1,654 | 3.609375 | 4 | from functools import reduce
def update_range(old_range, update_char):
"""
Narrows the supplied range using `update_char` ("F", "B", "R", or "L").
"""
begin, end = old_range
split_point = (begin + end) // 2
if update_char == "F" or update_char == "L":
return (begin, split_point)
i... |
95dd11f08be140bcab84bacf6ffaf8ce37a77306 | djalvaro/python | /hello.py | 828 | 3.8125 | 4 | '''
Created on Sep 8, 2015
@author: PC-43
'''
'''
print("hello World")
# here is a Comment
u=0
i=1
z=2
if u==0 or i<2:
print("wahoo")
print("I am still in the if")
else:
print("U is not 0 and I is >2")
'''
'''
#def someFunction(a, b):
# print(a+b)
#someFunction(12,451)
... |
a8b4d5baa2dc87de19295ea4d5ea9e73bd00b5f1 | Daniel-Obara/Daniel-Obara.github.io | /2nd Lowest.py | 587 | 3.875 | 4 | n = int(input("Enter the number of students: "))
i=0
mScoreOne = 101
mScoreTwo = 101
mNameOne = ""
mNameTwo = ""
while i < n:
print("Please enter student", i+1, "name:")
nI = str(input())
print("Please enter student", i+1, "score:")
sI = int(input())
if(sI < mScoreOne):
mName... |
9c7619456dcc70fb116f039351182ca7912ce0ce | jbosboom/sigmars-gardener | /solver.py | 2,736 | 3.765625 | 4 | from typing import Dict, List, Tuple
import data
_cardinals = ['air', 'earth', 'fire', 'water']
_metals = ['lead', 'tin', 'iron', 'copper', 'silver', 'gold']
def solve(puzzle: Dict[int, str]):
# Gold "matches with itself" for the purposes of the moves list.
# Find the current metal, the least metal present.
... |
87134e4bfe7d4b26ae3267482c55d6905d1eaeaa | andersontmachado/Python_na_PRATICA | /Ex032-Ano Bissexto.py | 334 | 3.59375 | 4 | from datetime import date
ano=int(input('Em qual ano você quer analizar: Coloque 0 para o ano atual: '))
if ano ==0:
ano=date.today().year
if ano % 4 == 0 and ano % 100 !=0 or ano % 400 == 0:
print('O ano {} é \033[1;35m BISSEXTO\033[m'.format(ano))
else:
print('O ano {} \033[1;32mnão\033[m é BISSEXTO'.form... |
1f42534a911d2f4f5b166048963f06433ce106e6 | ELJust/bao | /BAO.py | 2,472 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Run a game of BAO.
"""
from BAO_functions import turn
from BAO_functions import pebbles_left
from board import print_field
from board import game_area
from strategies import *
from save import result_to_file
def play_game(strategy_p1, strategy_p2, max_allowed_turn_count):
"""
The p... |
b6c13ddb830b43a379c2f4973142df09141e406c | philipdongfei/Violent-Python-A-Cookbook-for-Hackers | /unzip1.py | 661 | 3.5625 | 4 | #!/usr/bin/env python3
import zipfile
def extractFile(zFile, password):
try:
zFile.extractall(pwd=password)
return password
except Exception as inst:
print(inst)
return
def main():
zFile = zipfile.ZipFile('evil.zip')
passFile = open('dictionary1.txt')
for line in pa... |
180cdede607bda40e85b3aee001f7c4ca0f911f7 | ag-lee/algorithm | /programmers/open_chatting.py | 539 | 3.640625 | 4 | def solution(record):
answer = []
user_info = {}
# get user info (uid, nickname)
for r in record:
if "Leave" not in r:
tokens = r.split(" ");
user_info[tokens[1]] = tokens[2]
# make answers
for r in record:
tokens = r.split(" ");
if "Enter" == ... |
183d70610062a7db90229faea2f9def9a3e62c44 | anuragrana/Python-Scripts | /merry_christmas_using_python.py | 2,929 | 4.28125 | 4 | #
# Python script to wish Merry Christmas using turtle.
# Author - Anurag Rana
#
from turtle import *
from random import randint
def create_rectangle(turtle, color, x, y, width, height):
turtle.penup()
turtle.color(color)
turtle.fillcolor(color)
turtle.goto(x, y)
turtle.pendown()
turtle.begin... |
ee7caca5734b3eab8b257bffb25fa0f42e3ec910 | zelinayas/Python | /belajarPy.py | 371 | 3.75 | 4 | print("this line will be printed")
x=6
if x==1:
print("x adalah 1")
else:
print("x bukan 1")
myfloat=7.0
print(myfloat)
myfloat1=float(7)
print(myfloat1)
a="hallo"
print(a)
a='hallo'
print(a)
one=1
two=2
three=one+two
print("1 + 2 =",three)
a=4
def cek(a):
b = a ** 0.5
if b == int(b):
print("b... |
3acf4f65b49b36a5a322b1b92447dda4e5709ecd | srtkRWT/SHA1 | /SHA1.py | 2,502 | 3.796875 | 4 | def sha1(inp):
def preprocess(inp):
'''
modify input
'''
bits = ""
for i in range(len(inp)):
bits += '{0:08b}'.format(ord(inp[i]))
inp_len = len(bits)
bits += "1"
while len(bits)%512 != 448:
bits += ... |
69f6f33f35942f5fc9e588439b16d3ac26fc5880 | momentum-cohort-2020-01/word-frequency-danecodesnc | /keeping_score.py | 956 | 4.25 | 4 |
#This is an example for the homework.
#Example: score_dict = {}
#score_dict['Dan'] = 0
# score_dict
# {'Dan': 0}
# We then create 3 people that will have scores in a game, Dan, Dee, and Ryan.
# score_dict['Dee'] = 0
# score_dict['Ryan'] = 0
# This will then prin... |
14378260c6e2c219c505c576d01dd90ac2a269c3 | tendolkar3/citrus | /server/core/lib/sensors/sensor.py | 4,782 | 3.578125 | 4 | from core.lib.physics.utils import constants as c
import math
from core.lib.internal.geometry import perpendicular_distance_of_point_from_line
from core import globals
class GPS:
@staticmethod
def get_position(x, y):
# ToDo: normal distribution around x,y
return [x, y]
class VehicleSpeedSens... |
342fc15c11176b926ff382e6d179963a9a02ea86 | Plasmoxy/DevMemories | /Python/scripts122014/turtle/sandbox1.py | 693 | 3.65625 | 4 | import time, random
from turtle import *
reset()
speed(1000000)
down()
def cube(xsize, ysize, zsize):
for i in range(1, 2):
forward(xsize)
left(90)
forward(ysize)
left(90)
#end for
forward(xsize);
left(135);forward(zsize/2);backward(zsize/2);right(135)
left(90);forward(ysize);right(90);
left(135);forw... |
77747ee590ebfe74e9145c3070ee2c1c7557b514 | Ksanbal/Algorithm | /1_Factorial/Factorial.py | 924 | 3.9375 | 4 |
# 2015100902 김현균
# Algorithm to solve Factorial
# 재귀함수
def factorial_recursive(n):
if n <= 1:
return n
else:
return factorial_recursive(n-1) * n
# 반복적 문제 해결
def factorial_loop(n):
result = 1
if n == 0:
return n
else:
for _ in range(1, n+1):
result = ... |
5fac004965ffd33d32e9219b3fe1e98e0566d4a1 | senlindu/Data-analysis | /books_1/chapter_4/sample.py | 2,547 | 3.515625 | 4 | import numpy as np
import random
import matplotlib.pyplot as plt
# 范例:随机漫步
# 我们通过模拟随机漫步来说明如何运用数组运算
# 从0开始,步长1和-1出现的概率相等
# 通过内置的random模块以纯Python的方式实现1000步的随机漫步
# position = 0
# walk = [position]
# steps = 1000
# for i in xrange(steps):
# step = 1 if random.randint(0, 1) else -1
# position += step
# wal... |
ff63bb71b917212f34ba0cc48010863731797f4f | leonardonorambuena/TI2011-2021 | /clase2/example_2.py | 144 | 4.03125 | 4 | number = int(input('Ingrese un número: '))
for i in range(number, -1, -1):
if i == 0:
print(i)
else:
print(i, end=',') |
a1c1f8d6243e1bec2d16c7308c12cc26bcf170fe | nurarenke/study | /find_sum_path__binary_tree.py | 1,127 | 3.859375 | 4 | '''Print path that sums to the value in a given tree.
From Cracking the coding interview, problem 4.9.
1
3 5
2 6 9 4
>>> Tree = Node(1, Node(3, Node(2), Node(6)), Node(5, Node(9), Node(4)))
>>> Tree.print_sum_path(10)
1
3
2
'''
class Node(object... |
82511efe10d0c48b96f2627e272a6b560f090d93 | open-dicom/dicom_parser | /src/dicom_parser/utils/format_header_df.py | 1,512 | 3.609375 | 4 | """
Definition of the :func:`format_header_df` utility function, used to display
a formatted version of a single DICOM header's information dataframe.
"""
import functools
from dicom_parser.utils import requires_pandas
@requires_pandas
def format_header_df(df, max_colwidth: int = 28) -> str:
"""
Formats a ra... |
235ff9a3597f985cc99db3fe0eea4a4ec6b5bf9a | Lindamaja/MyExercises | /ex7.py | 603 | 3.59375 | 4 | # print line
print "Mary had a little lamb."
# print line
print "Its fleece was whise as %s" %'snow'
# print line
print "And everywhere that Mary went."
# print print '.' 10 times
print "." * 10 #what'd that do?
#define variable to letter
end1 = "C"
end2 = "h"
end3 = "e"
end4 = "e"
end5 = "s"
end6 = "e... |
0921b0407326323eb618c58b80255589c1eb460c | liv-yaa/Py_Code_Challenges | /CTCI_2020/double-linked-list.py | 5,657 | 4.375 | 4 | # Singly Linked List Node
class LLNode:
""" LinkedListNode class
> Sufficient to create a liked list (in main)
"""
def __init__(self, data):
""" Initializes a node in a linked list *with 'data' as only argument*
(we will set 'next' to None for now)
(Has to be generated after creating the nodes)
"""
... |
29fda78bffd34e5dee94497d21d334f697d83398 | jgosier/Ujima | /lib/myDict.py | 6,856 | 3.59375 | 4 | class myDict(dict):
"""A case insensitive dictionary that only permits strings as keys."""
def __init__(self, indict={}):
dict.__init__(self)
self._keydict = {} # not self.__keydict because I want it to be easily accessible by subclasses
for entry in indict:
... |
e9d18c3441f1f706c3620c0f3559fd17a9ffc422 | SunilMali-158/Python | /11_set.py | 349 | 3.71875 | 4 | # set can have only immutable objects stored
x = {1, 3, 5, 7}
print(type(x))
# print(x)
#set is mutable
# y = x
# y.clear()
# print(x)
x.add(9)
print(x)
x.add(7)
print(x)
x.discard(7)
print(x)
print(len(x))
x = {"1", "22", "3"}
print(x)
# y = {[1, 2, 3], [12, 5, 6]} throws error because list is... |
45076d538b6ef92f733093861d65cc159abefbac | davidevaleriani/python | /ball.py | 1,925 | 4.15625 | 4 | #######################################################################
# Bouncing ball v1.0
#
# This program is a first introduction to PyGame library, adapted
# from the PyGame first tutorial.
# It simply draw a ball on the screen and move it around.
# If the ball bounce to the border, the background change c... |
8ad8892aee46578e07b0f31ada6ca4dc812d3c9a | INSHAL123/assignments | /labA6/fibofunction.py | 206 | 3.96875 | 4 | def fibo(n):
a,b=0,1
print(a)
print(b)
for i in range(n-2):
c=a+b
a=b
b=c
print(c)
n=int(input("Enter the number of terms"))
fibo(n)
|
d3133012dca9aedeaa71874d3bb4a8ae0427c052 | m-rohit/python-for-beginners | /InstanceVar.py | 231 | 3.6875 | 4 | class Girl:
gender = 'female'
def __init__(self, name):
self.name = name
r=Girl("Richa")
s=Girl("Simmi")
print(r.gender)
print(s.gender)
print(r.name)
print(s.name) |
9e4d73c0695b723786a69a63449dadf257534da2 | sandeep9889/paint-app-using-python-turtle | /python_tutorial/oops/oops4_classmethod.py | 540 | 3.71875 | 4 | class Employ:
no_of_leaves= 8
def __init__(self,aname,asalary,arole): #here __init__ is constructor of class
self.name = aname
self.salary = asalary
self.role = arole
@classmethod #it can change value of class variable by instance variable
def change_leaves(cls,newleave... |
eae747dd757739f0b9357399d40d7b06dbe36392 | 60rzvvbj/pythonExperiment | /pythonExperiment/experiment4/py6.py | 476 | 3.96875 | 4 | # 6.练习随机数应用。请生成50个随机数据,模拟一个班的考试成绩(要求在40~100分之间)。
# 计算这批数据的平均分、最高分和最低分,并排序由高到低输出。
import random
lst = [random.randint(40, 100) for i in range(0, 50)]
print('成绩为:')
print(lst)
print('最高分:{},最低分{},平均分{}'.format(max(lst), min(lst), sum(lst) / len(lst)))
lst.sort()
lst = lst[::-1]
print('排序后:')
print(lst)
|
c751285a676c7694dc4c9be135e374d53c4a7189 | amenson1983/2-week | /_2_week/Lesson 2.py | 308 | 3.796875 | 4 | a = 2
b = 3
c = 3
d = 1
max = 0
if a >= b and a>=c and a>=d:
max = a
elif b >= a and b>=c and a>=d:
max = b
elif c >= a and c>=b and c>=d:
max = c
else: max = d
print(max)
num = 0
num1 = 0
if max == a or max == b:
num = 1
if max ==c or max == d:
num1 = 1
count = num + num1
print(count)
|
947464cc9f76eaadc1504ddf230ec4e0f2087c28 | osamunmun/python_vs_ruby | /list_insert.py | 297 | 3.828125 | 4 | #encoding: UTF8
import time
list = []
for i in range(1000):
list.insert(0,i)
before_loop = time.clock()
for i in range(1000):
pass
after_loop = time.clock()
before = time.clock()
for i in range(1000):
# list.pop(0)
list[0]
pass
print (time.clock()- before - (after_loop - before_loop))
|
b70421956c4943a051036df681022eae4797c58f | EarthChen/LeetCode_Record | /easy/path_sum.py | 813 | 3.984375 | 4 | # Given a binary tree and a sum, determine
# if the tree has a root-to-leaf path such that adding up
# all the values along the path equals the given sum.
class Solution:
def hasPathSum(self, root, sum):
"""
判断从根到叶子节点的值之和是否有等于sum的
:param root: TreeNode
:param sum: int
:retu... |
6307ce0ff79f0b39826fe9dfec4613ae7a13721a | deepagitmca/Basic-programming-using-python | /default_argumentfibonacci.py | 187 | 3.640625 | 4 | def fib(n=8):
a,b=0,1
result = []
for i in range(n-1):
result.append(b)
a,b=b,a+b
return result
print(fib(4))
print(fib()) |
9c2fa54bf93f7e24804e0df1e15c0c210374e6ed | mokshithpyla/DS-Algo | /LeetCode/Easy/LinkedListPalindrome.py | 923 | 4.0625 | 4 | # Given a singly linked list, determine if it is a palindrome.
#
# Example 1:
#
# Input: 1->2
# Output: false
# Example 2:
#
# Input: 1->2->2->1
# Output: true
# Follow up:
# Could you do it in O(n) time and O(1) space?
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self... |
4249301743c5b369ad98b59758393f9d567bb9d3 | tinysheepyang/python_scripts | /leetcode/数组/283移动0.py | 1,475 | 4 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/7/18 13:51
# @Author : chenshiyang
# @Site :
# @File : 283移动0.py
# @Software: PyCharm
def move_zero(arr):
"""
1.新定义一个数组nums,将原数组中arr不为0的数组添加到新数组nums
2.遍历新数组nums,将原数组前部分设置为不为0的数 arr[i] = nums[i]
3.将原数组nums后部分设置为0
时间复杂度为O(n) 空间复... |
41099179f51cfec1d0c832e7a273b7ff01df4887 | Taein2/PythonAlgorithmStudyWithBOJ | /Minjae/2021-02-08/9012_Parenthes.py | 405 | 3.671875 | 4 | for _ in range(int(input())):
q=[]
s= input()
q.append('(')
if s[0]!='(':
print('NO')
continue
flag=True
for el in s[1:]:
if el=='(':
q.append('(')
else:
if not q:
flag= False
break
... |
353ed738556ba8c6382bef81d25e1a557eb4439c | starkblaze01/Algorithms-Cheatsheet-Resources | /Python/Compute_First/first.py | 2,510 | 3.5 | 4 | import re
def leftrecursion(y, grammar1):
# print(y)
x = y.split(":")
x1 = x[0]
x2 = x[1].split("|")
x1_new = x1 + '`'
new = []
new1 = []
for i in range(len(x2)):
if x2[i][0] == x1:
hello = x2[i].replace(x1, "")
new.append(hello+x1_new)
else:
... |
a74861dd6dfa4f311324192d9e5f5e409495e9b2 | devblocs/python_interview_problems | /numbers/3_odd_even.py | 245 | 4.0625 | 4 | num = int(input("Enter the number: "))
stat = ["even", "odd"]
if num%2 == 0:
print("{} is an even number".format(num))
else:
print("{} is an odd number".format(num))
print()
print()
print("{} is an {} number".format(num, stat[num%2])) |
237b49706e0f5adff4a501c044a1d079dc599280 | tomboxfan/PythonExample | /exercise/python_1010_algo_recursion_factorial.py | 935 | 4.5625 | 5 |
def factorial_no_recursion(n):
result = 1
for i in range(1, n+1):
result *= i
return result
# IMPORTANCE!!! --------------------------------------
# 2 important points:
# 1) base case
# 2) recursive call
#
# Summary:
# 1) Recursion is convert the problem into a smaller scale sub-problems.
# Exa... |
dd1b79fda75299f750fb466ccd0bd39d6976fad9 | eronekogin/leetcode | /2019/container_with_most_water.py | 631 | 3.875 | 4 | """
https://leetcode.com/problems/container-with-most-water/
"""
class Solution:
def maxArea(self, height: 'List[int]') -> 'int':
l = 0
r = len(height) - 1
mostWater = 0
while l < r:
"""
Starting at the front and the end of the list, then
always... |
b48aad08cd809bd1d347883bffb97e72d210efc8 | Breast-Cancer-PINN-ML-Team/ZYCNN-Codes | /ZYCNN1.0.py | 3,949 | 3.875 | 4 | #Import TensorFlow
import tensorflow as tf
from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt
#Download and prepare the CIFAR10 dataset
#Downloading data from https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz
(train_images, train_labels), (test_images, test_labels)... |
30ceae463d048bc221d7b99e9bbb691a8c03a984 | AnatolyDomrachev/evgenia | /1/1.2.py | 771 | 4.53125 | 5 | '''
Generate a random list of integer numbers. Number of elements and the generation range should be
requested from the user. Print the generated list on the screen. Without using insertion or deletion,
make a circular shift of all elements 1 step to the right, then print the modiϐied list.
'''
import random
def gen_... |
e1425775a3be8a728eccc45560e5ec3bee437969 | coneypo/Web_Spider | /update_seconds.py | 1,095 | 3.765625 | 4 | # Author: coneypo
# Created: 08.31
import datetime
# 开始时间
start_time = datetime.datetime.now()
print(start_time)
tmp = 0
# 记录的秒数
sec_cnt = 0
while 1:
current_time = datetime.datetime.now()
# second 是以60为周期
# 将开始时间的秒 second / 当前时间的秒 second 进行对比;
# 如果发生变化则 sec_cnt+=1;
if current_time.second >= ... |
94d15eb99c152d180ea8d8bc84885d8a2576e84d | raymondFU-EAT/hi | /play.py | 387 | 3.5 | 4 | x=6
print(x)
x=5
y=4
print(y)
y=7
z=x*y
print(z)
price=66
pen=9.6
rain=True
name='qq'
price=65
print(price, pen, rain, name)
print(price*5, pen*5 ,rain*5, name*5)
print(rain+5)
H=input('請輸入身高')
W=input('請誠實輸入體重')
Z=input('想賺多少錢')
print('身高', H, 'cm','也太矮了巴',
'體重', W, '公噸','該減肥瞜', '未來財富', Z*100) |
ecd2ac8173f2fb7ecf8f2a5f2312e8273eed2ad5 | p-koo/libre | /libre/model_zoo/cnn_dist.py | 3,183 | 3.984375 | 4 | from tensorflow import keras
def model(
input_shape,
output_shape,
activation="relu",
units=[24, 32, 48, 64, 96],
dropout=[0.1, 0.2, 0.3, 0.4, 0.5],
):
"""Creates a keras neural network with the architecture shown below. The
architecture is chosen to promote learning in a distributive way.... |
eb2fd84bf20a6374189da83c05f954684bb29d94 | akucia/Simple-Integrator | /InputValidator.py | 2,719 | 4.28125 | 4 | from Error import Error
class InputValidator(object):
"""
contains various validation methods used in program
"""
def __init__(self):
"""
constructor
:return: none
"""
pass
def validateParameters(self, parameters):
"""
checks if given values... |
815d65975679e0deeca5e6011be852324339129d | gutucristian/examples | /ctci/python/ch_3/3.2.1.py | 817 | 3.734375 | 4 | from stack import Stack
from sys import maxsize
class StackWithMin(Stack):
def __init__(self):
Stack.__init__(self)
self.min_stack = Stack()
def cur_min(self):
if self.min_stack.is_empty():
return maxsize
return self.min_stack.peek()
def pop(self):
value = super(StackWithMin, self).po... |
a9f0460ac362af9ca0cc49a193072dc6b21be662 | laxmi-2000/list1 | /if-else.py | 1,249 | 4.1875 | 4 | # num=int(input("enter the number:"))
# num1=int(input("enter the number:"))
# if num>num1:
# print("it is maximum")
# else:
# print("it is minimum")
# num=int(input("enter the number:"))
# if num%2==0:
# print("even number")
# else:
# print("odd number")
# a=int(input("enter the year:"))
# if a%4==0... |
b7e138b7dc97bb12dbfb4294bdcb1249b52e7dcd | collo-swiss/School-Projects | /quick_sort.py | 766 | 4.1875 | 4 | """Gathumbi Collins Githiari
A program to sort elements using Quick Sort algorithm."""
def quick_sort(array, start, end):
if(start < end):
p_index = partition(array)
quick_sort(array, start, p_index-1)
quick_sort(array, p_index+1, end)
return(array)
def partition(array):
end = (len(... |
c646559c628895a78a25f6b08264ce49c59589a4 | TheAlgorithms/Python | /graphs/matching_min_vertex_cover.py | 2,172 | 4.21875 | 4 | """
* Author: Manuel Di Lullo (https://github.com/manueldilullo)
* Description: Approximization algorithm for minimum vertex cover problem.
Matching Approach. Uses graphs represented with an adjacency list
URL: https://mathworld.wolfram.com/MinimumVertexCover.html
URL: https://www.princeton.edu/~aaa/Pub... |
42e1cab695f545bc177b50b067ee7b1d2e810096 | PTsai/Python3-Basics | /02.conditionals.py | 240 | 4.4375 | 4 | #!/usr/bin/python3
a, b = 0, 1
if a < b:
print('a ({}) is less than b ({})'.format(a, b)) # The {} is replaced by the string in .format()
else:
print('a ({}) is not less than b ({})'.format(a, b))
print("foo" if a < b else "bar"); |
dda7b8e66802f840364c5bc92eb581f97a23506c | kangyongxin/Backup | /MuscleMemory/DeepQ_only.py | 2,436 | 3.75 | 4 | """
To build a baseline(deep q learning ) and visulize it
"""
"""
Qlearning 的基本步骤:
1 初始化 q表
2 观测值
3 用 greedy方法采样 动作
4 实施动作 得到 反馈
5 用反馈值 和状态动作一起 更新q表
6 循环
"""
from baselines.MuscleMemory.maze_env import Maze
from baselines.MuscleMemory.RL_brain import QLearningTable,InternalModel
import matplotlib.pyplot as plt
i... |
ccbd5769fc0e9581487914011af793628e06e49a | nathanncohen/politwoops | /ministres/ministers_to_csv.py | 1,248 | 3.703125 | 4 | #!/usr/bin/python3
# Liste des Ministres:
#
# https://fr.wikipedia.org/wiki/France#Le_gouvernement
#
# (requires beautifulsoup4 + urllib)
# Input Parsing
import argparse
parser = argparse.ArgumentParser(description='Construit la liste des ministres')
parser.add_argument('filename', help="the output .csv file", type=a... |
1950bacb6192c9d7c6e18944f0bef140c371501f | Programmer-Admin/binarysearch-editorials | /The Accountant.py | 313 | 3.625 | 4 | """
The Accountant
Undercover base conversion problem. We divide repeatedly by 26 to find the character, subtract one because it is 1-based.
"""
class Solution:
def solve(self, n):
ans=""
while n:
n,rem = divmod(n-1,26)
ans+=chr(rem+ord("A"))
return ans[::-1]
|
62050da0f5c919ff96fcfe3999d0960f8440c0ac | ianmlunaq/edhesive-python | /7.x_Ian_Luna.py | 743 | 4.125 | 4 | # 7.x.py | ian luna | 2020.04.21 | chr ord
characterList = []
numberList = []
for x in range(3):
prompt = input("Enter a number: ")
character = chr(int(prompt))
characterList.append(character)
print()
for x in range(3):
prompt = input("Enter ONE character: ")
number = ord(prompt)
numberList.... |
6eacd326ca1e3516d66fc401660546688c95a8ba | Jack2413/Simulation-and-Stochastic-Models_COMP312 | /Assignments/Assignment/Assignment1.py | 1,543 | 3.96875 | 4 | # -*- coding: utf-8 -*-
# Part 1 — Python
# 1 Write fragments of Python code for the following:
# a You have a dictionary, D={'a':100}. Add a new component with key 'b' and value 200
D={'a':100}
D['b']=200
print D
# b You have a dictionary D={'b':200, 'a':100}. Remove the component with value 200.
D={'b':200, 'a':10... |
8083044fcb40b8840228c732fe3787a34039add8 | SureshEzhumalai/python_excercises | /codePractice2/numtriangle1.py | 142 | 3.90625 | 4 | # num = 1
# for row in range(1,6):
# for col in range(1, row + 1):
# print(num , end=" ")
# num = num + 1
# print()
|
984016f6197e9e1f88bf8c78ff79d2c0f5e1c732 | Ahsank01/FullStack-Cyber_Bootcamp | /WEEK_1/Day_3/2_Birthday_Party.py | 1,390 | 4.53125 | 5 | #!/usr/bin/env python3
"""
You've been ordered to print name tags for your friend's birthday party!
You noticed that quite a few people seem to share the same name at this party -
so you're putting together an organized list for your order. Given a list of names,
print out the number of occurrences of each nam... |
592daeeb9d750d830cfd12bd3df018bd15c425e0 | dsbrown1331/Python1 | /Review/question6.py | 313 | 4.03125 | 4 |
def change_string(string):
new_string = ""
for char in string:
if char == "e":
new_string += "i"
elif char == "o":
new_string += "a"
else:
new_string += char
return new_string
string_in = input("Type something: ")
print(change_string())
|
710b97ff574e57b46329edb7a5443be405b9f1e7 | ZVR999/Assignments | /product.py | 1,350 | 3.609375 | 4 | class Product(object):
def __init__(self,price,item_name,weight,brand):
self.price = round(price,2)
self.item_name = item_name
self.weight = weight
self.brand = brand
self.status = 'for sale'
self.display_info()
def sell(self):
self.status = 'sold'
... |
2197d08f48d24ef78904cffc1d4f48bd8f2151f6 | RShorty30/chest2 | /thyroid.py | 683 | 3.609375 | 4 | import random
from random import randint
import numpy as np
present = ["no", "a trace", "a small", "a moderate", "a large"]
size = np.arange(0, 3.1, 0.1)
side = ["right", "left"]
file = open("thyroid_nodule.txt", "w")
string_thyroid_nodule = []
for s in size:
s = str(s)
if s == "0.0":
nodule = "The thyroid is norm... |
eee49815851426461e3b449e907e3a8228b3d68d | tirth1/python-examples | /simple_interest.py | 279 | 3.890625 | 4 | def simple_interest(principal,interest,duration_in_years):
total_interest=interest*0.01*duration_in_years*principal
total_amount=principal+total_interest
print("total_interest is {0}".format(total_interest))
print("total_amount is {0}".format(total_amount))
|
4007aa6705c7b5d878f17b6cfbfc122b82371a3b | rajeshanu/rajeshprograms | /regular expressions/match.py | 99 | 4.25 | 4 | import re
str="this is python"
#input("enter a word to match")
st=re.match(r"python",str)
print(st) |
e0765b30a656c4c13e036d20bde46af48bc5c658 | Lmyxxn/JZoffer | /code/蓄水池抽样问题.py | 987 | 3.5625 | 4 | #coding=utf-8
'''
Created on 2016年9月15日
Reservoir sampling的python实现
@author: whz
'''
import numpy as np
# import matplotlib.pyplot as plt
def pool(L,k):
arr = L[:k]
for i,e in enumerate(L[k:]):
r = np.random.randint(0,k+i+1)
if r<=k-1:
arr[r] = e
return arr
# def count(q... |
0eff91e5fd0531cc8489a966453d8a849af76c3a | vigoroushui/python_lsy | /4.function/function_product.py | 815 | 3.953125 | 4 | def product(ans,*args): # 需要添加一个可选参数ans
# ans = 1 加上这句话会测试失败,因为product()不需要默认值
for n in args:
if not isinstance(n, (int, float)):
continue
ans = ans * n
return ans
A = (1, 2, 3, 'a', 5.7)
print(A, product(*A))
print('product(5) =', product(5))
print('product(5, 6) =', product(5,... |
33b803dc49de53c2ec447aadcac948b5c18a4a60 | tasneemab/RailsProject | /CW4/textEdit.py | 1,157 | 3.75 | 4 | class Text(object):
def __init__(self, font=None, text=' '):
self.__font = font
self.__text = text
def set_font(self, fo):
self.__font == fo
def get_font(self):
return self.__font
def get_text(self):
return self.__text
def write(self, txt):
self._... |
434b70b16a6ff0ec16f3275af48870d5b28f8dae | chris-zh/cs61a | /chapter1/hw01/homework1.py | 2,487 | 3.75 | 4 | __author__ = 'Administrator'
from operator import add, sub
#Question 1
def a_plus_abs_b(a, b):
if b < 0:
f = sub
else:
f = add
return f(a,b)
print(a_plus_abs_b(1,-2))
print(a_plus_abs_b(1,2))
print(a_plus_abs_b(1,0))
#Question 2
def two_of_three(a, b, c):
return pow(a,2)+pow(b,2)+pow(c,2)-... |
f0671bfdccc1c879d48f697a5847dbec60aa5d96 | MrRKernelPanic/DioderLED | /MRO_DioderXBOX.py | 1,785 | 3.765625 | 4 | # pygame example: github.com/pddring/pygame-examples
import pygame
import random
import time
from PyMata.pymata import PyMata
# Give the pins names:
REDPIN = 5
GREENPIN = 3
BLUEPIN = 6
# Create an instance of PyMata.
SERIAL_PORT = "/dev/ttyS0"
firmata = PyMata( SERIAL_PORT, max_wait_time=5 )
# initialize the digita... |
84bbc963950b52e6dae75418c2c96809acb5b7d8 | Jaeger-17/SoftwareTestingQA | /BMI.py | 997 | 3.9375 | 4 | class BMI:
def __init__(self, givenFeet = 5, givenInches = 0, givenWeight = 100):
self.inches = givenInches
self.feet = givenFeet
self.weight = givenWeight
def set_height(self, givenFeet, givenInches):
self.feet = givenFeet
self.inches = givenInches
def set_weight... |
5e278bc12a9738b2a236db347303a29df29cf31e | abisha22/S1-A-Abisha-Accamma-vinod | /Programming Lab/17-01-21/program3.py | 526 | 4.125 | 4 | Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec 7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> a=float(input("Enter fist number: "))
Enter fist number: 7
>>> b=float(input("Enter 2nd number: "))
Enter 2nd number: 4
>>> c=float(input("Ent... |
601ae3232ed3e6efdae578eff21f9e7656722278 | NagoluTeja/pythontraining | /exer1.py | 283 | 4.28125 | 4 | num1 = int(input("Enter number 1: "))
num2 = int(input("Enter number 2: "))
num3 = int(input("Enter number 3: "))
if (num1 >= num2) and (num1 >= num3):
print("num1 is largest")
elif (num2 >= num1) and (num2 >= num3):
print("num2 is largest")
else:
print("num3 is largest")
|
d6d66222e5a7ad36133d80da64227bc5485b6721 | PdxCodeGuild/20170724-FullStack-Night | /Code/sam/python/Lab12_practice3.py | 661 | 4.1875 | 4 |
def maximum_of_three(a, b, c): # defining function with three parameters
if a < b:
if b < c: # nesting if statement, comparing b and c
return c # returning c if larger than b
else:
return b ... |
6f372b9c3cdfd8ad20d4a8d1d109390da2fc32fc | lixiaokei/knowledge | /code/example08.py | 884 | 3.640625 | 4 | """
元类 - 描述类的类
通过继承type可以定义元类 通过元类可以改变一个类的行为
"""
from random import randint
class SingletonMeta(type):
def __init__(self, *args, **kwargs):
self.__instance = None
super().__init__(*args, **kwargs)
def __call__(self, *args, **kwargs):
if self.__instance is None:
self.__ins... |
33bfbe649366f5a5de99c60331d8103431d65379 | DataSlayer54/coderdojo | /RockPaperScissors/RockPaperScissorsFinal.py | 4,214 | 4.125 | 4 | # Import statements, currently just random for generation later in the script.
import random
# Variable initialisation.
compsignstr = 'Nothing.'
playersign = 'Nothing.'
prevsign1 = 'Nothing.'
prevsign2 = 'Nothing.'
prevsign3 = 'Nothing.'
# These variables will be used for the scoreboard
playerwins = 0
computerwins = 0... |
f1a6aa8f7d46c9c7c5d97ffe52e505a265b95fa2 | Aasthaengg/IBMdataset | /Python_codes/p03803/s492358634.py | 192 | 3.53125 | 4 | strength=[2,3,4,5,6,7,8,9,10,11,12,13,1]
A,B=map(int,input().split())
a=strength.index(A)
b=strength.index(B)
if a>b:
print("Alice")
elif b>a:
print("Bob")
elif a==b:
print("Draw") |
9f34d8410c5ca74f0cecd81dc23348951133afb5 | AlimKhalilev/python_tasks | /laba15.py | 1,233 | 3.640625 | 4 | import random
answers = ["Загаданное число больше", "Загаданное число меньше", "Поздравляю! Вы угадали"]
def game(userNum, randNum):
if (userNum < randNum):
answer = 0
elif (userNum > randNum):
answer = 1
else:
answer = 2
print(answers[answer])
return answer
def getNumber0... |
3a18b3d43bcb29bc85d6edb7f635fd55a0babfb2 | nathanwag15/CodeWars | /python/walk.py | 567 | 3.734375 | 4 | def is_valid_walk(walk):
y = 0
x = 0
if len(walk) == 10:
for i in walk:
print(i)
if i == 'n':
y += 1
elif i == 's':
y -= 1
elif i == 'w':
x -= 1
elif i == 'e':
x +=1
... |
4ddae8cfdc65a7f5737eadff3ce366fd47320ccb | AwesomePotato23/test-things | /lolz.py | 444 | 3.921875 | 4 | print("Hello world!")
var = "awesome"
print("This is " + var)
var2 = "LolzTheSpooky"
print("Follow " + var2 + " on WasteOf!")
print("Ok so like once I almost was ran over by a car")
feeling = "scared"
print("I felt " + feeling + " lol")
#Yes I actually was scared btw lmao
print("Ok... uh")
if 3 > 1:
print("3 is gr... |
df267e5ba62fccd288ec7d4deb4918b554c35ded | brunompasini/Project-Euler | /problem5.py | 306 | 3.640625 | 4 | def is_div(n,l):
for el in l:
if (n%el != 0):
return False
return True
def all_in_20():
lis = range(1,21)
num = 2520
fim = False
while not fim:
num += 1
fim = is_div(num,lis)
return num
def main():
print(all_in_20())
main()
# 232792560 |
3f8fe7077a702ad24d4fca544e19520f51d0935a | weitaishan/PythonPractice | /Base/Finished/Test48.py | 278 | 3.703125 | 4 | # *_*coding:utf-8 *_*
'''
题目:数字比较。
比较2个数字的大小
'''
def compare(x, y):
if x - y > 0:
print("%d大于%d" % (x, y))
elif x - y == 0:
print("%d等于%d" % (x, y))
else:
print("%d小于%d" % (x, y))
compare(1, 3) |
320966d096169157284fbee627e4f64f5c7be32d | Swapnil2095/Python | /8.Libraries and Functions/getpass() and getuser() in Python (Password without echo)/getpass()/Security Question.py | 265 | 3.828125 | 4 | # A simple Python program to demonstrate
# getpass.getpass() to read security question
import getpass
p = getpass.getpass(prompt='Your favorite flower? ')
if p.lower() == 'rose':
print('Welcome..!!!')
else:
print('The answer entered by you is incorrect..!!!')
|
333bd83eee7307c9b7aef53780389a63d1726c72 | njmanton/hocodeclub | /monty_hall_1.py | 1,225 | 3.90625 | 4 | # import random
import random, sys
# counting variables
wins = 0 # number of wins
losses = 0 # number of losses
# get choice of switch from command line if present, otherwise 1 (switch). argv[0] is always filename
switch = int(sys.argv[1]) if len(sys.argv) >= 2 else 1
# get number of trials from command line if pre... |
38c19ff5db62563eec414d4c2a07e317be8ec628 | wanglu1207/2020 | /quiz3.py | 518 | 4.15625 | 4 | def main():
# Add up 3 numbers and compute the average
# the eroor of " ' and " "
NUM1 = int(input("What is the first number? "))
NUM2 = int(input("What is the second number? "))
NUM3 = int(input("What is the third number? "))
#num3 is not on the right line
theAverage = NUM1+NUM2+NUM3/3
#the... |
57df922636fd4a4c9a4316050d19a3fec517d96d | ronaldcotton/Cracking-the-Coding-Interview-Sixth-Edition-Python | /Chapter3-StacksAndQueues/question3.4-Queue_via_Stacks.py | 1,826 | 4.34375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Question 3.4 Queue via Stacks
# Using Two Stacks - Implement a Queue
class Stack:
def __init__(self):
self.stack = []
def __str__(self):
return str(self.stack)
# --- stack commands - LIFO ---
# remove last element from array
de... |
d763bd87c60368db4df2d743af8f23a0e0c19ead | fanxinwei/Problem_Solving_with_Algorithms_and_Data_Structures | /Chapter3/Stack/dicimal_to_binary.py | 534 | 3.71875 | 4 | from Stack_function import Stack
def dicimal_to_binary(k):
mystack = Stack()
new_string = ''
if k == 1: #排除0、1的二进制
return 1
if k == 0:
return 0
else:
while k != 0:
remainder = k % 2 # 余数
mystack.push(remainder)
k = k // 2 #除数
while... |
72786cf46e653732759b4e1f44f689ccccb2fa5d | banginji/algorithms_sot | /chapter4/path_directed_graph_nodes.py | 1,824 | 3.5625 | 4 | from datastructures import graph
import random
from collections import deque
def create_graph():
start_node = graph.Node(0)
node_1 = graph.Node(1)
node_2 = graph.Node(2)
node_3 = graph.Node(3)
node_4 = graph.Node(4)
node_5 = graph.Node(5)
node_6 = graph.Node(6)
start_node.children.app... |
b59e11c37e6a49a193ac932b84fb29dbdc455934 | joaoo-vittor/estudo-python | /OrientacaoObjeto/aula8Classes.py | 555 | 3.78125 | 4 | # A classe precisa de produtos
class CarrinhoDeCompras:
def __init__(self):
self.produtos = []
def inserir_produtos(self, produto):
self.produtos.append(produto)
def lista_produtos(self):
for produto in self.produtos:
print(produto.nome, produto.preco)
def soma_tot... |
60eba75ac80c51141527181c9d545edcbf980e82 | sachasi/poethepoet | /tests/fixtures/dummy_project/dummy_package/__init__.py | 385 | 3.59375 | 4 | import os
import sys
def main(*args, greeting="hello", upper=False):
if upper:
print(
greeting.upper(),
*(arg.upper() for arg in args[1:]),
*(arg.upper() for arg in sys.argv[1:])
)
else:
print(greeting, *args, *sys.argv[1:])
def print_var(*var_name... |
ca1047a249900dfdd978ed5aa7369da9f7ec8e23 | gokipurba/Simple_Learn-Python | /Try, Except.py | 544 | 3.78125 | 4 | '''try:
age = int(input("age: "))
income = 2000
risk = income / age
print(age)
except ValueError:
print("Invalid Value",)
except ZeroDivisionError:
print ("Age cannot be 0.")
print("#" * 25)'''
########################################
class Point:
def __init__(self... |
b6f6b4a1710a48ede6bd5a1f5ffd971e0628d67b | Hijiao/algorithms | /leetcode/0121.BestTimetoBuyandSellStock.py | 359 | 3.640625 | 4 | class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
min_buy_p = float("+inf")
max_b = 0
for p in prices:
max_b = max(max_b, p - min_buy_p)
min_buy_p = min(min_buy_p, p)
return max_b
... |
807b94c21a0bcd6e2c2c8f6bf91d10f26beca2ee | KristofferFJ/PE | /problems/unsolved_problems/test_149_searching_for_a_maximum-sum_subsequence.py | 1,034 | 3.84375 | 4 | import unittest
"""
Searching for a maximum-sum subsequence
Looking at the table below, it is easy to verify that the maximum possible sum of adjacent numbers in any direction (horizontal, vertical, diagonal or anti-diagonal) is 16 (= 8 + 7 + 1).
Now, let us repeat the search, but on a much larger scale:
First, gener... |
f704ae57539def2421240353fb91a0b3de6c5fba | UCD-pbio-rclub/Pithon_MinYao.J | /hw7/hw7-2_calculator.py | 4,390 | 4 | 4 | # Problem 2
# Create a simple calculator app. Make sure the app can do +,-,/,* at the minimum. Feel free to add more functions which may be found on a calculator.
from tkinter import *
def btnClick(numbers):
global operator
operator = operator + str(numbers)
text_Input.set(operator)
def btn_clear_display... |
ef78c63616dd731285e579c6818e0223ed05e4d8 | ChangxingJiang/LeetCode | /1401-1500/1464/1464_Python_1.py | 515 | 3.515625 | 4 | from typing import List
class Solution:
def maxProduct(self, nums: List[int]) -> int:
max1 = 0
max2 = 0
for n in nums:
if n > max1:
max2 = max1
max1 = n
elif n > max2:
max2 = n
return (max1 - 1) * (max2 - 1)
... |
67ccd809e61d024cc16f5d62be02153355846aa6 | Nicholas-Graziano/ICS3U-Unit4-01-Python | /adding_integers.py | 712 | 4.3125 | 4 | #!/usr/bin/env python3
# Created by: Nicholas Graziano
# Created on: November 2020
# This program checks if a number is negative or positive
def main():
# input
print("\n", end="")
positive_integer = print("Enter any postitve integer ")
positive_integer_as_string = input("Enter integer here:")
loo... |
4f9dda690ff55fbc7fc512038515ac6ff1ab78ab | themanoftalent/Python-3-Training | /08 Some Works/41_python.py | 1,127 | 4.65625 | 5 | # Create a tuple named zoo that contains your favorite animals.
zoo = ('Zebra', 'Tiger', 'Penguin', 'Elephant')
for i in zoo:
print(i)
print("--------------------------------")
# Find one of your animals using the .index(value) method on the tuple.
print("Tisger is located at one ",zoo.index('Tiger'))
# Determine... |
ace76deff1439bea611492de2c0326860e59b6dd | BuiltinCoders/PythonTutorial | /operators.py | 3,969 | 4.78125 | 5 | # # Type of operators in python
# 1. Arithmetic Operators
# 2. Assignment Operators
# 3. Comparison Operators
# 4. Logical Operators
# 5. Identity Operators
# 6. Membership Operators
# 7. Bitwise Operators
# 1. Assignment Operators
# assignment operators are used to do numeric caculation
# examples of assignment ... |
f2b98fda0d26c32b2d8f82911303725dd79241a1 | edwinagnew/spookyporters | /qkd.py | 5,790 | 3.59375 | 4 | from microqiskit import QuantumCircuit, simulate
import random
import numpy as np
import math
class bb84:
#Based (heavily) off https://quantum-computing.ibm.com/jupyter/user/qiskit-textbook/content/ch-algorithms/quantum-key-distribution.ipynb
#TODO - maybe seperate classes into bob and alice
def __init__(... |
28b49767689b1e8bd2fb5386c5ded1948fe26359 | livioribeiro/project-euler | /python/p003.py | 544 | 3.65625 | 4 | """
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143?
"""
import math
def is_prime(num):
if num <= 2:
return True
if num % 2 == 0:
return False
for i in range(3, math.ceil(math.sqrt(num)) + 1, 2):
if num % i == 0:
... |
f906d731a2ad9d3022a80b18a5e9f8b00610791c | fahira5/guvi | /fahiprime.py | 117 | 3.640625 | 4 | b=int(input())
n=0
for i in range(2,b//2+1):
if(b%i==0):
n=n+1
if(n<=0):
print("yes")
else:
print("no")
|
5210bc4fb57edab7ad1f8478a89374ac6c0c29e6 | Valipsy/Py_Course | /TP/Sol.py | 3,469 | 3.71875 | 4 | class TextProcessing:
def __init__(self, text):
self.text = text
def word_occurence(self, word):
count = 0
# Cleaning text as much as we can
text = self.text.replace(",", " ")\
.replace(":", " ")\
.replace(";", " ")\
... |
86ebdd9d4ca62e4825198212cee87b7657d515e6 | Hethsi/project | /Sum.py | 37 | 3.5625 | 4 | a=5
b=5
sum=a+b
print("Sum is:",sum)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.