blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
fb1f61a933edbd2f8514ff357dc39fcca95f8399 | koenveelenturf/Python-Stuff | /calculator.py | 1,028 | 4.1875 | 4 | #!/usr/bin/env python3
import sys
print("Calculator: ")
print("1) Add")
print("2) Substract")
print("3) Multiply")
print("4) Divide")
print("q) Quit this program")
numbers = []
choice = None
def options(prompt, option=('1', '2', '3', '4', 'q')):
while True:
choice = input( prompt )
if len(choice) < 1:
retur... |
64d48d4f605e01cd613642f05941a478fd14900b | uskey512/projectEuler | /0002/0002.py | 290 | 3.625 | 4 | def get_fibonachi_even_sum(maxOfNumber):
a = 1
b = 2
result = 0
tmp = 0
while b <= maxOfNumber:
if b % 2 == 0:
result += b
tmp = a + b
a = b
b = tmp
return result
print(get_fibonachi_even_sum(4000000))
|
de0cbe13f9dbacc4640f6762178a166ec63f87b8 | HenriTammo/OMIS | /tund1/kasutajaSisestus.py | 178 | 3.546875 | 4 | nimi = input("Mis on sinu nimi")
print ("Tere ", nimi)
arv = int(input("Palun sisesta mingi number"))
print (arv)
koma = float(input("Palun sisesta mingi number"))
print (koma) |
1d3657ddeb03b38bbcda2a3268c105a8ea21949b | BretRunestad/currency-converter | /currency.py | 1,110 | 4.1875 | 4 | def convert(rates, value, from_string, to_string):
"""Takes a list of rates, an amount of currency(value), a from_string, and
a to_string. It cross references the 'from' and 'to' strings to find the
applicable currency exchange rate. It then multiplies the value by that
rate, rounded to 2 decimal plac... |
a2e2a39534ce9e08dcc9e78f891be0aa7205fcfa | alexDx12/gb_python | /lesson_2/exercise_5.py | 544 | 3.828125 | 4 | my_list = [7, 5, 3, 3, 2]
new_item = int(input("Введите новый элемент рейтинга: "))
if new_item > max(my_list):
my_list.insert(0, new_item)
elif new_item < min(my_list):
my_list.append(new_item) # вопрос: можно ли вставить элемент в конец списка функцией insert? как указать
# последний индекс?
else:
in... |
6b1c758431647b2b9e1b1db93dc4944d522bb759 | CUGshadow/Python-Programming-and-Data-Structures | /Chapter 02/Exercise_02_05.py | 646 | 3.9375 | 4 | '''
(Financial application: calculate tips)
Write a program that reads the subtotal and the gratuity rate and
computes the gratuity and total. For example, if the user enters 10
for the subtotal and 15% for the gratuity rate, the program displays 1.5
as the gratuity and 11.5 as the total.
'''
subtotal = float(input('... |
7089795e38c4923f4e645a36dbd301ccecff0929 | urszulasologub/TDD | /calculator.py | 630 | 3.515625 | 4 | import math
class Calculator:
def __init__(self) -> None:
self.history = []
def add(self, a, b):
result = a + b
self.history.append(result)
return result
def sub(self, a, b):
result = a - b
self.history.append(result)
return result
def mul(sel... |
e9ea50bbf34ad4f74ae759b8211d060a385040d2 | jwstes/BlueLeg | /Receipt.py | 1,265 | 3.546875 | 4 | from datetime import datetime
class Receipt():
def __init__(self, items, customerID):
self.__items = items
self.__customerID = customerID
self.__date = self.generate_date()
self.__totalPrice = self.generate_totalPrice()
def generate_date(self):
y = datetime.now(... |
2fecd51a785efcd67ab87ddc576eafbfb9856f58 | amidying/python_chap_06 | /problems/07_pr.py | 277 | 4.28125 | 4 | # post = "Once upon a time there was a boy named Ali Neaz. He was very stupid and still he is a stupid"
post = input("Enter the post: \n")
if "Ali Neaz" in post or "ali neaz" in post:
print("they are talking about Ali Neaz")
else:
print("they are not talking about Ali Neaz")
|
06e515634bc40b2d4abaa955c714f2b970b2f5a2 | mscroggs/Logic-Bot | /test/test_sequence.py | 760 | 3.5 | 4 | from logic import FormulaFactory
from time import time
def test_sequence():
start = time()
f = FormulaFactory()
f.next()
leng = 0
count = 0
while leng <= 9:
if f.formula.is_tautology():
count += 1
f.next()
while len(f.formula) > leng:
if leng =... |
5b893b3b118bb4e05af88ba06d50cf12b2fe1f5f | eriksandgren/AdventOfCode2017 | /day05/day5.py | 772 | 3.546875 | 4 | #!/usr/bin/env python
def parseInput():
with open ("input.txt", "r") as myfile:
myInput = myfile.read()
myInput = myInput.split('\n')
return myInput
def part1():
s = parseInput()
myInput = [int(x) for x in s]
maxInd = len(myInput) - 1
ind = 0
steps = 0
while ind <= maxInd and ind >= 0:... |
bb68d2733fe632ed32d530eb886c654e57ca1e02 | RomanPutsilouski/M-PT1-37-21 | /Tasks/Titov_Tasks/Task7/task7.py | 4,579 | 3.609375 | 4 | import random
import task7_maze as mz
from abc import ABC, abstractmethod
class Entity(ABC):
@abstractmethod
def __init__(self, name, class_entity, damage, hp, lvl=1):
self.__name = name
self.__class_entity = class_entity
self.__damage = damage
self.__hp = hp
self.__lv... |
6a4460f488d83354311005a0a7b870476310cfab | kjuao9/coisas-de_python | /Python/2° Tri/Atividades/Atividades Tuplas/tuplas3.py | 265 | 3.65625 | 4 | import random
x = 0
a = random.randint(0,100)
b = random.randint(0,100)
c = random.randint(0,100)
d = random.randint(0,100)
e = random.randint(0,100)
tupla = (a,b,c,d,e)
print(tupla)
print("O maior número é:",max(tupla))
print("E o menor número é:",min(tupla))
|
1615ff3036295f89611eec0c65cf5f1415e089a4 | fmejias/FelipeMejiasLoria-IA-117 | /Ejercicios/E5-pacman-astar/pacman-astar.py | 16,806 | 3.859375 | 4 | ####This class represent a vertex of the graph ####
class Vertex:
###
# self.vertex_id = contains the label of the vertex
# self.visited = indicates if the node has been visited
# self.adjacent_vertex_list = contains all of the adjacent vertex of the vertex
###
def __init__(self,vertex_id,x,y):
... |
11a7a39d2a3b7cba6ef51012bbeeb106c6aad81b | taboyz/CI4003-NIDA | /homework_kronprom/week2/Leap_Year.py | 375 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on
@author: kronprom
"""
input_year = input("Enter AD year:")
try:
cal_year = int(input_year)
except:
cal_year = 0
if (cal_year % 100) == 0:
if cal_year % 400 == 0:
print ("leap year")
else :
print("NOT leap year")
elif cal_year % 4 == 0:
print... |
787e33fdf05e0aea0e879da8d9635d4380027cad | jbell1991/code-challenges | /challenges/leetcode/fizzbuzz/fizzbuzz.py | 656 | 3.953125 | 4 | def fizz_buzz(n):
# empty list
l = []
# iterate over each number from range 1 to n
for i in range(1, n + 1):
# if num % 3 == 0 and num % 5 == 0:
if i % 3 == 0 and i % 5 == 0:
# append "FizzBuzz" to the list
l.append("FizzBuzz")
# elif num % 3 == 0:
... |
9485e25c64025362756395ab3ea64a11d9a4af03 | akjiglar/Basic-Python-Program | /fact.py | 143 | 3.765625 | 4 | a=[2,4,3]
print("no of elements:-",len(a))
c=len(a);
for i in range (0,3):
for j in range (0,3):
print(a[j:c])
c--;
|
ce67ba4e60cb38b2d883e5a076b319d9f5264dd8 | matchado/Misc | /gower_dist.py | 1,268 | 3.890625 | 4 | import pandas as pd
import numpy as np
from sklearn.neighbors import DistanceMetric
def gower_distance(X):
"""
This function expects a pandas dataframe as input
The data frame is to contain the features along the columns. Based on these features a
distance matrix will be returned which will contain th... |
d7447d9037d4385632dd3779732e5ed016219067 | bakmaks/Algorithms | /Решето Эратосфена - простые числа/prime_numbers.py | 1,243 | 3.90625 | 4 | n = int(input("Введите натуральное число: "))
# список заполняется значениями от 0 до n
a = []
for i in range(n + 1):
a.append(i)
# Вторым элементом является единица,
# которую не считают простым числом
# забиваем ее нулем.
a[1] = 0
# начинаем с 3-го элемента
i = 2
while i <= n:
# Если значение ячейки до это... |
4ba55162de752114ae2b2542325119d91422f6e3 | yangzongwu/leetcode | /archives/leetcode/0041. First Missing Positive.py | 1,221 | 3.953125 | 4 | '''
Given an unsorted integer array, find the smallest missing positive integer.
Example 1:
Input: [1,2,0]
Output: 3
Example 2:
Input: [3,4,-1,1]
Output: 2
Example 3:
Input: [7,8,9,11,12]
Output: 1
Note:
Your algorithm should run in O(n) time and uses constant extra space.
'''
class Solution:
def firstMissingPosi... |
8ec86445c06d6ade17af41a84369264f547522a8 | mallikag99/bioinfo | /IntroPython/prog5.py | 485 | 3.828125 | 4 | #!/usr/bin/env python
#program to print out coding sequence and non-coding sequence in upper case and lower case respectively
myDNA2 = 'ATCCTCGGTCGATTCAACTGTAAGTCCCATGAGTCGCTATCGTATTGGATCGATCTTGGATCGAATCGATCGCGATCGATCAAAATCATGCTATCTTTATCGATCGATATCGATGCATCGACTACTAT'
coding_exon1 = myDNA2[0:53].upper()
noncoding_intron ... |
a9680ffa3c4b85b5faac6ceeee0e2452efcab802 | Qhupe/Python-ornekleri | /Eğitim Çalışmaları/Mantık_karsılastırma.py | 810 | 3.984375 | 4 | # Mantıksal Değerler (Boolean) bir veri tipi olup iki değere sahiptirler
# True ve False değerleri alan değişkenlerdir
a = True
b = False
print(type(a), type(b)) # satır çalıştığında tip olarak bool çıktısı alacağız
#Pythonda bir sayı değeri 0 dan farklı olduğu sürece true değeri dönderir
print(bool(14),bool(... |
3dd805760a918a998200208d6e4a5ce24b30bd37 | cifpfbmoll/practica-6-python-fperi90 | /P6ej6.py | 1,138 | 4.3125 | 4 | # Escribe un programa que pida primero dos números (máximo y mínimo) y que después te pida números intermedios. Para terminar de escribir números, escribe un número que no esté comprendido entre los dos valores iniciales. El programa termina escribiendo la lista de números.
# Escribe un número: 6
# Escribe un número ... |
925818576889943fa6d2177ee79ab42d7586eebf | Umekawa/nlp100knock2020 | /chapter01/problem009.py | 588 | 3.6875 | 4 | import random
def random_except_head_and_tail(s):
if len(s)<=4:
return s # もっと良いアーリーリターンの書き方がある気がする
sorted_s = s[0]
tail = s[-1]
rand = random.sample(range(len(s)-2), len(s)-2)
for i in rand:
sorted_s+=s[i+1]
return sorted_s + tail
s = 'I couldn’t believe that I could actually understand what I wa... |
45c80a7e39880665e9fa7dde2a9dd7102a00771f | Pathogene027/Pathogene | /adventure.py | 4,129 | 4 | 4 | import time
# title
print('*****************************')
print('*****************************')
print('* * * *')
print('* * The Hospital * *')
print('* * Episode * *')
print('* * * *')
print('*****************************')
print('*****... |
8e44158cedc8c2263a064b1aa8e1980695c85b77 | yuva671/Guvi | /ZEN Class/1/prime.py | 173 | 3.78125 | 4 | n=int(input())
count=0
for i in range(1,n):
if(n%i==0):
count+=1
print(count)
if(count>1):
print("not prime")
else:
print("prime")
|
907e0b07332f2ace5cdc42fa08a6c7792f0c78c4 | mitokohaku/Algorithm | /Learn/DataStructure/Tree/Trie_Tree/code.py | 2,145 | 3.671875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/2/2 10:46
# @File : BubbleSortCode.py
# ----------------------------------------------
# ☆ ☆ ☆ ☆ ☆ ☆ ☆
# >>> Author : Alex
# >>> QQ : 2426671397
# >>> Mail : alex18812649207@gmail.com
# >>> Github : https://github.com/koking0
# ☆ ☆ ... |
3e42d51ebe7e1955e67072b516160ef104bbc299 | vijaygao/jianzhioffer | /二进制中1的个数.py | 834 | 3.5625 | 4 | # 输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
# 负数应该为绝对值原码,第一位变为1,然后取反(符号位不变)加1,这就是补码。
# 比如 -1。 000000000000001变1000000000001变1111111111111110变1111111111111111111
# -*- coding:utf-8 -*-
class Solution:
def NumberOf1(self, n):
# write code here
temp = []
if n >= 0:
while n:
... |
d925d741f701aec1b7b4678ea157694c27514f30 | bumsol2/python | /Chapter8/06.실습문제8.1.1.py | 1,302 | 4.03125 | 4 | # 클래스 생성
class Item:
def __init__(self, name, price, weight, isdropable):
self.name = name
self.price = price
self.weight = weight
self.isdropable = isdropable
def sale(self):
print(f"[{self.name}] 판매가격은 [{self.price}]")
def discard(self):
if self.isdropable... |
aabd3a263fb4313f48b63f04aa50ed187392a65e | RyanAVelasco/rock-paper-scissors | /main.py | 4,082 | 3.734375 | 4 | import random
import os
import colored
from colored import stylize
options = ['rock', 'paper', 'scissors']
score = {
'victory': 0,
'loss': 0,
'draw': 0
}
# print('[ Score ] | [ BOT:', score['loss'], '] | [ PLAYER:', score['victory'], ']')
counter = int(input('Rounds in game: '))
while True:
os.system... |
28a284d48ac660230457d7ab63e1b3a1af8c092c | Vishnu4497/Sri-Hari-Vishnu-17P245 | /Translate Words/Task.py | 2,190 | 3.6875 | 4 | from time import process_time #TO CALCULATE TIME TAKEN TO PROCESS
Time_start = process_time() #START THE PROCESS TIME
# TO READ FIND_WORDS.TXT FILE AS A LIST
Find_Words = open("find_words.txt","r")
Find_Words_String = Find_Words.read()
Find_Words_List = Find_Words_String.split("\n")
# TO READ T8.SHAKESPE... |
d8637521559cf1d66d2ffc8ad9842d02168fa229 | quangngoc430/PeFile-View | /hexdumpfile.py | 1,680 | 3.5625 | 4 | import sys
import os.path
def read_bytes(filename, offset=0, chunksize=8192):
# This method returns the bytes of a provided file ##
try:
with open(filename, "rb") as f:
f.seek(offset)
while True:
chunk = f.read(chunksize)
if chunk:
for b in chunk:
yield b
... |
6b6a61a313c31cb5c41a20b4bd16f6831dadad67 | NightFaint/leetcode | /python/869. Reordered Power of 2.py | 655 | 3.640625 | 4 | #coding:utf-8
__author__ = 'NightFaint'
__date__ = '2018/7/20 20:27'
import collections
class Solution:
def reorderedPowerOf2(self, N):
"""
:type N: int
:rtype: bool
"""
#只要统计str(N)每个元素的个数,与2的n次方比较便可
s=str(N)
c=collections.Counter(s)
len_of_n=len(s)
... |
62548ec1faf0b33779ab20843d0a4190b13a8ee1 | Shawn-H-Wang/Python-Tutorial | /5.2_实现isOdd判断奇偶数.py | 761 | 3.59375 | 4 | def isOdd(x):
if isNum(x):
for i in x:
if i == '.':
print("这个数不是一个正整数!!")
break
else:
a = (int)(x)
if a == 1:
print("这个数为奇数!")
elif a%2 == 0:
print("这个数为偶数!")
else:... |
fabff8dba545b72cc43c06cf9094d710f3ae3dc5 | gtpgg1013/AI_docs | /part3-python/Bigdata/Code04-01 중첩 for문.py | 505 | 3.71875 | 4 | # i, k =0, 0
#
# for i in range(2,10,1):
# for k in range(1,10,1):
# print(i,"*",k,'=',i*k)
import random as rd
from random import randrange, randint #random. 안붙이고 하겠다
from random import * #걍 다 쓰겠다
count = 0
for _ in range(10): # i, k 안쓰는데 왜 있지? : 안쓸때는 지향하는게 낫다 : _로 바꾸기
for _ in range(10):
num... |
82965e734395fb2736c81f144f79c5ebcbb482da | Richa-Kadam/MscCSPaper2 | /FDS_Pract1_permutationsVariationCombination.py | 1,400 | 3.828125 | 4 | #!/usr/bin/env python
# coding: utf-8
# # FDS: PRACTICAL 1 : PERMUTATION AND COMBINATION
# Combinations
# In[25]:
import itertools
from itertools import product
box_1=['g','b']
perm=[]
for p in itertools.product(box_1,repeat=2):
perm.append(p)
perm
# In[26]:
box_2=['g','b','y']
perm=[]
for p in itert... |
4e8b0273136d9f1ab642842a442ff9b65ec16fa5 | a4lamber/seg1d | /seg1d/examples/ex_segmenter_sine.py | 3,130 | 3.53125 | 4 | '''
An example of instancing the Segmenter class to use the convenience methods on array data
.. plot::
>>> import seg1d
>>> import numpy as np
>>> import matplotlib.pylab as plt
Then we generate some data
>>> x = np.linspace(-np.pi*2, np.pi*2, 2000) #create an array of data
>>> targ = np.si... |
27c8d542137764485af432dab6f3dc7b8533b42e | Laixsias/BigdataPython | /6.1.py | 759 | 3.6875 | 4 | # конечный
# from time import sleep
# class TrafficLight:
# __color = ['Красный', 'Желтый', 'Зеленый']
# def running(self):
# i=0
# while i<3:
# print(f'{TrafficLight.__color[i]}')
# if i==0:
# sleep(8)
# elif i==1:
# sleep(6)
#... |
03ef504d2abaa027f4c05306102df8ab63a8d837 | JEmbry2019/tickets_python | /lists.py | 1,360 | 4.375 | 4 | # Declare a named constant for array size here.
MAX_AVERAGES = 8
# Declare array here.
averages = []
# Write a loop to get batting averages from user and assign to array.
for i in range(MAX_AVERAGES):
averageString = input("Enter a batting average: ")
battingAverage = float(averageString)
# Assign value to... |
f0705948dbd2edcbce93ff6de420ddcb3e6e4fa8 | H4MA-A/Network-Tool | /ArgumentParser.py | 3,349 | 3.6875 | 4 | #!/usr/bin/python3
import argparse
import pyfiglet
class ArgumentParser:
argumentParser = None
args = None
def __init__(self):
self.args
def parser(self):
arg = argparse.ArgumentParser(description="[+]Welcome to network security workshop \n [!]This tool is for "
... |
aef195cbee5af4cf1f836baa38ed3b4a51e1ff58 | lukewickstead/PythonPit | /PythonSandBox/Operators/operator_precedence_example.py | 1,153 | 3.6875 | 4 | # operator_precedence_example.py
#
# Operator Precedence Example
# Operators higher up the table have a higher precedence
# Operators on the same row and to the left have a higher precedence
# Operator Description
# ** Exponential ( to the power of )
# ~ + - ... |
8fa2a733c5f2269381ae819662b137c00418e33f | M71-max/Language_Translator | /Translator.py | 288 | 4.0625 | 4 | from translate import Translator
#translate from and to
print("Translates Spanish to English\n\n")
translator = Translator(from_lang = 'Spanish', to_lang = 'english')
message = input('Enter a message to translate : ')
print("\n\nThe Spanish is : ", translator.translate(message))
|
9ee98edf020637e4ed82d09c1a25ca5d25900d40 | sthefanoc/coding-problems | /DailyCodingProblem/2021-01-16-solution.py | 282 | 3.765625 | 4 | # Distance between two strings. Possible moves:
# - Insert
# - Substitute
# - Delete
string_a = 'caixa'
string_b = 'abacaxi'
# How many moves to turn string A into string B?
# Steps:
# 1) Check how many letters, in order, appear from string a to string b
# 2) Fill in the spaces
|
016b823b3fca7ddef1f610dec80abea849efe703 | olearyb/PythonGUI | /turtlefigure.py | 7,183 | 3.734375 | 4 | from turtle import *
import math
import random
'''
pen = Pen()
pen.color("#06CDF4")
pen.speed(0)
pen.width(2)
pen.up();pen.sety(-200);pen.down()
screen = Screen()
screen.bgcolor("gray20")
'''
colors = ["#03CDD2", "#A26DCB", "#FB7299"]
colors2 = ["#5BC0BE", "#6FFFE9"]
def gasket(n, l, pen):
# draw a triang... |
072aedb475c410b6fcd3eeed9b69d59c718a5b52 | dgallegos01/Python-Course | /Lists/List Methods/ListMethods.py | 1,394 | 4.3125 | 4 | # adding, removing and checking existant items in a list
numbers = [5,2,1,7,4]
numbers.append(20) # this will add 20 to the end of a list
print(numbers)
numbers.insert(0, 10) # this will add 10 to index 0
print(numbers)
numbers.remove(5) # this will remove 5 from the list
print(numbers)
numbers.clear() # this will rem... |
42591a617ec3b33b25e99c1376c8dc5df4a9fa70 | sandeepyadav10011995/Data-Structures | /Pattern-Cyclic Sort/1. Cyclic Sort.py | 1,019 | 3.765625 | 4 | """
Cyclic Sort -: This pattern describes an interesting approach to deal with problems involving arrays containing
numbers in a given range.
Question : Given an unsorted array containing n numbers ranging 1 to n. Sort the array in O(N) time !!
Example -:
Input :
Output :
----------------------------... |
a9ee0fceca7149f8828543eebf0d253cd6f20e4e | Salishoma/My-Code-House | /src/com/python/twoSum.py | 769 | 3.9375 | 4 | '''
1. Two Sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example 1:
Input: nums = [2,7,... |
b42604fe8a4e420218450f25d7ca6bda6a11f899 | chenmingjian/did_chenmingjian_coding_today | /.leetcode/322.零钱兑换.py | 1,648 | 3.546875 | 4 | #
# @lc app=leetcode.cn id=322 lang=python3
#
# [322] 零钱兑换
#
# https://leetcode-cn.com/problems/coin-change/description/
#
# algorithms
# Medium (36.40%)
# Likes: 286
# Dislikes: 0
# Total Accepted: 30.7K
# Total Submissions: 84.4K
# Testcase Example: '[1,2,5]\n11'
#
# 给定不同面额的硬币 coins 和一个总金额
# amount。编写一个函数来计算可以... |
5b615d9d50618a51a1e72cba6b2bdaf53777492d | DavidStevenCG14/David-Cespedes-1504047-Primer-Corte | /David S. Cespedes 154047/2017-1-master/02_Homework/04_Int2Words/int2words.py | 3,369 | 4.0625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Program: int2words.py
# Description: This module convert an integer number into spanish words
# Author: Diego Fernando Marin
def int2words(numero):
""" (number) -> string
return the number converted into a string of spanish words
"""
# TODO: return the ... |
79b7cbd08f1e03cdac214f8d799422c0b22c6db9 | NurFaizin/SDP | /Functions/ex22.py | 1,030 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
print "Let's practice everything."
print """You\'d need to know \'bout escapes with \\ that
do \n newlines and \t tabs
"""
puisi = """
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and re... |
685fc14ebeffabda282c061fc9ad316e2200476d | kabir37/techwhizkid | /calculator.py | 596 | 4.15625 | 4 |
print("Select operation.")
print("1. add")
print("2. subtract")
print("3. multiply")
print("4. divide")
print("5. quit")
choice = input("Enter choice(1/2/3/4/5): ")
if(choice == '5'):
print("BYE")
else:
while (True):
if choice in ('1', '2', '3', '4', '5'):
num1 = float(input("Enter first number... |
d19296ec0f5099e9d258ad6dcb682e35be7ddcd1 | ayushidhoble/practice_python | /12th.py | 557 | 4.34375 | 4 | '''
The function max()from exercise 1) and the function
max_of_three()from exercise 2) will only work for
two and three numbers, respectively. But
suppose we have a much larger number of numbers,
or suppose we cannot tell in advance how many
they are? Write a function max_in_list()that takes a
list of numbers and retur... |
3f4a6e3ae24888d576dc7b9f85b08ec5421cc65a | dharmen001/TFR_DB | /Test/AnotherClass/Test2.py | 803 | 3.546875 | 4 |
# """------7--------------------"""
def common_values(list1, list2):
starts_match = list1[0] == list2[0]
ends_match = list1[-1] == list2[-1]
return starts_match and ends_match
print(common_values([1, 4, 5, 6], [1, 3, 5, 6]) )
# --------8------------
def html_tag(text, tag):
return '<{}>{}</{}>... |
4d2369be01f651988894496e1ebb942c3a8ba232 | wmemon/python_playground | /24_days/Day 23/Question97.py | 338 | 3.890625 | 4 | """You are given an integer, N. Your task is to print an alphabet rangoli of size N.
(Rangoli is a form of Indian folk art based on creation of patterns.)"""
def print_rangoli(n):
for num in range(1, n + 1):
for alpha in range(1, num + 1):
print(chr(97 + n - alpha), end='-')
print()
... |
2c196f6b6269388a0392d17d7eb142c140304f43 | permCoding/elective-course-21 | /py/day12/02.py | 162 | 3.671875 | 4 | def F2(n):
if n == 0: # точка останова
return 0
else: # шаг рекурсии
return n + F2(n-1)
n = 10
print(F2(n))
|
5b399b03becff9b3563ff962cc53608215234c2a | amberhappy/-offer | /44-翻转单词顺序列.py | 248 | 3.59375 | 4 | class Solution:
def ReverseSentence(self, s):
s_split = s.split(" ")
s_reverse = s_split[::-1]
return " ".join(s_reverse)
# a = "i am a student"
# aa = a.split(" ")
# print(aa[::-1])
# print(" ".join(aa[::-1])) |
3d65816895e63b887f68da59d6bafd80dd91cd19 | pwildenhain/advent-of-code-2020 | /day2/solution.py | 1,237 | 3.8125 | 4 | # puzzle_input = [
# ["1-3 a", "abcde"],
# ["1-3 b", "cdefg"],
# ["2-9 c", "ccccccccc"],
#]
#Part 1, how many passwords are valid
with open("day2/input.txt") as input_file:
puzzle_input = []
for line in input_file.readlines():
rule, password = line.split(":")
puzzle_input += [[rule, ... |
77406d2a574770eba05971d45bb0821552c331d8 | alvinwang922/Data-Structures-and-Algorithms | /Strings/Roman-to-Integer.py | 580 | 3.78125 | 4 | """
Given a roman numeral, convert it to an integer.
"""
class Solution:
def romanToInt(self, s: str):
roman = {'M': 1000, 'D': 500, 'C': 100,
'L': 50, 'X': 10, 'V': 5, 'I': 1}
ans = 0
for i in range(0, len(s) - 1):
if roman[s[i]] < roman[s[i + 1]]:
... |
133dab9284a762413238bcd9003a1cf1531b0cea | Richie010/uplift-python-resources | /Tuple Problems/max-min.py | 804 | 3.765625 | 4 | # Find the Maximum and Minimum K elements in a Tuple
# """
# It is immutable
# So, we can't change the elemtns of the tuple
# So, we can't modify direct like the list problem
# But, there is a big chance that we can cast it to a List and then solve the problem with
# but it is alwasy better if we can solve directly sta... |
f0354d98b5e614fd35f06c23facaf01e465352b7 | rmoehn/alp2 | /Ueb07/partition.py | 998 | 3.890625 | 4 | from random import randint
def quicksort(A):
def partition(low, high):
assert high - low >= 1 and len(A) > 0
middle = low + (high-low)//2
assert low <= middle <= high
A[low], A[middle] = A[middle], A[low]
pivot = A[low]
i = low
for j in range(low+1,high+1)... |
37f8ea7b453210547750345060b706ea36afb589 | marcinrozycki/PhoneticSpeechTranscription | /TranscriptionFileCreator.py | 1,384 | 3.765625 | 4 | import argparse
import os
class TranscriptionFileCreator:
@staticmethod
def convert_file_into_transcription_file(input_word_file, output_transcription_file):
with open(input_word_file, 'r') as wordFile:
word_lines = wordFile.readlines()
with open(output_transcription_file, 'w') as... |
8383f5ee59cdc7d9f95d940df52ba2a34a526fd8 | Ninjala/leetcode | /easy/38.Count_and_Say.py | 1,113 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Question:
The count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1
2. 11
3. 21
4. 1211
5. 111221
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, th... |
c8c0733d89af863d0a7f6754d3755164ce06cd48 | adilcoelho/sistint_busca | /direction.py | 1,470 | 3.625 | 4 | from enum import Enum
class Direction(Enum):
N = '^'
S = 'v'
E = '>'
W = '<'
NE = '/'
NW = '#'
SW = '%'
SE = '\\'
def __lt__(self, other):
return False
def __le__(self, other):
return False
def prev(self):
if self.name == self.N.name:
... |
cd4906324fb564d58556ff144bc5d0f80cc5186d | yoannssense/python | /algo_phong.py | 1,707 | 4 | 4 | from array import *
# Phong sorting
#
# Algorithm to sort an array of letters alphanumerically first and alternate vowel and consonant.
#
# Examples:
# bike -> ebik
# airport -> apirot
# where > eherw
def phongSort(str):
vowels, consonents = get_sorted_vowels_consonents(str)
result = get_alternated_vowels_... |
8dc3d287a4176915a18c84ca31de56d2aafa492f | fanqi0312/MachineLearning | /PythonBase/PythonBase.py | 5,315 | 4.34375 | 4 | """
Python 基础语法
"""
data_int = 1
data_float = 0.2
data_str = "a"
print("================================ 打印")
print('hello, world')
# hello, world
# 以单引号'或双引号",可以用转义字符\来标识
print('I\'m \"OK\"!')
# I'm "OK"!
# 用逗号“,”隔开,会依次打印每个字符串,遇到逗号“,”会输出一个空格
print('The quick brown fox', 'jumps over', 'the lazy dog')
# The quick b... |
b34b477f9775af9bbcbc85f941a6dabf730efe63 | tcfh2016/knowledge-map | /Techs/prgramming-language/python/notes/files/file/write/textfilewrite_ex.py | 479 | 3.9375 | 4 | # -*- coding: utf-8 -*-
def write_file(name):
f = open(name, 'w')
f.write("You and me ")
f.write("learn python together.")
f.close()
# 如上是一个写文件的例子,下面是一个在文件头插入内容的例子。
def insert_title(title, fname='textfiletest.txt'):
f = open(fname, 'r+')
content = f.read()
content = title + "\n\n" + con... |
cfa8707fdf4c84d24d75050d8fb2d4a07ec47661 | ylpduxinghua/rosalind_codes | /GS.py | 1,420 | 3.515625 | 4 | def boolgs(graph,numofnode):
for node in graph.keys():
if len(dfs(graph,node)) == int(numofnode):
return node
return '-1'
def dfs(graph,node):
visited = set()
search(graph,node,visited)
return visited
def search(graph,node,visited):
visited.add(node)
if node in graph:
... |
659fac380cbb4a303a7d0c09c61761301784db5e | AGCapdeville/Film-Prediction-Machine | /gradient_descent.py | 551 | 3.859375 | 4 |
# Example of gradient descent
# line: y = mx + b
def update_weights(m, b, X, Y, learning_rate):
m_deriv = 0
b_deriv = 0
N = len(X)
for i in range(N):
# Calculate partial derivatives
# -2x(y - (mx + b))
m_deriv += -2*X[i] * (Y[i] - (m*X[i] + b))
# -2(y - (mx + b))
... |
ba09ffff2d54329a498db0f4aae8df762b328183 | soltanoff/sorting_algorithms | /by_quick_hoar.py | 1,978 | 3.578125 | 4 | # -*- coding: utf-8 -*-
import random
def sort_by_quick(array: list) -> list:
"""
Быстрая сортировка Хоара.
Суть: Разделение массива на две части производится следующим образом. Устанавливаем один курсор на левую границу
массива, а второй – на правую границу. Затем осуществляем перемещение курсоров на... |
5962ec7f7c6ed51c51b02fb6ebcaef372b43705b | 1141938529/ClassExercises | /week02/day2/03hk002.py | 974 | 3.875 | 4 | # 人口信息统计表
# ·使用input每次一个人员信息,形成一个元组,输入0代表输入结束
# ·(张三,男,20),(李四,女,30),(王五,男,25)...
# ·将所有失踪人员信息统计为一个列表
# ·遍历该列表,将人员信息打印为一个表格
# ·打印时按年龄降序排列
mlist = []
while True:
mstr = input("请输入人员信息:")
if (mstr == "0"):
break
mtuple = tuple(mstr.split(","))
# print(mtuple)
mlist.append(mtuple)
# print(mlis... |
f884cc08f3440d8099009d2afe6a5fd4b48b5b30 | oroV2/company-coding-questions-geeksforgeeks | /Array/Print Elements of Array.py | 842 | 4.5625 | 5 | """
Given an array Arr of size N, print all its elements.
Example 1:
Input:
N = 5
Arr[] = {1, 2, 3, 4, 5}
Output: 1 2 3 4 5
Example 2:
Input:
N = 4
Arr[] = {2, 3, 5, 5}
Output: 2 3 5 5
Your Task:
Complete the function printArray() which takes an array arr, single integer n,
as input parameters and pri... |
660c131e257d52961314193391dd327cdd284522 | Tiramisu-wwh/study | /study/process.py | 978 | 3.953125 | 4 | def print1(a):
if a == 1:
print('ok')
print('a is 1')
def print2(b):
if b == 1:
print('ok')
print('a is 1')
print1(0)
print('-----------')
print2(0)
a = '记得一键三连'
if (n := len(a)) < 10:
print(n)
x = 5
print(f'{x + 3}')
print(f'{x + 3 = }')
April = True
July = 5
print(April)... |
c5b149edac6b4c7ce24bb322e34caab16f6c8167 | mike-jolliffe/Learning | /leet_760.py | 394 | 3.6875 | 4 | class Solution:
def anagramMappings(self, A, B):
"""Return indexes of values in B ordered by A occurrence
:type A: List[int]
:type B: List[int]
:rtype: List[int]
"""
return [B.index(num) for num in A]
if __name__ == '__main__':
sol = Solution()
print(sol.an... |
c49bc51a01fa677de659abf81a308c74270b1314 | GIT-Ramteja/project1 | /list opt.py | 969 | 3.796875 | 4 | a=[1,2,12.8,13+12j,"aefredg"]
a.insert(3, 100)
print(a)
a.append(99)
print(a)
a.extend([11, 22])
print(a)
a[2]=20
print(a)
a[3:5]=[12+1.2j,"ramteja"]
print(a)
b=[12,13,12.24,0.088,12+0.04j,"harish"]
del b[4]
print(b)
del b[1:5]
print(b)
del b
c=[12,13,12.24,0.088,12+0.04j,"harish"]
print(c)
c.remove(12)
print(c)
c.pop(... |
54d2387d255062fe1e739f7defeb0cff1f9cf634 | Surenu1248/Python3 | /third.py | 233 | 4.375 | 4 | # Write a program to find given number is odd or Even
def even_or_odd(a):
if a % 2 == 0:
print(a, " is Even Number.....")
else:
print(a, " is Odd Number.....")
print(even_or_odd(10))
print(even_or_odd(5))
|
1707c0ad5e4658e8a75f0226cde502e8712254c5 | kimchhengheng/learning_python | /Hang_man.py | 3,015 | 3.78125 | 4 | """
your have 10 attempt
if you guest wrong draw the man
guess right it fill in the
check function then if it is not call decrease the value can call the figure
figure can do if else but waste
"""
import random
words = ["pugger", "littlepugger","tiger", "superman", "thor", "pokemon","avengers"]
def display():
pri... |
c851ccda1a0f3ec47d314e3473955d900c3ca03c | bddowningjennings-dev/codingdojo_platform | /Python/python_fundamentals/fun_with_functions.py | 499 | 4.21875 | 4 | """function demos"""
def oddities():
for i in range(0, 2001):
type = ''
if i % 2 == 0:
type = 'even'
else:
type = 'odd'
print "Number is " + str(i) + ". This is an " + type + " number."
oddities()
def multiply(arr, x):
for i in range(0, len(arr)):
arr[i] = arr[i] * x
return arr... |
8159fdc11fea8e8ee48e7873cc05721a3911c6a8 | kirandala/Pythoncore | /venv/Include/OLD discriptive/nested list.py | 248 | 4.0625 | 4 | x=[[10,20,30,],[1,2,3,4,5],[111,22,33,44]]
print(x)
print("Elements in rows")
for r in x:
print(r)
print("Elements to be printed in matrix style")
for i in range(len(x)):
for j in range(len(x[i])):
print(x[i][j], end='')
print() |
cc23dd0f2500eff0d35e881a66852f82af98eaf9 | leonardolginfo/Exercicios_python_org | /EstruturaSequencial/ler_e_mostra_num.py | 199 | 4.125 | 4 | # Faça um Programa que peça um número e então mostre a mensagem O número informado foi [número].
print()
print('Digite um número:')
numero = input()
print('O número digitado foi: ', numero)
|
1c28c2730da906557e8b1dafd961fd91b6ae17a4 | weiweizhang/tutorial | /L3/spiral_square.py | 272 | 3.59375 | 4 | from turtle import *
from random import *
setup(1.0, 1.0, 0, 0) # 画布全屏
bgcolor("black") # 背景色
speed(0) # 速度
hideturtle()
n = 2000
for i in range(n):
if i%2 == 0:
color('red')
else:
color('white')
forward(i)
right(91)
|
c83c6652b20533abe5b9dcea30ac204ada7d8502 | xiaopuzhu/python_test | /test31.py | 2,560 | 3.65625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'练习序列化和反序列化'
__author__ = 'sergiojune'
import pickle
import json
d = {'name': 'bob', 'age': 20, 'score': 80}
# 序列化,这个是序列化成bytes
p = pickle.dumps(d)
print(p)
# 这个序列化后直接存在指定文件
with open('pickle.txt', 'wb') as f:
pickle.dump(d, f)
# 反序列化
# 这个是将bytes反序列... |
b4607825558ca35ce73fe7cef6428ac745ad87fc | AlejandroIV/MetNum2 | /ModulosAdicionales/Met_EliminacionGaussiana.py | 1,925 | 4.03125 | 4 | """Modulo que contiene el Metodo de Eliminacion Gaussiana"""
# Este programa no intercambia las filas, asi que puede causar errores si el primer elemento de la matriz es cero
import numpy as np
def Metodo_Eliminacion_Gaussiana(orden):
"""Funcion que llevara a cabo el Metodo de Eliminacion Gaussiana"""
# Crea ... |
545159c55fe25ab0e3dd31728b782420f1f11a53 | manojbmk/Study | /Python/Practice/even_or_add.py | 147 | 4.21875 | 4 | num = int(input("Please enter the number: \t"))
if num%2 == 0:
print("{} is a Even number".format(num))
else:
print(num," is a Odd number") |
0d457707bf6271fa275b7d9b0490f1f8e60ca95d | sshantel/dicts-word-count | /wordcount.py | 539 | 3.859375 | 4 | import sys
import string
def dicts_word_count(file):
word_count = open(file)
word_count_dict = {}
for line in word_count:
words = line.strip().split(" ")
for word in words:
word = word.strip(string.punctuation).lower()
word_count_dict[word] = word_count... |
8466a3aad6575412b407c562c0f54da4629593ee | CptAwe/freeCodeCamp | /PolygonAreaCalculator/shape_calculator.py | 2,167 | 3.875 | 4 | class Rectangle:
POINTS = "*"
def __init__(self, width: int, height: int):
self._width = width
self._height = height
def set_width(self, width: int) -> None:
self._width = width
def set_height(self, height: int) -> None:
self._height = height
def get_a... |
b0b98df7337d884eafe73bb8d454a9e915bf7aff | nnd2890/heroScrape | /test/multiprocessing2.py | 3,030 | 3.640625 | 4 | from multiprocessing import Lock, Process, Queue, current_process, Pool, Manager
import time
import queue
# def print_func(continent="Asia"):
# print("the name of continent is: ", continent)
#
# if __name__ == "__main__":
# names = ["America", "Europe", "Africa", "Japan"]
# procs = []
# proc = Process(... |
938da8478148371090b8fa2b4a1c4468fd30f470 | drivard2/prime_factors | /prime.py | 1,184 | 4.0625 | 4 | """
A prime factor generator.
"""
import sys
factors = []
def generate_prime_factors(number, factors):
"""
Step 1: Accepts an integer parameter, and returns a
list of integers from that function.
"""
if (type(number) is not int):
raise ValueError
else:
# Instantiate ite... |
d3391a7b8ec18c1545a2faa963aa0062419c1174 | rohitrastogi/Interview-Prep | /solns/shortest_encoding.py | 1,391 | 4.1875 | 4 | '''
Given a list of words, we may encode it by writing a reference string S and a list of indexes A.
For example, if the list of words is ["time", "me", "bell"], we can write it as S = "time#bell#" and indexes = [0, 2, 5].
Then for each index, we will recover the word by reading from the reference string from that in... |
5748f8ac6b6e60f2a8d5be78fc7e75ff2201452e | andrewhumble/Pandas-SQL | /CSV/NFL Statistics/fantasy_TotalTDs.py | 1,403 | 3.8125 | 4 | from pandas import read_csv
from pandasql import sqldf
import matplotlib.pyplot as plt
# Demos running SQL queries on a CSV file
"""
Reads in two CSV files:
1. 2018 NFL Statistics
2. 2019 NFL Statistics
These stats seperate touchdowns into three categories: Rushing, Passing, and Receiving.
First, I loop throu... |
aca4b8aab8adc143ea178ab40993afcd3561dcda | Geovany585/PYTHONM | /Hoja_trabajo_2-3.py | 267 | 3.859375 | 4 | #PROGRAMA QUE SOLICITA AL USUARIO UN NUMERO POSITIVO Y MUESTRA EN PANTALLA SI ES PRIMO O NO
n=int(input("INGRESE NUMERO POSITIVO ENTERO, "))
i = 2
while n % i != 0:
i += 1
if i == n:
print(str(n) + " Es primo")
else:
print(str(n) + " No es primo") |
81ba07110c2d539e65b3102dce3ed06da51e9c23 | metal32/Algorithm | /Hashing/Rolling_hashes.py | 1,681 | 3.640625 | 4 | ''' Rabin Karp Algo O(n) n-> length of the text you are looking into '''
# d is the base and q is the prime number
# equation 1: append(val):((u*base)+val)modp = [(u mod p)*base+val] mod p
# equation 2: skip(val):[u-val(base**(u-1)modp)]modp=[(u mod p) - val(ba... |
ae96a54a1f62e129a69a323eb661c4d160d2aa2d | TheToby1/CS211 | /python/Lab2/q1_4.py | 1,240 | 3.828125 | 4 | '''Created on 14 Feb 2015
Grab a stick. Break it in two. Now randomly break another piece in two. Carry out
this process a total of n times.
Write a program that takes n as input and outputs the probability that a triangle can
be formed out of any three of the resulting pieces.
This solution takes a stick breaks it, t... |
d8456b488df94cb15a305a8a9eebd998deeda204 | philipjchristian/Test | /gender_converter.py | 193 | 3.859375 | 4 | def convert_gender(gender: str):
gender = gender.upper()
if gender == "M":
return "Male"
elif gender == "F":
return "Female"
else:
return "Uknown_gender" |
e3449393a6b6db741bbd9d2f3f949f12bb4983e3 | rber14/Python- | /homework4/phys162hw4.py | 2,342 | 4.1875 | 4 | #robertoCampos
#phys162Hw4
import math
import numpy as np
"""
*mass,length,height,gravity are pre-defined
*xdist calculates the range and returns it
*make sure to convert degree to radians in the xdist function
*xdist2 prints out the output and formats it without calling print()
"""
mass=200; #in grams
length=6;... |
788611f924b271f130839b1b395baaf4d02492b6 | ahrav/Python-Django | /python_practice/insert_doubly_linked_list.py | 491 | 3.875 | 4 | def sortedInsert(head, data):
node = Node(data)
if head is None:
return node
currentNode = head
while currentNode.next is not None:
if node.data >= currentNode.data and node.data <= currentNode.next.data:
currentNode.next.prev = node
node.next = currentNode.next
... |
8f509c01c0fcf4d62bf7eebff571b40dc097185a | lschanne/DailyCodingProblems | /year_2019/month_03/2019_03_12__balanced_string.py | 1,287 | 4.25 | 4 | '''
March 12, 2019
Given a string of round, curly, and square open and closing brackets, return
whether the brackets are balanced (well-formed).
For example, given the string "([])[]({})", you should return true.
Given the string "([)]" or "((()", you should return false.
'''
OPENER = 1
CLOSER = -1
def validate_str... |
4c70032e71059a030260b1fb60e970f40a90976c | codename-water/WiproPJP | /Junk/primitive.py | 169 | 3.59375 | 4 | a=13
print(a," is of type: ", type(a))
a=13.03
print(a," is of type: ", type(a))
a=True
print(a," is of type: ", type(a))
a='Saini'
print(a," is of type: ", type(a))
|
1a345e0ccb0f79ab315061b57baf9a69e2e9446b | Iron-Rush/python_develop | /python_algorithm/filter_data/ListFilter.py | 731 | 3.546875 | 4 | # ListFilter.py
# 在列表中根据条件筛选数据
# import timeit
# 生成随机列表
from random import randint
data = [randint(-10, 10) for _ in range(10)]
print(data)
# 通用
res = []
for x in data:
if x >= 0:
res.append(x)
print(res)
# 1.filter
# 1、循环帮你调用函数
# 2、帮你过滤你传入的参数,函数的结果返回的是true那就保存
# 返回false就不要,且返回的也是迭代器
ls1 = list(filter(lambd... |
a2e760d49f973f472f2de9051e24d9003ac9341c | arun-p12/project-euler | /p0001_p0050/p0046.py | 1,503 | 3.90625 | 4 | '''
The smallest odd composite number that cannot be represented as the sum of a prime
and twice a square. E.g. 9 = 7 + 2(1**2) ; 27 = 19 + 2(2**2)
Originally had maintained the list of 2x^2; and then check if for every i, if
the (odd_composite - i) is in that lis. This logic took about 7s to execute.
Modified logic ... |
babcb659453797e940fd429ee27bff230a2273a3 | ellismckenzielee/codewars-python | /reduce-pyramid.py | 380 | 3.703125 | 4 | ##REDUCING A PYRAMID KATA
##Given the first row of a number pyramid, the code below finds the
##value stored in the last row
def reduce_pyramid(base):
pascals = pascal(len(base)-1)
totals = [x*y for x,y in zip(pascals, base)]
return sum(totals)
def pascal(n):
line = [1]
for k in range(n):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.