blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
df9d4055dc7334179b6d7d482efb1817411c0b7b | arun-k/python-pgms | /count_change.py | 246 | 3.53125 | 4 |
def count_change(amnt,coins):
if amnt==0:
return 1
elif amnt < 0:
return 0
elif amnt > 0 and len(coins) <= 0:
return 0
else:
return count_change(amnt-coins[0],coins) + count_change(amnt,coins[1:])
|
f2a088ba660228afe5824b531f3b97cc8b5407af | smart14/Linear-Regression | /linreg.py | 4,398 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Dec 8 14:50:21 2018
@author: Lenovo
"""
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import style
import pandas as pd
import sklearn
import warnings
from sklearn import linear_model
from sklearn.model_se... |
273e19fd142a5180522b5e94b1a97316bbb42a4e | karakazeviewview/PythonTraining | /20210201/Ex5_5.py | 324 | 3.515625 | 4 | def int_input(msg):
return int(input(msg+'を入力してください>>'))
def calc_payment(amount,people=2):
dnum=amount/people
pay=dnum//100*100
if dnum>pay:
pay(pay+100)
payorg=amount-pay*(people-1)
print('***支払総額***')
print('一人当たり{}円,{}幹事は{}円です'.format(pay,people-1,payorg))
|
eb50839934d1d41b828439ce4a57c0026ae63407 | victorrayoflight/Foudil | /Examen 2019-02-18/14.py | 93 | 3.640625 | 4 | nb = int(input("Entre le nombre :"))
for i in range(1, 10):
print(i, "*", nb, "=", i*nb)
|
363d63626370cdcafcf6eeb6266ce6ac6be87fbc | jwk1215/Python-advanced | /025.py | 338 | 3.5625 | 4 | #! /usr/bin/env python
#문자열변수 Seq1 에 “ATGTTATAG” 가 담겨있습니다
#Seq1에서 3 칸씩 건너뛰며 출력 즉 첫 번째 네 번째 일곱 번째만 출력하는
#프로그램을 작성해보세요
Seq1 = "ATGTTATAG"
for i in range(0, len(Seq1), 3):
#print(i)
#print(Seq1[i])
print(i, Seq1[i])
|
168e13a9d2e440f983f9f574c3ba4515a9d3c22a | dp1608/python | /LeetCode/17/171023maximum_average_subarrayI.py | 1,676 | 4.09375 | 4 | # -*- coding: utf-8 -*-
# @StartTime : 10/23/2017 16:09
# @EndTime : 10/23/2017 16:09
# @Author : Andy
# @Site :
# @File : 171023maximum_average_subarrayI.py
# @Software : PyCharm
"""
Given an array consisting of n integers, find the contiguous subarray
of given length k that has the maximum average v... |
413be1c426ec122008721c67d454401846672deb | MonkeyNi/yummy_leetcode | /jump_game/45.py | 486 | 3.515625 | 4 | class Solution:
def jump(self, nums):
if len(nums) <= 1:
return 0
res = 1 # if we set r=nums[0], res=1, elif r=0,res=0
l, r = 0, nums[0]
# we do not need to consider the last ele in nums, since r>= len(nums)-1
while r < len(nums)-1:
res += 1
... |
76ab6498b886e3f099a0c8ed2acbc48c06302acd | rehth/test | /Pycharm/飞鸽传书/python17_05/threading 共享全局变量.py | 441 | 3.546875 | 4 | import threading
import time
g_num = 100
g_list = list()
def work1():
global g_num
for i in range(5):
g_num += i
g_list.append(i)
print(g_num)
print(g_list)
def work2():
time.sleep(1)
print(g_num)
print(g_list)
work1_thread = threading.Thread(target=work1)
work2_thread ... |
66b395cf7d8407653dde69621be2045577ad511c | ensermuyigezu/Algorithms | /Collections/closest_point.py | 1,451 | 3.546875 | 4 | import math
coordinates = [(1, 1), (-2, 4), (-1, 2), (2, 3), (3, 5), (-3, 6), (0, 8), (.45, 7.5), (-1.1, 1.9)]
X = sorted(coordinates)
Y = sorted(coordinates, key = lambda x:x[1])
def Closest_Points(points, Y):
if len(points) <= 3:
return brute_force(points)
middle = X[math.ceil(len(points) / 2) - 1]
... |
9fcc50b19ea91b1ab931f7b4f6acb72d00b56f60 | pavankumarpolavarapu/PythonForDataScience | /002-IntermediatePythonForDataScience/004-Loops/009-LoopOverDataFrame.py | 567 | 3.640625 | 4 | # cars_per_cap country drives_right
# US 809 United States True
# AUS 731 Australia False
# JAP 588 Japan False
# IN 18 India False
# RU 200 Russia True
# MOR 70 ... |
98cfc563d3c6b57aa1393789a9b0edf6c09a148a | adriyens/school-projects | /MazeSearch.py | 4,037 | 4.25 | 4 | # File: proj2.py
# Author: Adrianne Santinor
# Date: 11/30/2016
# Section: 22
# E-mail: santa1@umbc.edu
# Description: This program uses recursion to solve a maze game.
# Collaboration: I did not collaborate with anyone for this assignment.
# constants that correspond the index of a list to the position of a wall
RIGH... |
9acb8d80b2d74bb0a728e3610eb2bae1c987c425 | akkikiki/courses | /csci5622/homework/logreg/plot_learning_curv_diff_learning_rates.py | 4,149 | 3.8125 | 4 | import numpy as np
import matplotlib
import matplotlib.pyplot as plt
# http://scikit-learn.org/stable/auto_examples/model_selection/plot_learning_curve.html
def read_data(filename):
iterations = []
train_accuracies = []
hold_out_accuracies = []
for line in open(filename):
# example Update 1061T... |
c60be67a6821560230e456f767e96b29f1faa8af | kingkk31/BOJ | /source code/10826_피보나치 수 4.py | 161 | 3.671875 | 4 | n = 0
a = 0
b = 1
c = 0
n = int(input())
if n == 0 :
print(a)
elif n == 1 :
print(b)
else :
for i in range(2, n+1) :
c = a + b
a = b
b = c
print(c) |
00d8d6798b8b310bc9533300d642a3539a2903b2 | Remyaaadwik171017/mypythonprograms | /flow controls/ifelse.py | 179 | 4.21875 | 4 | num= int(input("enter any no:"))
if num==0:
print("The no is zero")
elif(num<0):
print("The entered no is negative:",num)
else:
print("You entered a positive no:",num) |
55f67c6e514b6d13d31cbe856ae699cc69e2471f | fjfzcjj/Slither-for-Computer-Science-Grade-11--final-project | /examples/SnakeGame.py | 12,911 | 3.84375 | 4 | import useful
from random import randint
import turtle
class snakeGame():
def __init__(self,wSize,nGrid,gamespeeds,offsets,colors,path):
self.wSize = wSize# screen window size
self.nGrid = nGrid# number of grid spacings
self.gamespeeds = gamespeeds# list of possible game speeds
self.offLeft = offsets[0] #... |
cca7a7194254aa2ee14e07efae3620c8368d129b | jiluhu/dirtysalt.github.io | /codes/contest/leetcode/find-duplicate-subtrees.py | 1,094 | 3.796875 | 4 | #!/usr/bin/env python
# coding:utf-8
# Copyright (C) dirlt
# TODO(yan): WA.
# Definition for a binary tree node.
from collections import defaultdict
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def findDuplicateSubtr... |
6f84090e961d8381cfe466ad2103edbdb928630a | bygonehe/robot_project | /Jupyter/New_function-Copy1.py | 7,903 | 4.3125 | 4 |
# coding: utf-8
# These code is for defination, for example :"The human tells the robot "Give me the red ball". The robot can see five objects. Which objects is the red ball?"
# In[7]:
# The function of produce the object
import numpy as np
import random
def objectfeature ():
#red = random.randint(1,256)
#... |
8df9c357436cadc6a018727ba6e0f02ba765d735 | marcospsviana/desafios-coder-byte | /filter_list.py | 351 | 3.53125 | 4 | def filter_list(l):
"""
>>> filter_list([1,2,'a','b'])
[1, 2]
>>> filter_list([1,'a','b',0,15])
[1, 0, 15]
>>> filter_list([1,2,'aasf','1','123',123])
[1, 2, 123]
"""
for n in l:
if (str(n)).isnumeric():
set_numbers.add(int(n))
set_numbers.remove('')
... |
6f7ef426bb90b4e6f47f2e478d475d47940fddec | michael-gif/Python | /alphabet scrambler.py | 334 | 3.578125 | 4 | import random
alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
newalphabet = []
print(''.join(alphabet))
for x in range(26):
num = random.randint(0,len(alphabet)-1)
newalphabet.append(alphabet[num])
alphabet.pop(num)
print(''.join(n... |
20123930207c56982df144d9484e0d585cfc3de6 | oprk/city_comparison | /data_table_fbi.py | 1,665 | 3.578125 | 4 | """
Module for parsing any Fbi related data in data/Fbi.
"""
import pandas
from data_table import DataTable
class Fbi(DataTable):
"""Table of FBI data."""
@staticmethod
def read(file_path):
data = pandas.read_excel(file_path, header=3)
# Remove empty columns.
data.drop(data.columns[[13, 14, 15, 16,... |
7e4df8d9029e2ec923f57ca3cf7eb0d5db88379e | Kite330/python- | /023从数组中找出a+b=c+d.py | 747 | 4.125 | 4 | """
给定一个数组[3,4,7,10,20,9,8],可以找出两个数队(3,8),(4,7)=>3+7=8+4
"""
import random
class Pair:
"""docstring for pair"""
def __init__(self,first,second):
self.first=first
self.second=second
def findPairs(arr):
Dict={}
i=0
n=len(arr)
while i<n:
j=i+1
while j<n:
pair=Pair(arr[i],arr[j])
sum=... |
96dafe4ce746465721cfdabb6df09b27cd0c25be | wuyeguo/advance_python | /py/1_decorator_Learn_0.py | 6,182 | 3.71875 | 4 |
# coding: utf-8
# Decoator
# ======
#
# http://www.cnblogs.com/rhcad/archive/2011/12/21/2295507.html
# >1 最简单的函数,准备附加额外功能:
# In[1]:
'''示例1: 最简单的函数,表示调用了两次'''
def myfunc():
print("'myfunc' called.")
myfunc()
myfunc()
# >2使用装饰函数在函数执行前和执行后分别附加额外功能
# In[2]:
'''示例2: 替换函数(装饰)
装饰函数的参数是被装饰的函数对象,返回原函数对象
装饰的实... |
d2db1689c56abb2f648944b0c46cad06c6cbf6d5 | J297-hub/exercicios-de-python | /Pacote Dowload/pythonProject/aula014ex059.py | 758 | 3.84375 | 4 | n1=int(input('Primeiro valor:'))
n2=int(input('Segundo valor:'))
opcao=0
while opcao !=5:
print('''Opçôes de cálculo:
[ 1 ] SOMAR
[ 2 ] MULTIPLICAR
[ 3 ] MAIOR
[ 4 ] NOVOS NÚMEROS
[ 5 ] SAIR DO PROGRAMA''')
opcao=int(input('Escolha sua OPÇÃO:'))
if opcao ==1:
op1 = (n1 + n2) # somar
print('... |
32c43ed387093b6a985482e518fe6011cf12dc7e | theChad/ThinkPython | /chap15/exercises.py | 1,771 | 4.3125 | 4 | import math, copy
# Point class definition
class Point():
"""Cartesian coordinate point
"""
# Section 15.2 exercise
def distance_between_points(p1, p2):
"""Find the distance between points p1 and p2
p1, p2: Point objects
"""
ydiff = p2.y-p1.y
xdiff = p2.x-p1.x
distance = math.sqrt(yd... |
6a53c813864010c994e88625098c910c5e7ba5f3 | yusj0530/weblib | /연습/mymath.py | 568 | 3.625 | 4 | class UserException(Exception):
def __init__(self, name, age):
Exception.__init__(self)
self.name =name
self.age = age
def checkPerson(name, age):
try:
if age>20 :
print("안녕하세요 {0}님 입장가능 입니다.".format(name))
else:
raise UserException(name, age)
... |
9f26718c4249535730480fefe4d92b77ce942b15 | pradeepvallam/Pradeep | /Source/LAB-1/lab1_1.py | 123 | 3.71875 | 4 | a = input("Please enter a string: ")
b = ""
for i in range(0,len(a)):
if a[i] not in b:
b = b + a[i]
print(b)
|
6a1681d846033171e5a1e764ed5bccd07c96d7ca | Joroks/W-Seminar | /program.py | 3,053 | 3.625 | 4 | from classes import Partitioning, Key, Text, Alphabet, Frequencies
from typing import Iterable
from itertools import product
def decode_sort(enc: Text, symbols_enc: Alphabet, ref: Text, symbols_ref: Alphabet):
"""Evaluate the used encryption key by pairing the symbols up according to their frequency."""
freq_... |
7dc8268de7892da1f82c53dcf30896f9444f4fee | ShehryarKh/python_code_example | /largest_product_of_3.py | 711 | 4.3125 | 4 | __author__ = 'shehryar'
'''
Given an array find the largest product
using 3 numbers
This is not the optimal solution. Optimal solution below
'''
def three_product(array):
if(len(array)>3):
max1 = max(array)
min1 = min(array)
array.remove(max1)
array.remove(min1)
max2 = m... |
8071a04024f8ab3e3ad5b8fdc9cbf96788431320 | FilipLangner/CodersLab-Workshop_1 | /Guessing_game_2.0.py | 1,227 | 4.40625 | 4 | def guessing_game(min, max):
"""
The function is a reverse guessing game where the user thinks a number in a range specified in the function
parameters. The computer takes attempts to guess it and is prompted by the user of whether the guess is too high,
too low or successful
:param min: low limit o... |
7e9960095311284310575f0d7b81e0cebc2afec2 | zeddmaxx/Tuple- | /python1 lab3 5.py | 148 | 3.5625 | 4 | t=(1,2,4,7,9,21,45)
print(t);
num = int(input("enter num to be deleted"))
b=list(t)
b[num]=100
print()
t=tuple(b)
print(t, end=' is the updated t')
|
66e46ee8698b5b7fcda6cabad254f25dc1a3453d | mikejthomas/BIOTE_pset4 | /p1_zip-map.py | 250 | 4 | 4 | #Michael Thomas
#BIOT-E 100
#Assignment 4
#zip-map
#declare x,y,z
x = ["a", "b", "c"]
y = [1, 2, 3]
z = ["m", "l"]
#Zips x,y,z
for i, j, k in zip(x, y, z):
print i, j, k, "\n"
#Use map to add "none" when the lists are un-even
print map(None, x, y, z)
|
8a1915d3a0cf0a3d70742414d44109348b22d46b | Vivbhav/IS_Assignments | /111508015_IS_Lab_Assignment8/ecc.py~ | 3,252 | 3.9375 | 4 | def modInverse(a, m) :
a = a % m;
for x in range(1, m) :
if ((a * x) % m == 1) :
return x
return 1
def addition(x1, y1, x2, y2, field):
slope = (y2 - y1) / (x2 - x1)
slope = slope % field
xnew = (slope * slope - x1 - x2) % field
ynew = (-y1 + slope * (x1 - xnew)) % field
temp = list()
temp.append(xnew)
... |
995522c1d54cb79eb65878aa362b41e9c25b28dd | saipavans/programming_winter | /winter_lab_4/BTask1.py | 447 | 3.5 | 4 | file_path = "./words.txt"
def check_file(file_path, find_word):
fin = open(file_path)
word_table = {}
for line in fin:
word = line.strip()
if word in word_table.keys():
word_table[word] += 1
else:
word_table[word] = 1
return (find_word in word_table.keys... |
10588ab8d9b06f075c8218c46a19a933ba22bc5f | data-mining-in-action/DMIA_Industry_2019_Spring | /seminar03/geo.py | 1,009 | 3.53125 | 4 | import numpy as np
EARTH_RADIUS = 6372795.0
def earth_distance(lon1, lat1, lon2, lat2, is_radians=False):
"""
Вычисление расстояния между точками заданными географическими координатами
Если входные пареметры массивы, то возвращается расстояния первый с
первым и тд
:param lon1: float or np.array
... |
9f5f3a4902b0a9c389276c2782d21e949073c0bd | Aasthaengg/IBMdataset | /Python_codes/p02405/s832001628.py | 280 | 3.578125 | 4 | while 1:
H, W = map(int,raw_input().split())
if H + W == 0: break
for h in range(H):
if h % 2 == 0:
if W % 2 == 0:
print ('#.'*(W//2))
else:
print ('#.'*(W//2)+'#')
else:
if W % 2 == 0:
print ('.#'*(W//2))
else:
print ('.#'*(W//2)+'.')
print '' |
2e43c6432f1ed5d9a4b710e80f974ef8115d759d | rgyllenhammer/OOpygameAnimation | /blob.py | 3,544 | 4.15625 | 4 | '''
this is a very simple animation to illustrate how to take
an object oriented approach to making an animation with
python and pygame
'''
import pygame
import time
import random
# initializes pygame so fonts can be easily accessible
pygame.init()
# the main purpose why i made this stupid animation... work with
#... |
3b2a2bad66533c316985c2f48bdaceeb8aac4f39 | miladaghamohamadnia/view-factors | /src/basics.py | 3,433 | 4.03125 | 4 | from abc import ABC, abstractmethod
################### Abstract Types ###################
class Point(ABC):
"""
Abstract Vector of coordinates representing a point
"""
def __init__(self, coordinates=[]):
self._coords = coordinates
self.n = len(self._coords)
def __len__(self):
return len(self... |
e7d26d1522df55e1d256f3022a8abee40df86242 | facedesk/pypractice | /variables.py | 655 | 4.125 | 4 |
print('''hello world!
hello world!
asdfas
asdf
asdf
asddf
and this will show up!
''')
first_name = raw_input("what is your first name?")
last_name = raw_input("what is your last name?")
full_name = first_name +" "+ last_name
#string^
print(full_name)
number1= 500
#integer^
number2= 1000.0
#floating point^
number... |
a679a162e42dfabb566aea667e9247dc1b2b994b | pablocesar87/stoner_band_generator | /application/utils.py | 1,255 | 3.5 | 4 | import os
import random
from .settings import APP_ROOT
vowels = ['a', 'e', 'i', 'o', 'u']
acceptable_consonants = ['sh', 'ch', 'br', 'tr', 'th']
def generate_random_band_name():
gramatically_wrong = True
with open(os.path.join(APP_ROOT, 'wi_words.txt'), 'r') as file:
words_list = file.read().split(... |
e1c6c016a940e384244af3e103b622da803856fa | wittawas19/Python-Lab | /Chapter2/63010885_Lab02_05.py | 2,172 | 3.59375 | 4 | class game_of_word :
def check(word) :
mylist = []
left = []
re = 0
for i in range(len(word)) :
if i == 0 or re == 1 :
if "P " in word[i] :
subStr = str(word[i])
subStr = subStr.re... |
64763e24950c45e7dfb8cde64dcda546e7420f67 | LoneWolfXVII/GUI-based-program | /LCS_GUI.py | 2,339 | 3.734375 | 4 | from tkinter import *
import LCS
mainWindow = Tk()
mainWindow.title('Longest Common Subsequence:')
#mainWindow.iconbitmap('D:/DOCUMENTS/SEM 4/Assignments/DAA/Logo.ico')
maximum = 1000
def findLCS():
global lbl_LCS
global str1
global str2
str1 = ent_getstr1.get()
lenStr1 = len(str1... |
62d2fe05d9234ee7a7c908130bf83c367e896a5b | pnayak333/List_Data_Structure | /Linked_List.py | 2,666 | 4.21875 | 4 | #Creating a Wrapper - Node
class node:
def __init__(self,data):
self.data = data
self.next = None
#Creating Linked List
class Linked_List:
def __init__(self):
self.head = None
#Creating Append MEthod
def append(self,data):
New_Node = node(data)
if self.head is... |
b8ee4086d2cc6237a6050fa278d3e50df8102997 | lxyres/leetcode-python | /389. Find the Difference.py | 539 | 3.59375 | 4 | class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
result=0
for i in s:
result^=1<<(ord(i)-ord("a"))
for i in t:
result^=1<<(ord(i)-ord("a"))
number=0
... |
05e0dd6c841d9f0d2ccaee5bffb9f469e1771042 | stcybrdgs/myPython-refresher | /pythonGenerators/fibonacciGen_alt.py | 726 | 4.40625 | 4 | # fibonacciGen_alt.py
#
# this script creates a generator to yield the fibonacci sequence
# functions ==========================
def fibonacci_generator():
trailing, leading = 0, 1
while True:
yield leading
trailing, leading = leading, trailing + leading
# main ===========================... |
d5756995629b80f80df98b449e9260b29a8352cc | pontuslaestadius/gameboy-rs | /debug.py | 714 | 3.8125 | 4 | print "DEBUGGING log.txt"
f = open('log.txt', 'r')
list = []
for line in f:
list.append(line),
max_count1 = 0
max_count2 = 0
max_count3 = 0
max_item1 = ""
max_item2 = ""
max_item3 = ""
for item in list:
count = list.count(item)
if count > max_count1:
max_count1 = count
max_item1 = item
continue
if max_it... |
ba8470fd39d27f152863edf49513dd923e7e403e | rafarbop/Python-Curso-em-Video | /desafio37.py | 1,006 | 4 | 4 | # Desafio 37 Curso em Video Python
# By Rafabr
import os,time,sys
from estrutura_modelo import cabecalho,rodape
cabecalho(37,"Programa para converter número de base decimal para outras bases númericas")
try:
n_decimal = int(input('Digite um número inteiro: '))
base = int(input('Escolha para base númerica de... |
733cd9b96a6a73b84fc82bf19dd1a1aee0840b2e | mclxly/study | /python/base/buildindex.py | 952 | 3.53125 | 4 | # A Dictionary of Sets
def main():
indexEntries = {}
infile = open("indexdata.txt", "r")
fields = extractRecord(infile)
while len(fields) > 0 :
addWord(indexEntries, fields[1], fields[0])
fields = extractRecord(infile)
infile.close()
printIndex(indexEntries)
def extractRecord(infile) :
line = ... |
c8345c5c73e652b2631ec07090608773a443c88a | Enes-Kasapoglu/Asistan-2.0 | /Asistan_2.0/baslarken.py | 1,315 | 3.625 | 4 | from tkinter import *
def welcometips():
welcomert = Tk()
welcomert.title("Başlarken")
welcomert.geometry("685x300")
welcomert.resizable(False,False)
welcomert.config(bg="#202020")
brandfont = ('roboto', 30)
labelfont = ('roboto', 10)
brandlabel = Label(welcomert,text="Başlarken",bg="... |
8d3ebc70ef64c6bdaabf61feb73f5de2db3b94e6 | rbyelyy/simple_code_challenges | /company_name_levenshtein_distance/converting_company_names.py | 4,113 | 3.546875 | 4 | # coding=utf-8
import csv
import os
import re
import urllib2
def download_nasdaq_company_list(file_name, url):
"""
Download file with up to date NASDAQ company names
"""
response = urllib2.urlopen(url)
with open(file_name, 'w') as f:
f.write(response.read())
def get_dirty_company_list(... |
8122bd32d03ff3199a27266c9299675779378c40 | dsissongh/tides | /tides/func1.py | 2,012 | 3.53125 | 4 | import os
import collections
def showmenu():
'''
generates the menu based on the files for anual tide
information found in the directory
'''
order = {}
menu = ''
count = 1
stations = generatedatadictionary()
cstations = collections.OrderedDict(sorted(stations.items()))
for key in cstations:
order.upda... |
89514f1bc52313c9de4c9c81675f55dcddecbc39 | MingduDing/My_codes | /crossin编程教室/ex15.py | 398 | 3.796875 | 4 | # -*- coding: utf-8 -*-
from sys import argv
script, filename = argv # argument variable 参数变量,需要事先输入
txt = open(filename) # open函数用于打开一个文件,创建一个file对象
print "Here's your file %r" % filename
print txt.read() # read函数
print "Type the filename again:"
file_again = raw_input(">")
txt_again = open(file_again)
print ... |
4fb66c905a1035274a2335e8107f5a4ee98f7d1e | Aasthaengg/IBMdataset | /Python_codes/p02392/s818463261.py | 118 | 3.640625 | 4 | z = input()
w,x,y = z.split()
a,b,c = int(w),int(x),int(y)
if a < b and b < c:
print("Yes")
else:
print("No") |
f6496aec05115687894f8799ac4653f60c71b312 | rob-3/python-text-framework | /UI.py | 1,602 | 3.90625 | 4 | '''
Fully implemented
'''
import textwrap
from builtins import print as builtinprint
def println(string=''):
builtinprint(textwrap.fill(string, 80))
def print(string=''):
builtinprint(textwrap.fill(string, 80), end='')
def print_in_box(string, heavy):
'''
Prints a string inside of a box using box dr... |
663d1d4fd745c824482f5b1c53ec4cdaada9d2ac | Gaurav-Dutta/python_learning | /Assignments/quadratic_formula.py | 273 | 3.90625 | 4 | a = int(input("Enter A: "))
if a == 0:
print("'A' must be a nonzero number")
quit()
b = int(input("Enter B: "))
c = int(input("Enter C: "))
import math
root1 = (-b + math.sqrt(b*b - 4*a*c))/ 2*a
root2 = (-b - math.sqrt(b*b - 4*a*c))/ 2*a
print(root1)
print(root2) |
56c8a295cb9462f565d8c3cd79f59f8578be56fe | SunderB/python-maths-interpreter | /maths-interpreter.py | 7,318 | 3.75 | 4 | #!/usr/bin/python3
from typing import NamedTuple
import re
import uuid
class Token(NamedTuple):
type: str
value: str # can be any type
position: int
class Error(Exception):
"""Base class for exceptions in this module."""
pass
class InputError(Error):
"""Exception raised for err... |
21ba98864b9f0ceddb46b5e200420cfeea1187b1 | FelipeMQ/CS1100 | /libpynput/presskey0.py | 1,168 | 4.0625 | 4 | #from pynput.mouse import Button, Controller
from libpynput.keyboard import Key, Controller
#mouse = Controller()
keyboard = Controller()
# Press and release space
keyboard.press(Key.space)
keyboard.release(Key.space)
# Type a lower case A; this will work even if no key on the
# physical keyboard is labelled 'A'
keyb... |
7e5958aff316b320d2f7ab3a9b713f74f559f159 | sachin-611/practicals_sem3 | /fds/prac_3/file3.py | 3,017 | 3.84375 | 4 |
def Merge(div_a,count_of_div_A,div_b,count_of_div_B): # function to sort and merge the DOB of students of computer division A and division B
combined={}
i=0
j=0
while ((i < count_of_div_A) and (j < count_of_div_B)):
for keyA in div_a:
for keyB in div_b:
if div_b[ke... |
4a1d69d5ac3da7c33b411956a4944abd7e8e67a4 | bd52622020/appSpaceAden | /Task3_Python.py | 2,073 | 3.65625 | 4 | # class human(Researcher):
# "'my classs inherits from human an adds teaches as a paramter'"
# def __init__(self,Name,Occupation,subject)
# super __init__(self,Name,Occupation)
# self.subject
# # Part 1
# def __str__(self):
# return "the human surname:" + self.lastname
# # Part 2
... |
4f7152cd45a1cd5dae06d579c77e33666d48bca8 | CruzLS/EncryptionBasics-IS | /main.py | 12,911 | 3.953125 | 4 | # -*- coding: utf-8 -*-
import os
import string
import re
import sys
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
TAM_MAX_CLAVE = 26
def __init__(self):
pass
def cifrar():
textoCifrado = ''
key = ''
ans=True
while ans:
print ("""
1. Cifrar Alberti
2. Descifrar Alberti
3... |
ef2c2be413fc68446704687c8efe76edc34056f9 | lorak127/University-Courses | /LFTC/Laborator/Tema1Python/Circle.py | 251 | 3.640625 | 4 | import math
class Circle:
radius = 0
def __init__(self, radius):
self.radius = radius
def get_perimeter(self):
return 2 * math.pi * self.radius
def get_area(self):
return math.pi * self.radius * self.radius |
3705503ec1ac4c4f014fbb964b82b8f212f0bd26 | xshirl/grokkingalgorithms | /bfs/minimumDepth.py | 714 | 4.0625 | 4 | from collections import deque
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
def find_minimum_depth(root):
if root is None:
return 0
queue = deque()
queue.append(root)
minimumTreeDepth = 0
while queue:
minimumTreeDepth += 1
levelSize = len... |
abee9ec63540c73b5924f26144d3c1250e922fb0 | Balaji-Ganesh/Furnishing-OpenCV-Basics | /Chapters/Chapter_8-Contours_Shape_Detection.py | 7,604 | 4.21875 | 4 | import cv2
import numpy as np
"""Required functions"""
def concatenate_images(images):
"""
:param images: list of images to be concatenated.
:return: Concatenated images, in the order how the list is passed as parameter.
NOTEs: (1)
>>> lst = [[1, 2, 3],[4, 5, 6]]
... |
0e35d9848d51a53f95a37ac750847ccb903080c2 | sravi97/I210_Information_Infrastructure1 | /Lecture/Lecture 13/filebreak.py | 328 | 3.90625 | 4 | #get a file name from the user
while True:
file_name = input("Please enter a file name or STOP: ")
if file_name.upper() == "STOP":
break
text_file = open(file_name, "r")
file_content = len(text_file.readlines())
text_file.close()
print(file_name, "has", file_content, "number of li... |
2ba35c7d97daf0a0b55a0f4a0373fa9aa65733f5 | neternefer/codewars | /python/uni_total.py | 343 | 3.84375 | 4 | def uni_total(string):
"""(str) -> int
You'll be given a string, and have to return the total of all the
unicode characters as an int.
Should be able to handle any characters sent at it.
>>> uni_total("aaa")
291
"""
#your code here
result = 0
for i in string:
result += or... |
10741384084ab19a8af897d8a2778886c1d0a701 | jarkyll/puzzles | /Bot Save Princess.py | 1,084 | 3.84375 | 4 | #!/usr/bin/python
def print_path(dir, count):
for _ in range(count):
print(dir)
def find_answer():
max = int( input() )
for i in range(0, max):
row = input().strip()
#nothing is going to be stripped and is just making a copy
if row.find('m') != -1:
mario ... |
614c77a820cfd7f9a506404182e41fef38cdee03 | voidclown/Hello-World | /dice_roll.py | 1,168 | 4.125 | 4 | import random
yes = "y"
no = "n"
random_num_min = 1
roll_counter = 1
keep_playing = True
play = input("Welcome to diceroll!\nWould you like to roll a dice? y/n: ")
while play != yes and play != no:
play = input("Please enter y or n!: ")
if play == yes:
while keep_playing:
sides = in... |
679580dc135ec4f209d3d179569a589930ef90c0 | typemegan/Python | /CorePythonProgramming_2nd/ch13_classes/roundFloat2.py | 601 | 4.25 | 4 | #!/usr/bin/python
#coding:utf-8
'''
Junior Customization:
Example 13.2
'''
class RoundFloatManual(object):
def __init__(self, val):
assert isinstance(val, float), "value must be float!"
self.value = round(val, 2)
def test(self):
return '%.2f' % self.value
__str__ = test
__repr__ = test
#def __str_... |
6fdf57067a989749d9c8697a9929dc363679090f | bkelly1984/umba_trial | /generic_dao.py | 5,250 | 3.515625 | 4 | import logging
class GenericDao:
"""
This abstract class contains information and parameters to manipulate a database table.
Attributes:
GenericDao.table_name (str): the name of this table in the database.
GenericDao.columns (list): the names of the columns in this table.
... |
85e1d3d333938cd93741e3b6cb7d378c0e3f96ac | FJRH03/PythonCourse | /CourseProjects/Translator.py | 463 | 3.78125 | 4 | '''
Author: @XXXKaos (GitHub)
Francisco Ramirez
Twitter: @DeNyJavier
'''
#Buiilding translator method
def translate(phrase):
tranlation = ""
for letter in phrase:
if letter.lower() in "aeiou":
if letter.isupper():
tranlation = tranlation + "G"
tranlat... |
e230c19ac0aefeeb6d9060466d6fa913898ab2b4 | ivn-svn/Python-Advanced-SoftUni | /Multidimensional-Lists/Lab/03. primary_diagonal.py | 471 | 3.828125 | 4 |
def create_matrix(size):
result = []
for n in range(size):
result.append(list(map(int, input().split())))
return result
def calc_sum_primary_diagonal(matrix, size):
sum_primary_diagonal = 0
for n in range(size):
num = matrix[n][n] #num of row and column are the same
sum_pr... |
d06c2d4247d4340bf173a34e2770fd67e44bdd5c | gitonga123/Learning-Python | /large.py | 559 | 4.25 | 4 | #python program to find the largest number among user inputs numbers
print("Ths program determines the largest number among the user entry: ")
x = 1
number = []
while x != -1:
x = int(input("Enter the numbers to determine the largest or -1 to stop: "))
number.append(x)
if(len(number) > 0):
number.remove(-1)
if... |
bbf9f7772b1d7ec9494f451b10aa56206104a9ad | sterhannzer/OperationSystems | /SysOp2/Kolejka.py | 5,744 | 3.5 | 4 | from copy import deepcopy
from Zgloszenie import *
from random import randint, shuffle
class Kolejka():
def __init__(self, max):
self.kolejka = []
self.kolejnosc_wyszukiwania_zgl = [] # posortowane sa od najwiekszego do najmniejszego, pobierac ostatni elem
self.kolejka_real_time = []
... |
cc469cd9f9364b78ca56a9f5ae4add86be97299c | swarnlata9/assignment1-assignment2 | /solution2.py | 1,258 | 3.65625 | 4 | def find_path(graph, start, end, path=[]):
path = path + [start]
if start == end:
return path
for node in graph[start]:
if node not in path:
newpath = find_path(graph, node, end, path)
if newpath:
return newpath
if __name__ == '__main__':
l... |
489ceef0ae230dc7aebaa3a3f5db021bf1125f56 | thiago-allue/portfolio | /12_back_dev/paradigms/iterators/py_scripts/34. collections.py | 1,427 | 4.0625 | 4 |
# coding: utf-8
# ## `collections.namedtuple`
#
# `namedtuple()` is a factory function; that is, it generates a class, and not an instance of a class (an object).
#
# So there are two steps:
#
# 1. First, use `namedtuple()` to generate a `class`
# 2. And then create an instance of this `class`
# In[4]:
from col... |
5d47caf7b1a9ad861479129f28691fe0fe0b024e | scubbae/pythoncource | /assign7.py | 467 | 4.03125 | 4 | # My favorite song by Mariaha Carry
myFavoriteSong = {
'Artist': 'Maria Cary',
'Title': 'Butterfly',
'Album': 'Butterfly',
'Date': '1997',
'Genre': 'Contemporary R&B'
}
for key, val in myFavoriteSong.items():
print(key, ':', val)
print("\n")
def guess():
song = list(myFavoriteSong.value... |
d6779d67a2e4b9af0558d6ee8e3bff5d3ca7feda | nayneshrathod/imrjalgoan | /mysample.py | 185 | 3.90625 | 4 | lst = []
msg = input("enter A String ")
for i in msg.split():
lst.append(i)
word = input("enetr remove word")
lst.remove(word)
msg = ""
for i in lst:
msg += " " + i
print(msg) |
31a6500b845dbdb6494acfb1ee58d1fe48496569 | ZhuYacheng/regular_expression | /元字符.py | 841 | 3.9375 | 4 | """
作者:ZYC
时间:2021年09月23日
"""
import re
# []:列表符号,用于一组字符
txt = 'else if(i==2) {} else else else'
x = re.findall('[a-z]', txt)
print(x)
# . 匹配除了换行符之外的任意字符,匹配一个
# ^ 匹配开始,匹配到返回匹配值到列表,否则返回空表
# $ 匹配结束,匹配到返回匹配值到列表,否则返回空表
x2 = re.findall('if.+2', txt)
print(x2)
x3 = re.findall('^e', txt)
print(x3)
x4 = re.findall('else$',... |
ed4a4d578769a257e587e42e18e990466db45d52 | ElleSowulewski/CIT228-Data | /project/oranges.py | 718 | 3.703125 | 4 | import csv
import matplotlib.pyplot as plt
import numpy as np
filename = 'fruit-type.csv'
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader)
for index, column_header in enumerate(header_row):
print(index, column_header)
years = []
oranges = []
with open(filenam... |
4d9cd1648616cb4a967343660962f7455444a9dd | Ducky-O/Python | /week6_work.py | 4,080 | 3.828125 | 4 | import sqlite3
import os
from sqlite3.dbapi2 import connect
conn = sqlite3.connect('C:\Phudit_python\week6-work.db')
c = conn.cursor()
#c.execute('''CREATE TABLE students (id integer PRIMARY KEY AUTOINCREMENT,
# name varchar(50) NOT NULL,
# lname varchar(50) NOT NULL,
# email varchar(50) NOT NULL,
# gender ... |
3646a91997c85a21a153c79159c7758345388241 | UhakeR/Palestra_Coding | /Impiccato_Cozzetto/main.py | 1,096 | 3.578125 | 4 | f = open('parola.txt')
s = f.readline().strip()
f.close()
tentativi = len(s) - 1
# s = 'pippopluto'
s = s.upper()
'''
t = ''
for i in range(len(s)):
t = t + '-'
'''
t = '-' * len(s)
print('La parola da indovinare è lunga', len(s), 'caratteri')
print('Hai', tentativi, 'tentativi')
print(t)
parolaTrovata = False
... |
f0ebb0721fda181aef88ee02f2bfb55aec57b394 | ArunkumarRamanan/CLRS-1 | /ProgrammingInterviewQuestions/11_CheckStringBalancedParenthesis.py | 1,530 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Aug 28 15:56:31 2016
@author: Rahul Patni
"""
# checking is string has balanced parenthesis
import random
class Node:
def __init__(self, value):
self.value = value
self.next = None
class Stack:
def __init__(self):
self.size = 0
self... |
b3b04603bb2530450938f2c7cfdcfd42dc78032c | hangongzi/leetcode | /list/sort_list.py | 1,298 | 3.859375 | 4 | class ListNode:
def __init__(self, val):
self.val = val
self.next = None
class Solution:
def sortList(self, head: ListNode) -> ListNode:
def mergeTwo(l1: ListNode, l2: ListNode)->ListNode:
prevhead = ListNode(-1)
prev = prevhead
while l1 and l2:
... |
9aac353890fc311c759069d153d74ef01e59d952 | zl0bster/PY200_Spring_2021 | /lesson_4/1_iter_dict.py | 1,339 | 4.09375 | 4 | """
Сделать свою реализацию словаря, в котором будет переопределен метод __iter__,
чтобы он возвращал итератор не по ключам, а сразу по паре ключ, значение.
Используйте наследование от встроеного типа dict, и полиморфизм для метода __iter__.
Конструктор базового класса переопределять не нужно.
Что... |
dffeda0aaede39c65eba3b1dbe19e3bd7873a7f8 | Sagarsaurus/RIP2014 | /Project 2/Problem 3/project3.py | 2,731 | 3.6875 | 4 | import pygame, math, numpy
# initialize pygame
pygame.init()
# Define some colors
GREEN = (0, 255, 0)
RED = (255, 0, 0)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
BLUE = (0, 191, 255)
# Set the width and height of the screen [width, height]
size = (640, 480)
screen = pygame.display.set_mode(size)
pygame.display.set_... |
0c0de08ed3afb1689a1cb5ba573d1d80a0e91222 | srirachanaachyuthuni/cryptography-problems | /xor_hex_strings/xor_two_hex_strings.py | 668 | 4.25 | 4 | # Perform XOR of two hex strings
def HexToRaw(string):
return string.decode('hex')
def RawToHex(string):
return string.encode('hex')
def sxor(string1,string2):
# convert strings to a list of character pair tuples
# go through each tuple, converting them to ASCII code (ord)
# perform exclusive or ... |
67002994cdced64fdbdac90ace02e5dea5e6b639 | xDarKyx/School-Work | /Python/Lab2-4/Lab2-4P03/addFunctions.py | 1,747 | 3.921875 | 4 | import time
''''List with the only valid types of expenses allowed for the dictionary'''
expTypes=["Transport","Food","House keeping","Clothing","Telephone&Internet","Others"]
'''add() function: adds to a specific day a specific type and a amount of expense'''
def add(expenses):
t=input("Type:") #Type of exp
d... |
e9c7ada1853ad4429fe42d6549263fefdcb34280 | Da-Yuan/LeetCode-Python | /LeetCode-217.py | 445 | 3.640625 | 4 | # 给定一个整数数组,判断是否存在重复元素。
# 如果任何值在数组中出现至少两次,函数返回 true。如果数组中每个元素都不相同,则返回 false。
def Solution1(nums): # 超出时间限制
if len(nums)==1:
return False
for i in range(len(nums)):
for j in range(len(nums)-i-1):
if nums[i]==nums[-j-1]:
return True
return False
a1=[1,2,3,1]
a2=[1,2,3,4]
a3=[3,1]
print(Solution(a3)) |
e4c7b57c213b8892bb8d3b776c950b4f5f19fa5f | Aasthaengg/IBMdataset | /Python_codes/p02665/s426457637.py | 1,342 | 3.5 | 4 | #!/usr/bin/env python3
import sys
def solve(N: int, A: "List[int]"):
if N == 0:
if A == [0]:
print('0')
elif A == [1]:
print('1')
else:
print('-1')
return
if N == 1:
if A == [0, 1]:
print('2')
elif A == [0, 2]:
... |
d0a65eda833714e0123919dd301cfcfd7a1880e3 | Hives/advent-of-code | /aoc-2017-python/day_02.py | 755 | 3.53125 | 4 | #! /usr/bin/python3
from functools import reduce
from itertools import permutations
puzzle_input = [[int(n) for n in line.strip().split("\t")] for line in open("inputs/day_02.txt").readlines()]
def part_1(spreadsheet):
return reduce(
lambda acc, row: acc + max(row) - min(row),
spreadsheet,
... |
8cd61d1998428947b6d6911cd3003d81d388e235 | aabharbhatt99/Python | /fibonaaci_series.py | 237 | 3.953125 | 4 | # fibonaaci series code
n = int(input("Number of terms: "))
mylist = [1, 1]
for i in range(n-2):
mylist.append(mylist[-1]+mylist[-2])
for j in range(len(mylist)-1):
print(str(mylist[j]) + ", ", end="")
print(str(mylist[-1]))
|
dd46b2a186e43f23112b5e3944cb661f51b780d5 | joshuahudelson/Understanding_The_FFT | /Generate_Square_Wave.py | 558 | 3.78125 | 4 | import math
import matplotlib.pyplot as plt
""" BASIC CODE:
10 REM *** DFT 1.0 - GENERATE SQUARE WAVE ***
12 INPUT "NUMBER OF TERMS";N
20 PI = 3.14159265358#
30 FOR I = 0 TO 2*PI STEP PI/8
32 Y=0
40 FOR J=l TO N STEP 2: Y=Y+SIN(J*I) /J: NEXT J
50 PRINT Y
60 NEXT I
70 END
"""
number_of_frequencies = 128
points_in_cycl... |
4cbcca05e2f2049fafb4e74106abcc653aa8e552 | pacarty/PythonLearning | /src/ControlFlow/while.py | 295 | 4.21875 | 4 | # Print numbers one by one
count = 0
while count < 5:
print(count)
count += 1
# We can use the argument "end" to add text to the end of
# each print statement instead of starting a new line each time
count = 0
while count < 5:
print(count, end=', ')
count += 1
print(count) |
d915b2720fbec37a72a3dbcfd20006594bad4b49 | jonasgheer/projecteuler | /problems/prob_7.py | 350 | 3.953125 | 4 | """ 10001th prime """
from math import sqrt
def is_prime(n):
i = 2
while i <= sqrt(n):
if n % i == 0:
return False
i += 1
return True
primes = []
n = 2
while True:
if is_prime(n):
primes.append(n)
if len(primes) == 10_001:
break
n += 1
print('10... |
1d7b0d9a816105852e48c0b6d53cde9de9b6c112 | bentrevor/pe-solutions | /python/pe003.py | 465 | 3.71875 | 4 | # Find the largest prime factor of the composite number 600851475143.
import math
bigNum = 600851475143
def isFactor(x, y):
if y % x == 0:
return True
return False
def isPrime(x):
for y in range(2, int(math.sqrt(x)) + 1):
if isFactor(y, x):
return False
return True
# count down so the fir... |
b76d954b7b0b6fd712cd4d3b071c0f6bff5fcf64 | yinzhiyizhi/Python_Practise | /函数/递归函数.py | 3,221 | 4 | 4 | def fact(n):
if n==1:
return 1
return n*fact(n-1)
fact(1)
# 1
fact(5)
# 120
print(fact(100))
# 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
# 递归函数的优点是定义简单,逻辑清晰。
# 理论上,所有的递归函数都可以写成循环的方式,
# ... |
3b2a9a7c13260161e10a795dd3513b977fa1e1ab | Vineetkhadloya/LeetCode-Solutions | /src/findMin.py | 678 | 3.765625 | 4 | def findMin(nums) :
l = 0
r = len(nums) - 1
if(nums[l]<nums[r] and len(nums)>=2):
return nums[r]
res = nums[0]
while l <= r:
print(l,r)
if(nums[l] < nums[r]):
res = max(res,nums[r])
print("nums[r] = ",nums[r])
print(... |
0355d8df340fd1075dc87286fff1a86cb3ca586f | hoyongjungdev/bioinformatics-algorithms | /chapter1/minimum_skew.py | 849 | 3.75 | 4 | def main():
genome = input()
print(to_string(minimum_skew(genome)))
def skew(genome: str) -> list[int]:
result = [0]
for i in range(0, len(genome)):
g = genome[i]
if g == 'C':
diff = -1
elif g == 'G':
diff = 1
else:
diff = 0
... |
cf137fb989e6302de80e32a16e5bedd7b54486ff | ivanenko0and/Colloquium-2 | /task 6.py | 1,359 | 3.734375 | 4 |
"""
Створіть масив А [1..8] за допомогою генератора випадкових чисел з елементами від -10 до 10 і виведіть його на екран.
Підрахуйте кількість від’ємних елементів масиву.
Виконав Іваненко Андрій Вадимович
"""
import numpy as np
answer = '1'
while answer == '1':
array, amount = np.random.randint(-1... |
7d25f283e045db890fbab62e5a46e63b7b0808fb | libyal/dtformats | /dtformats/file_system.py | 4,000 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""File system helper."""
import abc
import os
class FileSystemHelper(object):
"""File system helper interface."""
@abc.abstractmethod
def BasenamePath(self, path):
"""Determines the basename of the path.
Args:
path (str): path.
Returns:
str: basename of the p... |
a22f2b365f78e8bd3e56d04073f61071d14208f1 | Zeta611/project-euler | /036-double-base-palindromes.py | 386 | 3.671875 | 4 | from collections import deque
def is_palindrome(n, base):
digits = deque()
copy_n = n
while copy_n:
digits.append(copy_n % base)
copy_n //= base
rev_n = 0
while digits:
rev_n *= base
rev_n += digits.popleft()
return n == rev_n
print(
sum(n for n in range(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.