blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
b632426f63e15c563a3432e466f38dc80c4a2715 | anudeeptreddy/AlgorithmToolBox | /week5/primitive_calculator_5_2.py | 1,412 | 3.765625 | 4 | # Uses python3
import sys
def optimal_sequence_dp(n):
# Algorithm to compute the minimum number of operations needed to obtain the number n starting from 1.
# Permissible operations for the current number x are: x * 2 (or) x * 3 (or) x + 1
sequence = []
no_of_ops_to_i = [0] * (n+1) # Needed to acco... |
3fb17157eabb72cf0582411fe8606ee38f2b47bc | zopepy/leetcode | /missing_words.py | 346 | 3.734375 | 4 | def missingWords(s, t):
s = s.split()
t = t.split()
sl = len(s)
tl = len(t)
i = 0
j = 0
missing = []
while i<sl or j<tl:
if i<sl and j<tl and s[i] == t[j]:
i+=1
j+=1
else:
missing.append(s[i])
i+=1
return missing
s = "I am using hackerrank to improve programming"
t = "am hackerrank to improve"... |
00b63dc97003b31f82987d042ac4e4b1082986d8 | TylermEvans/Portfolio | /Raytracer/math3d.py | 7,345 | 4.15625 | 4 | #Tyler Evans
#ETGG 1803
#Lab 2
import random
import pygame
"""This VectorN class creates a vector object that can store any number of variables."""
class VectorN(object):
""""This is the VectorN object. This helps define the Vector Class"""
def __init__(self,*other_Args):
"""The attributes of this c... |
0ab9d1e8dcad5ae6b6022145a64a7ed0ffa6a887 | Sandeep8447/interview_puzzles | /src/test/python/com/skalicky/python/interviewpuzzles/test_find_shortest_task_plan_with_cool_down_time_and_without_reordering.py | 929 | 3.875 | 4 | from unittest import TestCase
from src.main.python.com.skalicky.python.interviewpuzzles.find_shortest_task_plan_with_cool_down_time_and_without_reordering import \
find_shortest_task_plan_with_cool_down_time_and_without_reordering
class Test(TestCase):
def test_find_shortest_task_plan_with_cool_down_time_and... |
24ebb9e4096586b9dce22f6925d2ffff9ddfea1e | Keeeweee/adventOfCode-2019 | /day-04/second.py | 624 | 3.6875 | 4 | def checkValidPassword(password: str):
previousDigit = 0
for digit in password:
digit = int(digit)
if digit < previousDigit:
return False
else:
previousDigit = digit
for i in range(10):
if str(i) + str(i) in password and not str(i) + str(i) + str(i) i... |
d267d6284874e393c26218654c46e6c0f28a4345 | trishalmuthan/tjhsst-ai | /unit3-turnbasedgames/Othello/printboard.py | 168 | 3.53125 | 4 | import sys
board = sys.argv[1]
to_print = ''
for count, char in enumerate(board):
if count % 8 == 0:
to_print += '\n'
to_print += char
print(to_print) |
a50a96e31a8edf70f2c052e99dc7297b77114520 | Fariha-simi/git_tut2 | /test11.py | 796 | 3.84375 | 4 | #Assignment-2:
a=90
b=100
c=80
d=40
e=0.45
d=8.9
f=0.04546
if a>b>c>d or d>e>f>a>=b:
print("First Commit")
if a>=b and d>=e or a>b:
print("Second Commit")
if a==b or a!=b:
print("Third Commit")
elif d>e>f:
print("Forth Commit")
if c==d and d==f:
print("Fifth Commit")
elif c%d==0:
print("Sixth C... |
35c7251076f76bdc887f9e5bc7702454b008ac6e | c0state/MergeSortPython | /MergeSortPython.py | 1,407 | 4.21875 | 4 | def mergesort(array):
if len(array) < 2:
return array
else:
subarray1 = mergesort(array[:len(array)/2])
subarray2 = mergesort(array[len(array)/2:])
# merge sorted sub-arrays
arr1index = 0
arr2index = 0
mergedarray = []
while (arr1index < len(subarray1)) or (arr2i... |
3e3169d03ccb681420dce45898436cbcc091e930 | JhonataAugust0/Python | /Estruturas/exercicios/sequencia.py | 1,003 | 4.0625 | 4 | print('''Existe uma sequência que se repete indefinidamente com as figuras
de um triângulo, árvore, losângulo, espada, coração e um quadrado, nesse padrão.
Ou seja, há um padrão de repetição das 6 primeiras figuras.\n''')
n = int(input("Digite o número de elmentos que a sequência vai ter.\n"))
padroes = n / 6
resto = ... |
076d50de2d44175f1b5ef42262be19a179bc49cc | adriand1az/search_bar | /searchbar.py | 907 | 3.8125 | 4 | import re
names_file = open("random.txt", encoding="UTF-8")
data = names_file.read()
names_file.close()
class Search:
def __init__(self):
pass
def search_letter(self): # Searches document for a str
user_search = input("search: ")
searching_letter = re.findall(user_sea... |
df19f1bf6a4a46c6ab8fb9518e81359b735d657b | r-azh/TestProject | /TestPython/machine_learning_with_python/ch06_classification_II_sentiment_analysis/mine/arithmettic_underflows.py | 523 | 3.625 | 4 | import numpy
numpy.set_printoptions(precision=20) # default is 8
x = numpy.array([2.48E-324])
print(x)
print('#### underflow for 2.47E-324 #### ')
x = numpy.array([2.47E-324])
print(x)
x = 0.00001
y = x ** 64
print(y)
print('#### underflow #### ')
y = x ** 65
print(y)
import sys
print(sys.float_info)
# To mit... |
3f008e967a4daa01bea401a1b093a77dd4f6153d | sevenhe716/LeetCode | /LinkedList/q160_intersection_of_two_linked_lists.py | 947 | 3.65625 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
# 统计两链表长度之差,然后长链表先开始走差值步,然后判断是否有相同的节点
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: L... |
12a65fd2459ec8f5c5241cd83606681318badb1b | Mustafa017/python-programs- | /iteration and recusion.py | 1,490 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 19 14:28:32 2017
@author: mustafa
"""
class BankAccount:
def withdraw(self):
pass
def deposit(self):
pass
class SavingsAccount(BankAccount):
def __init__(self, balance=1500):
self.balance = balance
def deposit(self, amount):
... |
fa7271f1ac462828d2df28a81f3fd90e1142fda4 | randaghaith/Python-Course | /Week 2/Practice2-D.py | 334 | 3.6875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[6]:
jordanStates = ["Irbid","Ajloun","Jerash","Mafraq","Balqa","Amman",
"Zarqa","Madaba","Karak","Tafilah","Ma'an","Aqaba"]
for state in jordanStates:
if state[0] == "A":
print(state)
for state in jordanStates:
if len(state) == 5:
... |
e7ac521f886ad6288472229a5012887ccd42d1ae | wenli810620/code_interview | /chapter4.py | 9,909 | 3.96875 | 4 | #!/usr/bin/python
# filename: chapter4.py
# TREE CLASS
class Tree(object):
def __init__(self, n):
self.Parent = None
self.LeftChild = None
self.RightChild = None
self.Data = n
self.VisitState = VisitStates.UnVisited
def insert(self, node):
# go to left
... |
4987eb861286b14adcf606058eb47829b5460891 | jamezaguiar/cursoemvideo-python | /Mundo 1/016.py | 375 | 4.21875 | 4 | #Exercício Python 016: Crie um programa que leia um número Real qualquer pelo teclado e mostre na tela a sua porção Inteira.
from math import trunc
num = float(input("Digite um valor: "))
print ("O valor digitado foi {} e sua porção inteira é {}".format(num,trunc(num)))
#Função trunc da biblioteca math corta o ... |
deff9c47219064d4541d237a8a833e2355e10b51 | SilvesterHsu/leetcode | /leetcode-algorithms/027. Remove Element/solution.py | 323 | 3.796875 | 4 | from typing import List
def removeElement(nums: List[int], val: int) -> int:
if not nums or not len(nums):
return 0
i,t = 0, 0
while i < len(nums):
if nums[i] != val:
nums[t] = nums[i]
t += 1
i += 1
return t
l = [1,2,3,4,5]
print(removeElement(l,3))
print... |
4667b7a934075983091607ba89de170d575c1d48 | park-seonju/Algorithm | /Labssafy/swea/1790_쉬운거스름돈.py | 240 | 3.578125 | 4 | T=int(input())
for tc in range(1,T+1):
n=int(input())
ans=[]
money_list=[50000,10000,5000,1000,500,100,50,10]
for money in money_list:
ans.append(n//money)
n%=money
print('#{}'.format(tc))
print(*ans) |
d397cca2f4251b487b076503942a3d166548b017 | cyhsGithub/Data-Structure | /list/list_intersection.py | 935 | 3.78125 | 4 | class Node:
def __init__(self,elem, next=None):
self.elem = elem
self.next = next
a,b,c,d,e = Node(1),Node(2),Node(3),Node(4),Node(5)
a.next = b
b.next = c
c.next = e
d.next = e
def intersection(a, b):
a1 = a
b1 = b
is_intersection = False
len_a = 1
len_b = 1
while a1.next ... |
61d3ad25743cc0bad55e7ae679ea34c8f6db9b5d | pydemos/test | /09_面向对象的特征/hm_07_父类的私有属性和私有方法.py | 764 | 3.921875 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Keawen
class a:
def __init__(self):
self.num1= 100
self.__num2 = 200
def __test(self):
print('私有方法 %d %d' %(self.num1,self.__num2))
class b(a):
def demo(self):
#1在子类的对象方法中.不能访问父类的私有属性
#print('访问父类的私有属性%d ^self.__nu... |
0d058955965aeb1719b4c57cdf3728ffa5168992 | Daniel-M/doconce_demo | /code/code1.py | 80 | 3.5625 | 4 | total = 0
for number in range(10):
total = total + (number + 1)
print(total)
|
b0215d6739bd146d377b049bbcfe3ca9d3f2c689 | andrewyen64/letsbrewcode-python | /5-IteratorsLoops/notes.py | 1,572 | 4.03125 | 4 | # Iterators
### iter() ------------
s = 'Saturn'
iter(s)
it1 = iter(s)
it2 = iter(s)
next(it1)
# 'S'
next(it1)
# 'a'
next(it1)
# 't'
next(it2)
# 'S'
### range() ------------------------
range
# <class 'range'>
range(100)
# range(0, 100)
list(range(10))
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
list(range(1, 10, -2))
# []
... |
70e6e811acfeae14923da17d5989c15ec70ca969 | aanaree/4883-SWTools-greene | /Assignments/A09/twenty48.py | 9,900 | 3.703125 | 4 | #!/usr/local/bin/python3
from tkinter import *
from tkinter import ttk
import tkinter as tk
import numpy
#from ttk import Button,Combobox
import random
class Matrix():
#creates the square in which the game is played
def __init__(self,row,col,fill =0):
self.row = row
self.col = col
... |
a5501c0532c59d165cda33728cf8ba8e244285ff | skywalkerqwer/PythonBase | /week01/day03/exericise/exericise02.py | 255 | 4.1875 | 4 | month = int(input("输入月份"))
if 1 <= month <= 12:
if month <= 3:
print("春")
elif month <= 6:
print("夏")
elif month <= 9:
print("秋")
elif month <= 12:
print("冬")
else:
print("输入错误")
|
7122070beb1d641b86a34c1dfb0e027bb8fb9c8b | ABHISHEK-AMRUTE/Hello-world-1 | /Python/factorial.py | 386 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Sep 2 15:58:58 2018
@author: Karan Randhir
"""
#Print factorial of a number input by user
n=input("Enter number ")
try :
n=int(n)
print("Enter an intege")
fact = 1
for i in range (1,n+1) :
fact = fact *i
print("Factorial of t... |
2be9aea0e450ef15125d483ab4d971cc1204d9c0 | planga82/KeepCodingPracticasPython | /KC_EJ01.py | 349 | 3.890625 | 4 |
# Ejercicio 1
import math
correcto = False
while not correcto:
entrada = raw_input("Radio del circulo: ")
try:
radio = int(entrada)
correcto = True
area = round(math.pi * radio ** 2,1)
print("El area del circulo es: " + str(area))
except ValueError:
print('El valor ... |
e9adba2f7ed99278ec413631dd3c0bf86ccc5d53 | Ahuge/advent_of_code_2019 | /1/part_2.py | 914 | 3.546875 | 4 | import math
import sys
with open("input.txt", "rb") as fh:
data = fh.read().split("\n")
def calculate_fuel_for_mass(mass):
return math.floor(mass/3.0) - 2
def calculate_fuel_for_fuel(fuel_mass):
total = 0.0
while fuel_mass:
fuel_mass = calculate_fuel_for_mass(fuel_mass)
if fuel_mass <... |
514f0bdcdbd6cecc8b504fae902d6d180e4a2576 | Plutoxxx/Python | /python_my_day/myday9/threading_test/threading_ex3.py | 667 | 3.84375 | 4 | import threading
import time
lock = threading.Lock()
def run(n):
lock.acquire()
global num
num += 1
time.sleep(0.1)
lock.release()
num = 0
# t1 = threading.Thread(target=run, args=("t1",))
# t2 = threading.Thread(target=run, args=("t2",))
# t1.start()
# t2.start()
# run(1)
# run(2)
t_obj = []
star... |
0e0140b402e5f96ee033ee1b9f4ab81898e52b0e | JadenFiotto-Kaufman/Process-Scheduling | /Scheduler.py | 4,455 | 3.765625 | 4 | from enum import Enum
#Identifier for what scheduling methd is being used
class Methods(Enum):
FCFS = "First Come First Serve"
SJF = "Shortest Job First"
SRT = "Shortest Remaining Time"
PRIORITY = "Priority"
RNDRBN = "Round-Robin"
#Scheduler takes a process and sets its value based on the scheduling... |
9a41f6ba90f9c2b39cdf75db5b6bf8c5116c3b4d | DinaShaim/Python_basics | /HomeWork_4/les4_task_5.py | 778 | 4.0625 | 4 | # Реализовать формирование списка, используя функцию range() и возможности генератора.
# В список должны войти четные числа от 100 до 1000 (включая границы).
# Необходимо получить результат вычисления произведения всех элементов списка.
# Подсказка: использовать функцию reduce().
from functools import reduce
l... |
534348b217bd39fd125be75d27806d0fbdeec378 | oliver-ode/Algorithmic-Coding | /CodingBat/Python/Logic1/caughtSpeeding.py | 208 | 3.5625 | 4 | def caught_speeding(speed, is_birthday):
bday = 0
if is_birthday:
bday = 5
if speed <= 60 + bday:
return 0
elif speed <= 80 + bday:
return 1
else:
return 2
|
b77b8249eee7ea2b964deb1ba60ba18594094f65 | jesusrcorrochano/Random-Numbers | /Visualization.py | 607 | 3.765625 | 4 | #Author: Jesús Rodríguez Corrochano
#Import the needed libraries
import json
import matplotlib.pyplot as plt
#Load the data
List = json.load(open("Random_List.json"))
#Calculate the times each number appears (frequency)
Number = []
Frequency = []
for i in range(0,101):
freq = 0
for j in List:
... |
929016e8169118ec38fc7b4c2c27be291b126fb5 | BingfanWang/Introduction-to-Algorithms--Python | /Sort/BubbleSort.py | 1,303 | 3.6875 | 4 | # 冒泡排序
# 原理: 两层循环: 第i轮外层循环, 内层从后往前检索到位置i, 检索过程比较相邻位置大小, 若后者小于前者, 交换位置
# 原理续: 第i轮循环结束, 列表前i个依次排列列表前i小元素
# 稳定排序, 原址排序
# 时间复杂度: O(N^2)
import random
import time
def bubble_sort(list_a):
# 外层循环, 指定内层循环每次停止位置.
# 只需到倒数第二位时, 整个列表已经排好, 最后剩下的一个一定是倒数第一
for index_i in range(len(list_a) - 1):
# 内层循环, 从后往前检索到位... |
fca48a73fd6df7d30333b44220bf2bd84e9b5709 | zhuy9/rosebotics2 | /src/capstone_1_runs_on_laptop.py | 7,485 | 3.953125 | 4 | """
Mini-application: Buttons on a Tkinter GUI tell the robot to:
- Go forward at the speed given in an entry box.
This module runs on your LAPTOP.
It uses MQTT to SEND information to a program running on the ROBOT.
Authors: David Mutchler, his colleagues, and Bryan Wolfe.
"""
# ----------------------------------... |
a901504ddfc8fe4305789a86e2e4e88400c6027e | Charlymaitre/30exo_python | /30.py | 420 | 4 | 4 | # Faire un programme python qui construit des pyramide d’étoile. Le programme demande à l’utilisateur le nombre de ligne et le programme dessine une pyramide.
valeurInitiale = int(input("Choississez votre nombre de ligne "))
star = 1
space = valeurInitiale - 1
line = 0
while line < valeurInitiale:
p... |
fcb77413af336b465c5bdb9a2c4ae3e8de871c6f | sanjusci/nltk-basic | /lemmatization.py | 1,076 | 3.796875 | 4 |
__author__ = "Sanju Sci"
__email__ = "sanju.sci9@gmail.com"
__copyright__ = "Copyright 2019"
from nltk.stem import WordNetLemmatizer
class Lemmatization(object):
"""
A very similar operation to stemming is called lemmatizing.
The major difference between these is, as you saw earlier, stemming can oft... |
d732dc26eadd823baf4c5d07e8bcbb6dd8d4d3f1 | ryanhalabi/Project_Euler | /P5.py | 661 | 3.609375 | 4 | #2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
#
#What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
good = []
n = 100000000
for i in range(1,n):
if (20*i)%19==0:
if (20*i)%18==0:
if (20... |
c9ee0d5f5ca9386135cd7838666c27763d26a245 | rajeevj0909/FunFiles | /Easy Inputs.py | 489 | 3.828125 | 4 | name=input ("I am going to ask you a few questions, what is your name?")
food=input ("What is your favourite food?")
film=input ("What is your favourite film?")
sport=input ("What is your favourite sport?")
team=input ("What sports team do you support?")
print ("I am going to repeat your answers.")
print ("Your f... |
a96b9f7bb4afdfe96912884c22f3867c1298f07b | daniel-reich/ubiquitous-fiesta | /uWW8cZymSkrREdDpQ_9.py | 349 | 3.625 | 4 |
def sums_up(lst):
pairs = []
for index_a, number_a in enumerate(lst):
for index_b, number_b in enumerate(lst[index_a + 1:], start=index_a + 1):
if number_a + number_b == 8:
element = [index_b, sorted([number_a, number_b])]
pairs.append(element)
pairs = [item[1] for item in sorted(pairs)... |
16e181c7cb122632b849d209cca0b809a46d1208 | canwe/python3-course-advanced | /04_functools/partial_sample.py | 404 | 4.15625 | 4 | """
You can use partial to “freeze” a portion of your function’s arguments
and/or keywords which results in a new object. Another way to put it
is that partial creates a new function with some defaults.
"""
from functools import partial
def add(x, y):
return x + y
p_add = partial(add, 2)
# We are basically defau... |
6bfcceb4a2cd048facdaaab5852f10a260a25687 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/shervs/lesson06/mailroom4.py | 4,965 | 3.640625 | 4 | #!/usr/bin/env python
import sys
import string
import os
donor_dict = {"William Gates, III": [1.50, 653772.32, 12.17],
"Jeff Bezos": [877.33],
"Paul Allen": [663.23, 43.87, 1.32],
"Mark Zuckerberg": [1663.23, 4300.87, 10432.0],
}
prompt = "\n".join(("Please choose ... |
0aa704664a032e37e2cbad88ac0c0a5310990987 | nmaslov255/SICP-assignments | /Chapter 1/assignment_3.py | 493 | 3.984375 | 4 | # function witch return sum of squares
def sum_of_biggest_squares(a, b, c):
def square(x): return x * x
a, b, c = abs(a), abs(b), abs(c)
if a > b:
if b > c: return square(a) + square(b)
else: return square(a) + square(c)
else:
if a > c: return square(a) + square(b)
... |
6ba4d1f64a09e199e793d5398f7ae58895e249a7 | goelalex/inf1340_2014_asst2 | /papers.py | 11,323 | 3.609375 | 4 | #!/usr/bin/env python3
""" Computer-based immigration office for Kanadia """
__author__ = 'Susan Sim, Xiwen Zhou, Alex Goel'
__email__ = "ses@drsusansim.org, xw.zhou@mail.utoronto.ca, alex.goel@mail.utoronto.ca"
__copyright__ = "2014 Susan Sim, Xiwen Zhou, Alex Goel"
__license__ = "MIT License"
__status__ = "Protot... |
fa71498105ec8173ae38f3106abb4a8b6048a7f6 | Natykk/Mini-Jeux-Python | /Devine_le_nombre.py | 329 | 3.796875 | 4 | from random import randint
nmb = randint(0, 20000)
nmb2 = 0
compteur = 0
while nmb != nmb2:
compteur += 1
nmb2 = int(input("Ecrire un nombre"))
if nmb2 > nmb:
print("Trop Grand")
elif nmb2 < nmb:
print("Trop Petit")
else:
print("Gagné avec ", compteur, " coups")... |
eba6ea6aa6667aac09398d0efabc00479d9a87bb | Neverfinsh/pythonWorkSpace | /Python_02.py | 1,300 | 4.0625 | 4 |
# python的编码问题
print("py中文输出整数的编码")
print(ord("A"));
print(ord("我"));
print(ord("爱"));
print(ord("你"));
#py 把整数转换成字符串
print(chr(97));
# py求字符串的长度问题,使用的是Unicode的编码方式。中文只占一个字节。
# py在保存中文是必须要添加utf-8的头文件
print(len('aaa'));
print(len("爱"));
# py list集合中使用;有序,可以重复
listview=['a','b','c']
print(listview);
listview.append... |
00a92411f351a6cad74f629e65f29bdf998e53e1 | hershi/Exercism | /python/hello-world/hello_world.py | 156 | 3.625 | 4 | #
# Skeleton file for the Python "Hello World" exercise.
#
def hello(name=''):
return "Hello, %s!" % ("World" if name == '' or name is None else name)
|
1dc3fc83a02a9a9726c3981ee4df87e40e963b6c | qmnguyenw/python_py4e | /geeksforgeeks/python/python_all/38_3.py | 1,884 | 3.96875 | 4 | Python – Time Strings to Seconds in Tuple List
Given Minutes Strings, convert to total seconds in tuple list.
> **Input** : test_list = [(“5:12”, “9:45”), (“12:34”, ), (“10:40”, )]
> **Output** : [(312, 585), (754, ), (640, )]
> **Explanation** : 5 * 60 + 12 = 312 for 5:12.
>
> **Input** : test_li... |
628d4a2884921f73f9b79a0fa8b7427268e6e5b8 | vksmgr/DA-Py | /src/numpy_linearalgebra.py | 649 | 3.59375 | 4 | import numpy as np
#dot product of two matrix
mtx1 = np.array([[ 1. , 2. , 3. ], [ 4. , 5. , 6. ]]) # 2 X 3 mtx
mtx2 = np.array([[ 6. , 23. ], [ - 1 , 7 ], [ 8 , 9 ]]) # 3 X 2 mtx
print(mtx1.dot(mtx2))
#test mtx product
my_1 = np.array([[1, 2], [3, 4]])
my_2 = np.array([[5, 6], [7, 8]])
print(" produc... |
ed5b762be165860c9446e3e15d42e51a07ff325e | aBorovtsov1994/AlphaCalculator | /main.py | 845 | 4.15625 | 4 | """
This calculator is going to take a bill and split it among a set amount of users (user-defined). It will calculate the
ratio each person owes and then use those ratios to calculate how much of the tips/fees each user owes and adds that
to the total they are owed.
"""
num_of_users = 0
bill_subtotal = 0
tips_amount =... |
a7062c073328668badfbdc321cdaf639ed6b2aa4 | renzopachecoj/kotlin-syntax-analyzer | /.history/interfaz_20200716164323.py | 601 | 3.515625 | 4 | import tkinter as tk
window = tk.Tk()
window.geometry("500x600")
label = tk.Label(text="Código en lenguaje Kotlin")
label2 = tk.Label(text="Resultados de análisis")
textFld = tk.Text() #input
textFld2 = tk.Text() #salida
textFld2.configure(state="disabled")
btn = tk.Button(text="Analizador Léxico")
btn2 = tk... |
f22cd4f810b1df4585ace0c918a22f03ac87a091 | carlosabrx/statistical-mechanics | /Gauss.py | 362 | 3.53125 | 4 | import math
import numpy as np
def gauss(sigma):
''' Takes in sigmas as input. Gives two independent Gaussian random numbers obtained by sample transformation'''
psi = np.random.uniform(0,2*math.pi)
wf = -math.log(np.random.uniform(0,1))
r = sigma * math.sqrt(2 * wf)
x = r * math.cos(psi)
y = r * ... |
a0f967bc2b6378427d98d12e6e4dd1ad808b4d89 | SarmahMayuri/python-concepts | /if_else.py | 573 | 4.375 | 4 | #if,elif, else
#Eg:1
name= 'Mayuri'
if name == 'Mayuri':
print('Hi Mayuri')
elif name== 'Sameer':
print('Hi Sameer!')
elif name== 'Nayanita':
print('Hi Nayanita')
else:
print('Name not present!')
#Eg: 2
#hungry is set to a boolean value, and since if,else statement search for a T/F condition
# we don... |
d102082a3e1ae6ab88084b940b37afe8f51513c9 | ismailgunayy/project-euler | /python-solutions/Problem10 - PE.py | 417 | 3.53125 | 4 | """
Created by İsmail GÜNAY
Start Date: 15:20 / 18.01.2020
End Date: 15:31 / 18.01.2020
ProjectEuler Problem10
The sum of all the primes below two million
"""
def is_prime(n):
for i in range(2, round((n**0.5) + 1)):
if n % i == 0:
return False
return True
sum = 0
for j in ra... |
7a056b8590979efa161fb45fdaa878072edeb6db | H-Cong/LeetCode | /23_MergeKSortedLists/23_MergeKSortedLists_2.py | 1,923 | 4 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
# Divide And Conquer
# idea: group two lists together and use the 21 merge ... |
48ee71f6cc18fb5d27fcaf8df77f5892b415fc1d | whglamrock/leetcode_series | /leetcode706 Design HashMap.py | 2,652 | 3.90625 | 4 |
class ListNode:
def __init__(self, key, value):
self.key = key
self.value = value
self.next = None
self.prev = None
# the double linked list solution should satisfy the need in real interview
class MyHashMap(object):
def __init__(self):
"""
Initialize your da... |
2430cbc3ec3512b3b12890dfaa059bddf44c8fd5 | nisimperets/assignment-1-complete | /ex1 q2.py | 1,408 | 3.96875 | 4 |
def check_palindrome():
"""
Runs through all 6-digit numbers and checks the mentioned conditions.
The function prints out the numbers that satisfy this condition.
Note: It should print out the first number (with a palindrome in its last 4 digits),
not all 4 "versions" of it.
"""
#number_t... |
e887d14ab495ff5002ec77c1812a6ccb7da9399b | mavhamm/FATEC-ALOG | /AlogTrab4.py | 1,007 | 3.78125 | 4 | '''
Trabalho #4 de ALOG | 31/05/2019
Conversão para binário
@ Renan
Explicação:
Expoente começa em 7 e descresce a cada iteração.
Ex.: como 7 >= 2³ não é verdade, o expoente diminui e só.
Agora, 7 >= 2², então subtrai-se 2² de 7, e adiciona-se 10² à var binário
10² = 100, que é 4 em b... |
79b95439a6ea12d263f9695d8234d49be33c7c2c | HwangSangBin/Level-Test | /1157.py | 293 | 3.703125 | 4 | Alpa = input().upper()
biggest = 0
a = 0
for j in range(26):
total = Alpa.count(chr(65 + j))
if total > biggest:
biggest = total
biggest_Alpa = chr(65 + j)
elif total == biggest:
a = biggest
if a == biggest:
print("?")
else:
print(biggest_Alpa) |
b488b3b15211414fbfbbbae9b7726a63d714b366 | gabriellaec/desoft-analise-exercicios | /backup/user_084/ch24_2020_03_11_12_32_53_419016.py | 168 | 3.75 | 4 | def calcula_aumento(S):
S=int(input('qual o valor do salario atual: ')
if S>1250:
A=S*1.1
return(A)
else:
A=S*1.15
return(A) |
78c9a5cb36acba88a7a333eb7ca32e19eab367fc | ashraf-a-khan/CodeWars-Python | /TwoOldestAges.py | 662 | 4.1875 | 4 | """
The two oldest ages function/method needs to be completed. It should take an array of numbers as its argument and return the two highest numbers within the array. The returned value should be an array in the format [second oldest age, oldest age].
The order of the numbers passed in could be any order. The array wi... |
083e6899b6eff12ae956e5b00c6b4384034e040d | yiyinghsieh/python-algorithms-data-structures | /lc0021_merge_two_sorted_lists.py | 2,110 | 3.875 | 4 | """Leetcode 21. Merge Two Sorted Lists
Easy
URL: https://leetcode.com/problems/merge-two-sorted-lists/
Merge two sorted linked lists and return it as a new sorted list.
The new list should be made by splicing together the nodes of the first
two lists.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
"""
... |
c77312dd71aa5cc6691d2520f9d31028cc36da59 | pn/adventofcode | /2020/day16p1.py | 574 | 3.59375 | 4 | lines = [line for line in open('input16.txt').read().splitlines() if line]
i = 0
rules = []
for i, line in enumerate(lines):
if line.startswith('your ticket:'):
break
rules.append(list(list(int(r) for r in rule.split('-')) for rule in line.split(': ')[1].split(' or ')))
tickets = []
for line in lines[i ... |
42660439775a81d1f40739011cd91ac9f30ad279 | gonayak/assignment | /lab3_a.py | 295 | 4.03125 | 4 | #a. Write a function that accepts an integer and returns True
# if the input is between 4 and 10, inclusive; otherwise, return False
def intergernum(n):
if n in range(4,11):
print True
else:
print False
n= int(raw_input("Enter the number : "))
intergernum(n) |
5e89e648aa8cdf85fa6807a222ef28e038aa657d | Jivanni/Simple-login-system | /main.py | 2,541 | 4.0625 | 4 | #defining errors
class Error(Exception):
pass
class Useralreadyexists(Error):
pass
class Invalidcredentials(Error):
pass
#opens the database with user information
with open("pass.txt","r") as filehandler:
users = [user.split() for user in filehandler.readlines()]
# checks if username or em... |
867a08064d4f264c9e022f0e72e9669a1fe6cdf9 | HuaiHsin/reviews-analytics | /read.py | 2,451 | 3.703125 | 4 | #讀取檔案
def read_file(filename):
data = []
count = 0
with open(filename, "r") as f:
for line in f:
data.append(line)
count += 1
if count % 1000 == 0:
print(len(data))
print("檔案讀取完了,總共有:", len(data), "筆資料!")
return data
#統計資料
def count_result... |
6369f4bb0a28e2b1db9893f66f81addff7d7f853 | johncrook/logic-puzzle | /townWithUpdatedGUI.py | 12,378 | 4.03125 | 4 | from Tkinter import *
#THE BEST THE BEST THE BEST THE BEST THE BEST THE BEST THE BEST THE BEST
#THE BEST THE BEST THE BEST THE BEST THE BEST THE BEST THE BEST THE BEST
#THE BEST THE BEST THE BEST THE BEST THE BEST THE BEST THE BEST THE BEST
#THE BEST THE BEST THE BEST THE BEST THE BEST THE BEST THE BEST THE BEST
... |
8e28d447661aa5331e6693779a2d0635c0ac840b | PratikNN/Python-Assignment3 | /5.py | 314 | 4.125 | 4 | #5.write a program to read a tuple with months,and days convert tuple into dictionary.
#list of tuples
tup=[('jan',31),('feb',28),('mar',31)]
d={}
for i in tup:
key=i[0]
val=i[1]
d[key]=val
print(d)
#tuple of tuples
tuple=(("jan",31),("feb",28),("mar",31),("apr",30))
print(dict(tuple))
|
37ae6ae62364efb6dbeae7f2a083f9f104925bd0 | Mike-Whitley/Programming | /cosc367 AI - Machine learning/l7q1.py | 503 | 3.8125 | 4 | import copy
def swapPositions(list, pos1, pos2):
list[pos1], list[pos2] = list[pos2], list[pos1]
return list
def n_queens_neighbours(state):
answer = []
lst_state = list(state)
for i in range(len(state)):
for j in range(i, len(state)-1):
new_list = copy.copy(lst_state)
... |
28c1c943d99de36202c29a1c2e500fd4feb41523 | robertoTlapa/cursoPython | /CURSO PYTHON/numeroSecreto_While.py | 549 | 3.890625 | 4 | numeroSecreto = 777
numero = int(input(
"""
+==================================+
| Bienvenido a mi juego, muggle! |
| Introduce un número entero |
| y adivina qué número he |
| elegido para ti. |
| Entonces, |
| ¿Cuál es el número secreto? |
+======... |
6948a66cbfd117e9b19d6997d6bcb450f6f13688 | pater8715/SimulationModelSaturday | /Ejercicios/JHONAR JOSE VERGAR PICO/ejercicio49.py | 202 | 3.65625 | 4 | persona = {}
mas= 'si'
while mas =='si':
key = input('que datos quiere introducir' )
value = input(key + ': ')
persona[key] = value
mas = input('quiere añador mas informacion (si/no) ') |
70d7e896de90831db4725c1407bdf1e3bc8d62f7 | jashjchoi/holbertonschool-higher_level_programming | /0x03-python-data_structures/7-add_tuple.py | 420 | 3.75 | 4 | #!/usr/bin/python3
def add_tuple(tuple_a=(), tuple_b=()):
ta = len(tuple_a)
tb = len(tuple_b)
newtup = ()
for i in range(2):
if i >= ta:
a = 0
else:
a = tuple_a[i]
if i >= tb:
b = 0
else:
b = tuple_b[i]
if (i == 0):
... |
64ef399d2d5e128f67e8f8fa285729c91f766f97 | dmaterialized/python-learning | /learning9.py | 382 | 3.9375 | 4 |
# this script creates an empty file.
import datetime
filename=datetime.datetime.now()
now = datetime.datetime.now()
#create an empty file
def create_file():
# ''' this function creates an empty file '''
with open(str(filename.strftime("%Y-%m-%d-%H-%M")),'w') as file:
file.write("") # """ writing empty stri... |
4cb1f4fc2217cad4fc531b53081abd7590cf9906 | HankerZheng/LeetCode-Problems | /python/146_LRU_Cache.py | 4,563 | 3.90625 | 4 | # Design and implement a data structure for Least Recently Used (LRU) cache.
# It should support the following operations: get and set.
# get(key) - Get the value (will always be positive) of the key
# if the key exists in the cache, otherwise return -1.
# set(key, value) - Set or insert the value if the key is not al... |
1650e5e931dd534d7a19ab4f6f62156bf2dc0b6b | schoentr/data-structures-and-algorithms | /code-challanges/401_code_challenges/trees/test_fizzbuzz.py | 845 | 3.546875 | 4 | from trees.tree import BinaryTree, BinarySearchTree
# from fizzbuzz import fizzbuzz
def test_fizzbuzz_one():
numbers = BinarySearchTree()
numbers.add(1)
numbers.add(3)
numbers.add(28)
numbers.add(90)
numbers.add(10)
numbers.add(18)
numbers.add(21)
numbers.add(65)
numbers.add(100)
ex... |
fb5b97cbdc6ddcdada9ce77be86c82d854ec79a6 | Sailer43/Python_library | /Collection/__linked_list__.py | 3,710 | 3.734375 | 4 | __name__ = "Linked List"
"""TO_DO"""
class __linked_list__:
"""TO_DO"""
class __node__:
"""TO_DO"""
def __init__(self, list_refer, data = None):
self.data = data
if (list_refer.has_next):
self.post_node = None
if (list_refer.has_pr... |
2c057cae01e979404c691ccb7e4d33a933c9c83e | jbfrrr/code-drills | /numbers/primes/find_next_prime.py | 487 | 3.65625 | 4 | import unittest
from is_prime import isPrime
def findNextPrime(number):
if (isPrime(number+1)):
return number+1
else:
return findNextPrime(number+1)
class FindNextPrimeTest(unittest.TestCase):
def testFindNextPrime(self):
self.assertEqual(findNextPrime(100003573), 100003601)
... |
896a6c6ca5f6655c208355d8237ef66abf7e5fa6 | southerton81/py_algo | /merge.py | 1,267 | 3.921875 | 4 | inv_count = 0
# Inversions count, how far (or close) the array is from being sorted.
# If array is already sorted then inversion count is 0. If array is sorted
# in reverse order that inversion count is the maximum.
def mergeSort(alist):
global inv_count
#print("Splitting ",alist)
if len(alist)>1:
... |
6bed6710255b0156783d122a9f5d1ee6fecc8b09 | KellyJason/Python-Tkinter-Turtle-Example | /Tkinter_Walkthrough_4.py | 1,277 | 4.40625 | 4 | import os
import tkinter as tk
import turtle
#begining of the window
root= tk.Tk()
#this creates an area for the labes and button to go in
canvas1 = tk.Canvas(root, width = 350, height = 250, bg = 'lightsteelblue2', relief = 'raised')
canvas1.pack()
# this is the label
label1 = tk.Label(root, text='Want ... |
0701168c3ac04379a5e76e3ec675e3549756c7f6 | Cynthiaore9/moor-siwes | /ass2.py | 94 | 4 | 4 | age = int(input("Enter Age: " ))
print(f"conversion of {age} to days is {365 * age}")
|
b9f69bdc834d167c3cc92132491e98e89b1f67ca | Yarince/Crawler-Kruipertje | /app/utils/json_helper.py | 533 | 3.609375 | 4 | import json
class JsonHelper:
"""
This class can help with JSON strings
"""
@staticmethod
def to_json(value):
"""
This method changes a dict to json value
:param value: anything
:return: json string
"""
return json.dumps(value, ensure_ascii=False)
... |
d80877f67934917aba1da4ca6860b12321ca1ab3 | taoyan/python | /Python学习/day08/子类继承父类,不能直接使用父类的私有属性和方法.py | 356 | 3.5 | 4 | class Person():
def __init__(self):
self.__age = 10
def __show(self):
print('我是一个私有方法')
def text(self):
print('我是一个共有方法')
class Student(Person):
def show(self):
#访问父类的私有方法
# print(self.__age)
self.text()
student = Student()
student.show() |
dfce0e42d462b242f582563f778e80c716be44f3 | derekthecool/MyCodingPractice | /2020-11-12_AgeToDays/code.py | 131 | 4.15625 | 4 | #!/usr/bin/python3
# Age To Days Challenge
age = int(input('Enter your age in years: \n'))
print(f"You are {age * 365} days old")
|
e1a4789f85b764461f15a2db457d9c31ad02367f | thunderlai/ProjectEuler | /largestprimefactor.py | 653 | 3.8125 | 4 | import math
def largestprimefactor(n):
largest = 1
y = 0
# first take the square root of the number, use the ceiling
# we will iterate up to this, checking the largest prime number?
nsqrt = int(math.ceil(math.sqrt(n)))
# as soon as we find the current lowest divisible facotr, we should check th... |
52347a71f8b51e60a0f7590b7aaa3dd7d427c159 | sbeleuz/states-of-the-world | /models/country_model.py | 2,377 | 3.953125 | 4 | """This module is responsible for modeling a Country from a SQL object to a Python object.
It uses SQLAlchemy as on ORM.
"""
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, Float, String
Base = declarative_base()
class Country(Base):
"""A class used to represent ... |
b350e96da2859a4010d979ac7d82403173802216 | cmajorsolo/Python_Algorithms | /Codility100PercentPerformanceAnswers/MaxProductOfTree.py | 1,110 | 3.796875 | 4 |
def solution(A):
A.sort(reverse=True)
positiveArray = [i for i in A if i > 0 ]
negtiveArray = [i for i in A if i <=0 ]
print(A)
print(positiveArray)
print(negtiveArray)
if len(positiveArray) >= 3:
result1 = positiveArray[0] * positiveArray[1] * positiveArray[2]
if len(negt... |
0b1a0ae7e839a8da008cc23f86bfbc634c9b879d | JeffWb/Python-DataStructure | /linear table/chain table.py | 3,084 | 3.640625 | 4 | """
_*_ coding:utf-8 _*_
@Auther:JeffWb
@data:2018.11.22
@Version:3.6
"""
#node
class LNode:
def __init__(self, elem,next_ = None):
self.elem = elem
self.next = next_
#error
class LinkedListUnderflow(ValueError):
pass
#single chain table
class LList():
#initialize
def __init__(self,head = None):
self._... |
d4e08e348fa48cfce4c62463089ac858a8e1d1d0 | snapf/python-1811 | /Week8/test_sim_projectile.py | 2,523 | 3.5625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 20 14:49:01 2017
@author: ctchou
"""
import numpy as np
import matplotlib.pyplot as plt
import sim_projectile as sim
# Script name: testSimulateProjectile
#
# Purpose: This script is used to test whether the function
# simulateProjectile is worki... |
29fe2fd77262479aab5d6d514771ce820c16f583 | matt24ck/matt24ck-ds1 | /to-lower-case.py | 359 | 3.703125 | 4 | #!/usr/bin/env python
upper = "ABCDEFGHIFKLMNOPQRSTUVWXYZ"
lower = "abcdefghifklmnopqrstuvwxyz"
i = 0
s = raw_input()
while s != "end":
i = 0
while i < len(s) and i < len(upper):
if s[i]
i += 1
j = 1
while j < len(s) and j > 0 and s[(len(s) - j)] != ":":
j += 1
print s[:i], s... |
0a5b6dfeddf135cd4dd5916fc145b975ec02c1a0 | Hamsik2rang/Python_Study | /Day13/Sources/Day13_6.py | 128 | 3.859375 | 4 | # Bottom up Fibonacci in Python
fibo = [1, 1]
for _ in range(8):
fibo = [fibo[-1], fibo[-1]+fibo[-2]]
print(fibo[-1]) |
652d19c214a8650a14e056544e2ee47fc003b34b | EugeneHochenedel/GenericAlgorithms | /GeneticParser/GeneticParser.py | 4,726 | 3.59375 | 4 | def varMapping(list, translate):
int = 0;
for items in (list):
if (items == translate):
return int;
else:
int += 1;
def Main():
#Opens and reads the file
inFile = open("Expression.txt", 'r');
#Does the following for every expression in the opened file
for expression in (inFile):
#Boolean to de... |
3fea72c1f2e860c543a68bcc3ff6f3c7de7feac5 | sudhanshuptl/Python_codeskulptor_mini_Games | /Guess the Number/Guess the number.py | 1,601 | 4.03125 | 4 | # Guess The Number
# Sudhanshu Patel
# NIT Rourkela
import simplegui
import random
import math
# initialize global variables used in your code
num_range = 100
attempt = 7
Number = 0
# helper function to start and restart the game
def new_game():
print ""
print "New game. Range is ... |
273cf8774f33efa0925f0af25b67e38651abf32f | MonikaSophin/python_base | /2.2 string.py | 1,141 | 4.34375 | 4 | """
2.2 基本数据类型 -- String(字符串)
"""
## 字符串运算符
str1 = "hello world!"
print(str1)
# + 字符串拼接
print(str1 + " 你好")
# * 重复输出字符串
print(str1 * 3)
# [] 通过索引访问字符串
print("str1[1] =", str1[1])
# [:] 通过左闭右开区间截取字符串
print("str1[1:4] =", str1[1:4])
# in 成员运算符(不区分大小写) - 如果字符串中包含给定的字符返回 True
print("h in str1", "h" in str1)
# not in 成员运算符... |
a8ed13c64fe1d1007441ac0c8c2d453443f31ede | reshmarn28/Python-Programs | /HP/HP_afternoon/datastrctures.py | 563 | 3.78125 | 4 | #Set
# s1 = {10,20,30}
# s2 = {30,40,50}
# print(s1.union(s2))
# print(s1.difference(s2))
# str = input("Enter a string")
# s = set(str)
# v = {'a','e','i','o','u'}
# d = s.intersection(v)
# print("Vowels in",str,"are:",d)
#tuple
t1 = (10,20,30,40,29,40,10,10,10,10,1.4,2.6)
# print(t1[1:5])
# print(len(t1))
# print(t1... |
01310fee10fe47b64af3dc446b6337d2daee97c2 | Bdl-1989/Bdl-1989.github.io | /codeFile/dfs.py | 852 | 3.796875 | 4 | # Python
def recursion(level, param1, param2, ...):
# recursion terminator
if level > MAX_LEVEL:
process_result
return
# process logic in current level
process(level, data...)
# drill down
self.recursion(level + 1, p1, ...)
# reverse the current level status if needed
#Pyth... |
096dd7426667aa76f9879338a058ac15fba6d475 | shaunlee0/PythonPractise | /PythonBookWork/PERT-estimator.py | 694 | 3.5625 | 4 | print("Welcome to the PERT estimation script\n=====================================")
optimal = int(input("Please enter the optimistic estimation in man days for your task...\n> "))
nominal = int(input("Please enter the nominal estimation in man days for your task...\n> "))
pessimistic = int(input("Please enter the pes... |
8e543eda71e903d5d6115a926f152693009945b8 | Dre-AsiliVentures/Python-Programming-scripts | /Py 55.py | 197 | 3.78125 | 4 | try:
variable=10
print(variable+ "hello")
print(variable/2)
except ZeroDivisionError:
print("Divided by zero")
except(ValueError,TypeError):
print("An error occurred.")
|
e529b8df47bbb869b81bdb747011d52f53209f1d | LukeMi/python | /PythonCode/com/lukemi/primary/Test.py | 784 | 3.53125 | 4 | class tClass():
def __init__(self, orig=0):
self.storedValue = orig
def read(self):
return self.storedValue
def write(self, x):
self.storedValue = x
def Test():
a = tClass()
print
"a: " + str(a.read())
a.write(10)
print
"a: " + str(a.read())
b = tClas... |
71fe706e558f9791df707dc353f77101544dfd41 | iamrishap/PythonBits | /DataStructure/arrays.py | 2,029 | 3.8125 | 4 | from collections import Counter
def rotator(A):
'''
>>> A = [[1, 2, 3], \
[4, 5, 6],\
[7, 8, 9]]
>>> rotator(A)
[(7, 4, 1), (8, 5, 2), (9, 6, 3)]
'''
print([a[::-1] for a in zip(*A)])
# print(list(map(list, zip(*A)))[::-1])
def duplicates(A):
'''
>>> duplicates([1,2... |
69de6e9b7bd5bbe002f444ca77f61aef6318c535 | florianschaal/Labyrinthe | /src/server/robotClass.py | 3,621 | 3.953125 | 4 | #!/usr/bin/python3.5
# -*-coding:Utf-8 -*
"""Provide class Robot"""
from ..setup import *
import random
class Robot:
"""Permet de jouer avec le robot sur une carte"""
def __init__(self):
"""Définition initiale de tous ses attributs"""
self.coord = {}
self.newCoord = {}
self.direction = ''
self.nbMove =... |
914c9a4d8bf78d45333bc757c6029e323c8b84eb | flaxdev/N-g.datamining | /src/iterators.py | 2,195 | 3.671875 | 4 | from src.geometry import Position
class PropertyIterator():
"""
Class PropertyIterator
Linearly iterates over properties from start to end in n steps
"""
def __init__(self, iterators):
self.iterators = iterators
self.steps = sum(map(lambda x: x.steps, iterators))
self._currentIterator = self.i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.