blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
a48e91a699fd8c9ce1a217a3a4520ff7683a0620 | chenjinpeng1/python | /day4/JSQ.py | 1,264 | 3.546875 | 4 | #python 3.5环境,解释器在linux需要改变
#作者:S12-陈金彭
import re
def jisuan(num):
num=chengchu(num)
# String=jiajian(num)
return num
def chengchu(num):
# print(num)
# print(re.search('\d+[\.?\d+]?[\*|\/]\d+',num))
if re.search('\-?\d+[\.?\d+]?[\*|\/]\d+',num) is None:
return num
String=re.search('... |
605e75a36708b35729165355612f2e583c6bb3bd | chenjinpeng1/python | /day1/User_login_3/login.py | 3,020 | 3.65625 | 4 | #python 3.5环境,解释器在linux需要改变
#用户登陆认证,阅读手册查询readme文件
#调用文件 login.txt,lock.txt
#作者:S12-陈金彭
Auth_File="login.txt" #认证登陆文件
Lock_File="lock.txt" #锁定文件
F_Auth = open(Auth_File)
Read_Auth=F_Auth.readlines() #执行前将账号密码文件读取到变量,避免循环读取
F_Auth.clos... |
d5339b7e3261d953b7187bae0f79cad2ce7cdc25 | chenjinpeng1/python | /Learning/day4/learning.py | 6,904 | 3.671875 | 4 | #python 3.5环境,解释器在linux需要改变
#商城购物,阅读手册查询readme文件
#作者:S12-陈金彭
# li = [13, 22, 6, 99, 11]
# for i in range(1,5):
# for m in range(len(li)-i):
# if li[m] > li[m+1]:
# temp = li[m+1]
# li[m+1] = li[m]
# li[m] = temp
# print(li)
#---------------------------迭代器-----------------... |
397f7c078e4240f0b5dbf8cf281ff7c4e0d38e56 | chenjinpeng1/python | /Learning/day9/多线程队列.py | 800 | 3.515625 | 4 | #python 3.5环境,解释器在linux需要改变
# -*- encoding:utf-8 -*-
#Auth ChenJinPeng
import time
import queue
import threading
q=queue.Queue()
def consumer(n):
while True:
print("consumer [%s] get task %s"%(n,q.get()))
time.sleep(1)
q.task_done()
def producer(n):
count = 1
while True:
pri... |
3ae340232a18caaf8039a021c74cce02195fb093 | OlegLeva/udemypython | /data_time/weekday.py | 232 | 3.515625 | 4 | from datetime import date
day = int(input('Введите день '))
mount = int(input('Введите месяц '))
year = int(input('Введите год '))
data_1 = date(year, mount, day)
print(data_1, data_1.isoweekday()) |
24244974328c4d0bebafcb6849cf9f34e4a20cdf | OlegLeva/udemypython | /codewars_4.py | 2,416 | 3.71875 | 4 | # def divisors(integer):
# res = []
# for x in range(2, integer + 1):
# if x == integer:
# continue
# if integer % x == 0:
# res.append(x)
# if res == []:
# return f"{integer} is prime"
# else:
# return res
#
# print(divisors(13))
#
# def unique_in... |
51870915c84356ae8b89f41116bfad1856ad5649 | OlegLeva/udemypython | /tkinter_frame/temperatur_converter.py | 1,396 | 3.609375 | 4 | from tkinter import *
from tkinter import ttk
def calculate(*args):
try:
value = float(fahrenheit.get())
fahren = (value - 32) * 5/9
celsius.set(float('%.3f' % fahren))
except ValueError:
pass
root = Tk()
root.title("fahrenheit to celsius")
mainframe = ttk.Frame(root, padding=... |
f671ceda60fed582e53f0628e3d2c7b1420c4a79 | OlegLeva/udemypython | /41/atribute.py | 504 | 3.625 | 4 | class BlogPost:
def __init__(self, user_name, text, number_of_likes):
self.user_name = user_name
self.text = text
self.number_of_likes = number_of_likes
post1 = BlogPost(user_name='Oleg', text='Hi', number_of_likes=7)
post2 = BlogPost(user_name='Nik', text='Hello', number_of_likes=5)
post... |
d0ac9c79bc132a70a1542d97018838a58e7d7835 | OlegLeva/udemypython | /72 Бесконечный генератор/get_current.py | 788 | 4.21875 | 4 | # def get_current_day():
# week = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
# i = 0
# while True:
# if i >= len(week):
# i = 0
# yield week[i]
# i += 1
#
#
# amount_day = int(input('Введите количество дней '))
# current_day = get_curre... |
b9f48b506100dbfe6fc37262adde19077cb606d3 | choldstare/pythonstudy | /example9.py | 745 | 3.984375 | 4 | print "I am 6'3\" tall." # escape double-quote inside string
print 'I am 6\'3" tall.'
tabby_cat= "\tI'm tabbed in." # \t acts as a tab
persian_cat="I'm split\non a line." # the \non split the line
backslash_cat="I'm \\ a \\ cat." # the double \\ caused just one of them to print.\\
#the fat_cat below used ""... |
824e020881e6097c26d66fca82031bafd7431999 | mekunalkishan/PythonBegin | /Excercise_Strings.py | 518 | 4.09375 | 4 | ex_string = "Just do it!"
#Access the "!" from the variable by index and print() it
print (ex_string[10])
#Print the slice "do" from the variable
print(ex_string[5:7])
#Get and print the slice "it!" from the variable
print(ex_string[8:11])
#Print the slice "Just" from the variable
print(ex_string[:4])
#Get the stri... |
57aca02f8c266fb2fae85692717da731e87ed325 | koltpython/python-assignments-spring2020 | /Assignment1/starter/tic_tac_toe.py | 3,122 | 4.53125 | 5 | """
Koc University, Turkey
KOLT Python Certificate Program
Spring 2020 - Assignment 1
Created by @ahmetuysal and @hasancaslan
"""
import turtle
SCREEN_WIDTH = 720
SCREEN_HEIGHT = 720
PEN_SIZE = 5
SQUARE_SIZE = 100
ANIMATION_SPEED = 100 # Animation speed
def draw_empty_board():
"""
This function should dra... |
15b88f363f9b4a6073eb4becb46d7c31e708461b | KaiFujimoto/KaiChen_Spotify | /sort_by_strings.py | 972 | 4.03125 | 4 | def sort_by_strings(s, t):
"""
sample input: "cats" "atzc"
sample output: "catz"
assumption(s) => 1. s does not have repeating letters
2. s and t are all lowercased
3. Overall, the goodwill of the person running my code that they will be nice. (have mercy plox)
4. Person running ... |
4f330c0fdbe5a6cc49b506011b88c610ef1abc60 | Jules-Boogie/controllingProgramFlow | /SearchAStringFunction/func.py | 1,087 | 4.21875 | 4 | """
A function to find all instances of a substring.
This function is not unlike a 'find-all' option that you might see in a text editor.
Author: Juliet George
Date: 8/5/2020
"""
import introcs
def findall(text,sub):
"""
Returns the tuple of all positions of substring sub in text.
If sub does not appea... |
b1185e9c9738f772857051ae03af54a4fb20487e | Jules-Boogie/controllingProgramFlow | /FirstVowel-2/func.py | 976 | 4.15625 | 4 | """
A function to search for the first vowel position
Author: Juliet George
Date: 7/30/2020
"""
import introcs
def first_vowel(s):
"""
Returns the position of the first vowel in s; it returns -1 if there are no vowels.
We define the vowels to be the letters 'a','e','i','o', and 'u'. The letter
'y' ... |
749309f49b5f64bd3daccbe8ded8211721e52916 | hamidshahsavar/python | /senarios/prime_number_generstor.py | 115 | 3.5 | 4 |
def is_prime(n):
for i in range(n):
if n i==0
return False
else:
return True
|
b7d990539a50faef24a02f8325342f385f518101 | github0282/PythonExercise | /Abhilash/Exercise2.py | 1,141 | 4.34375 | 4 | # replace all occurrences of ‘a’ with $ in a String
text1 = str(input("Enter a string: "))
print("The string is:", text1)
search = text1.find("a")
if(search == -1):
print("Character a not present in string")
else:
text1 = text1.replace("a","$")
print(text1)
# Take a string and replace every blank space wi... |
fde6c8a93608ad30bf3eba3db4fdceb1772e6089 | SeanSyue/TensorflowReferences | /ZhengBo/test.py | 2,516 | 3.6875 | 4 | # -*- coding: utf-8 -*-
import tensorflow as tf
def relu(x, alpha=0.5, max_value=None):
'''ReLU.
alpha: slope of negative section.
'''
negative_part = tf.nn.relu(-x)
x = tf.nn.relu(x)
if max_value is not None:
x = tf.clip_by_value(x, tf.cast(0., dtype=_FLOATX),
... |
40d3602df649e0e7236ef9ed7d82eded2c0a480b | MouseDoNotLoveCat/02_Python_Liao | /5.5.py | 181 | 3.8125 | 4 | # _*_ coding: utf-8 _*_
"""@author: Luhow
匿名函数
@time:2018/12/122:57
"""
def is_odd(n):
return n % 2 == 1
L = list(filter(lambda n : n % 2 == 1, range(1, 20)))
print(L) |
0a9af0e9f32015d7c9545e815dc04199863fb36a | chiongsterer00/cp2015 | /p03/q1_display_reverse.py | 200 | 4.0625 | 4 | def reverse_int(n):
reverse = [""]*len(n)
for i in range(0, len(n)):
reverse[-i-1] = n[i]
print("".join(reverse))
integer = input("Please enter an integer\n")
reverse_int(integer)
|
722b0f60d2d6c4694152fc6620ecbfa89dca4257 | nathanlmetze/Algorithms_Python | /MergeSort.py | 582 | 4.09375 | 4 | # MergeSort algorithm
# By Nathan M. Using pseudocode from the book
# Using variable names found in the book
# Used for floor
import math
# Helper method
def merge(B, C, A):
i = 0
j = 0
k = 0
while i < len(B) and j < len(C):
if B[i] <= C[j]:
A[k] = B[i]
i += 1
else:
A[k] = C[j]
j += 1
k += 1
if ... |
1a46fb51ff0f9e4d59a3bd869791ef4d8aed1735 | Arifuzzaman-Munaf/HackerRank | /Python/Validating Credit Card Numbers.py | 368 | 3.75 | 4 | import re
N = input()
for i in range(int(N)):
credit = input().strip()
validation = re.search(r'^[456]\d{3}(-?)\d{4}\1\d{4}\1\d{4}$',credit)
if validation:
flatten = "".join(validation.group(0).split('-'))
valid = re.search(r'(\d)\1{3,}',flatten)
print('Invalid' if valid el... |
81a230aa7696bd7d651811e6d8fcdf22b8121f23 | tomik/honey | /honey/pagination.py | 1,315 | 3.515625 | 4 |
from flask import url_for
class Pagination(object):
"""Simple pagination class."""
def __init__(self, per_page, page, count, url_maker, neighbours=5):
self.per_page = per_page
self.page = page
self.count = count
self.url_maker = url_maker
self.neighbours = 5
def ... |
f8b6d469de64fae530a908d7f861058978990ce3 | shresth26/nifpy | /nifpy/financials.py | 4,069 | 3.78125 | 4 | from datetime import datetime
import lxml
from lxml import html
import requests
import numpy as np
import pandas as pd
import bs4
"""
To get the name of symbol/ticker of the stocks for which you want information you can
look it up on https://finance.yahoo.com/ and from there you can pass the scrip name
i... |
11ccee81914bcac1b9a119b93760d1d709f5ed4e | samanbatool08/py-resize | /list.py | 283 | 3.96875 | 4 | from cs50 import get_int
numbers = []
while True:
number = get_int("Number: ")
if not number:
break
# Avoid duplicates
if numbeer not in numbers:
# Add to list
numbers.append(number)
print()
for number in numbers:
print(number)
|
fbf4b19b08ecc9352b07afbe74cb6b461c847240 | khuang7/3121-algorithms | /wk2/insertionsort.py | 413 | 3.953125 | 4 | # we are interested in looking specifically on how to calculate the time
def main():
A = [5, 4, 3, 2, 1]
print(insertionsort(A))
def insertionsort(A):
for j in range(1, len(A)):
key = A[j]
# insert A[j] into the sorted sequence A[1..j-1]
i = j
while i > 0 and A[i - 1] > k... |
dffd95e9a9283ee2903f27b023ab90f5c120e7de | khuang7/3121-algorithms | /dynamic_programming/longest_common_subsequence.py | 1,308 | 3.609375 | 4 | '''
Finds the longest common subsequence of two sequences
(Given as 2 arrays)
'''
from pandas import DataFrame
x = [0, 3, 9, 8, 3, 9, 7, 9, 7, 0,]
y = [0, 3, 3, 9, 9, 9, 1, 7, 2, 0,6]
def main():
longest_subsequence(x, y)
def longest_subsequence(a, b):
DP = [[0] * (len(a)) for i in range(len(b))]
back_t... |
782b19c9bf441bca8e8c5ae754cbec05c0bce121 | khuang7/3121-algorithms | /dynamic_programming/fib.py | 838 | 4.125 | 4 | '''
A simple fibonacci but using memoization and dynamic programing
An introduction to the basics of dynamic programming
'''
memo = {}
def main():
print(fib_naive(5))
print(fib_bottoms_up(4))
def fib_naive(n):
'''
We used the recursive method in order to fine
every combination from f(n) down the ... |
14fd6a8f9fc561862baa3fead606419540d608a8 | Ze1al/Algorithm-Python | /other/5.py | 621 | 3.78125 | 4 | # 计算最少要用几次按键
# 输入:AaAAAA
# 输出8
# 1. 边界条件: n<=0, return 0
# 2. 判断第一个字符是不是大写,大写 res+1
# 3. 连着2个字母以上都是大写或者小写 就 res=长度+2(用const方法)
# 4. 连着2个字母不一样就用 res += 3
def count_keyboard():
n = int(input())
a = input()
count = len(a)
if a[0].isupper():
count += 1
for i in range(1, n):
if a[i].isl... |
2d84645e1883150617c3caef26892c6ee45ade23 | Ze1al/Algorithm-Python | /other/sort_by_name.py | 790 | 4.0625 | 4 | # 输入包括多行,每一行代表一个姓和名字
# 输出排好序以后的名字
from collections import Counter
import sys
names = ['ZHANG SAN', 'LI SI', 'WANG WU', 'WANG LIU', 'WANG QI', 'ZHANG WU', 'LI WU' ]
def get_count(name):
first_names = [name.split()[0] for name in names]
first_name = name.split()[0]
counters = Counter(first_names)
retur... |
7d17735ad32cef1f0c57f05d282db03bf0258b0f | Ze1al/Algorithm-Python | /sort/SelectSort.py | 212 | 3.625 | 4 |
def SelectSort(arr):
n = len(arr)
for i in range(0, n-1):
min_index = i
for j in range(i+1, n):
if arr[i]>arr[j]:
arr[i],arr[j] = arr[j],arr[i]
return arr
|
718c4c08139313bdeeab46707056e87c505b5bc1 | gomes97/codekata | /large.py | 105 | 3.859375 | 4 | x=input(" ")
y=input(" ")
z=input(" ")
if x>y and x>z:
print(x)
elif y>z:
print(y)
else:
print(z)
|
cc9687778ced87f7136faf0a49db7645b71602d1 | gomes97/codekata | /isomorpic.py | 242 | 3.84375 | 4 | s=raw_input()
s1=raw_input()
l=len(s)
l1=len(s1)
if(l==l1):
for i in range(l):
for j in range(i+1,l):
if(s[i]==s[j]):
if(s1[i]==s1[j]):
print("isomarpic")
else:
print("not a isomorpic")
else:
print("not a isomorpic")
|
a6bd6fcc63575cde80874ed0fb7e28af9b36453d | gomes97/codekata | /subset.py | 203 | 3.546875 | 4 | a1=[1,2,4]
a2=[1,2,4,7]
c=0
for i in range(len(a2)):
if(a1[0]==a2[i]):
for j in range(len(a1)):
if(a1[j]==a2[i]):
i=i+1
c=c+1
if(c==len(a1)):
print("subset")
else:
print("not a subset")
|
a443cd1c306de6e4f030977dde74c4394a46fddd | VladislavRb/alg_lab3 | /main.py | 720 | 3.5625 | 4 | from tree import BinaryTree
from random import randint
arr = list(set([randint(0, 100) for i in range(20)]))
print("array length:", len(arr))
bst = BinaryTree(arr)
print("=====")
print("is balanced:", bst.is_balanced(bst.root))
print("tree height:", bst.get_height(bst.root))
print("=====")
bst.print_tree()
print("... |
eacc76f9e2a3e6a8322ec5969792f7d4d743fd0b | 1nfernoS/week2 | /week2/korova.py | 163 | 3.75 | 4 | i = int(input())
if i%10 == 1 and i//10!=1:
print(i, 'korova')
elif i%10<5 and i//10!=1 and i%10!=0:
print(i, 'korovy')
else:
print(i, 'korov')
|
89495c7cb55268122493bb126b1e3ea9a9c19fca | Jamilnineteen91/Sorting-Algorithms | /Merge_sort.py | 1,986 | 4.34375 | 4 | nums = [1,4,5,-12,576,12,83,-5,3,24,46,100,2,4,1]
def Merge_sort(nums):
if len(nums)<=1:
return nums
middle=int(len(nums)//2)#int is used to handle a floating point result.
left=Merge_sort(nums[:middle])#Divises indices into singular lists.
print(left)#Prints list division, lists with singular... |
b59d828a5f75746cff11a5238a485c7cc98b594d | Expert37/python_lesson_3 | /123.py | 1,099 | 4.5 | 4 | temp_str = 'Все счастливые семьи похожи друг на друга, каждая несчастливая семья несчастлива по-своему. Все счастливые семьи'
print('1) методами строк очистить текст от знаков препинания;')
for i in [',','.','!',':','?']:
temp_str = temp_str.replace(i,'')
print(temp_str)
print()
print('2) сформировать list со слов... |
b4253e5b362ff30e2c67bc828d655abaf35fb837 | aritra14/Rosalind-Solutions | /rosalind1.py | 305 | 3.75 | 4 | # Counting DNA Nucleotides
dna=input(' Enter the nucleotide sequence ')
dna=dna.upper();
acount=dna.count('A',0,len(dna));
tcount=dna.count('T',0,len(dna));
gcount=dna.count('G',0,len(dna));
ccount=dna.count('C',0,len(dna));
X=[acount,ccount,gcount,tcount];
print (' '.join(str(x) for x in X))
|
aa76920f13f7b7ef89f0a86245c5aad19a0c779d | Lucas-Brum/Curso-em-Video | /mundo 2/desafios/Desafio042.py | 676 | 4.03125 | 4 | reta1 = float(input('Digite o tamanho da primera reta: '))
reta2 = float(input('Digite o tamanho da segunda reta: '))
reta3 = float(input('Digite o tamanho da terceira reta: '))
if (reta3 + reta2) >= reta1 and (reta1 + reta2) >= reta3 and (reta1 + reta3) >= reta2:
print('\33[4:34mÉ possivel fazer um triangulo com a... |
9fc75a7a85a6a6d3ec3d3c327d447e8914d233f4 | Lucas-Brum/Curso-em-Video | /mundo 1/Desafios/Desafio031V2.py | 221 | 3.515625 | 4 | distancia = float(input('Qual a distancia da sua viagem?'))
preço = distancia * 0.50 if distancia <= 200 else distancia * 0.45
print('O preço da tua viagem vai ser \33[34m{}'.format(preço))
print('\33[32mBoa viagem!')
|
fc18ba786b67f3239b07df14f050f96abe544ed8 | Lucas-Brum/Curso-em-Video | /mundo 1/Aula/aULA10A.py | 129 | 3.84375 | 4 | nome = str(input('Qual teu nome: '))
if nome == 'Lucas':
print('Que nome lindo você tem!')
print('Bom dia {}!'.format(nome)) |
bf0a1713be99d38957d9fcf028fd14ea8f83b2ae | Lucas-Brum/Curso-em-Video | /mundo 1/Desafios/Desafio013.py | 158 | 3.703125 | 4 | salario = float(input('Digite o salario atual: '))
aumento = salario + (salario * 0.15)
print('O seu novo salario fica \33[4:31m{:.2F}\33[m.'.format(aumento)) |
4afe476be401c4706f4e6ed5851dcd406d4090da | Lucas-Brum/Curso-em-Video | /mundo 2/desafios/Desafio038.py | 498 | 3.84375 | 4 | print('\33[31m-=-\33[m' * 20)
print('\33[4m\33[1mQual valor é maior?')
print('\33[m\33[31m-=-\33[m' * 20)
valor1 = float(input('Digite um valor:'))
valor2 = float(input('Digite outro valor:'))
print('\33[31m-=-\33[m' * 20)
if valor1 > valor2:
print('\33[31m{}\33[m é maior que \33[34m{}\33[m'.format(valor1, valor2)... |
d107ae97122fa0c64aa129a7466f75ad5a8b33b1 | ZJTJensen/Python-class-work | /touples.py | 309 | 3.8125 | 4 | def touples(my_dict):
touple =()
for key,data in my_dict.iteritems():
# print key, " = ", data
touple += key, data
# touple += data
print touple
my_dict = {
"Speros": "(555) 555-5555",
"Michael": "(999) 999-9999",
"Jay": "(777) 777-7777"
}
print touples(my_dict)
|
b9bda4d7cea4da14e7a169a377bffc28e6c27e36 | ZJTJensen/Python-class-work | /comparing.py | 331 | 3.78125 | 4 | list_one = [1,2,5,6,2]
list_two = [1,2,5,6,2]
val = 0
yes = 0
while val < len(list_one):
if list_one[val] == list_two[val]:
val=val+1
continue
elif list_one[val] != list_two[val]:
print "not the same"
yes = 1
break
if yes == 0:
print "They are the same"
# 111111211
... |
738efa2e2e3343519471b35b2a6a9e11ef1c0e1a | ZinGitHub/Innovative-AI-App-Final-Project-Deliverable- | /AIResearchAssistant.py | 36,450 | 3.75 | 4 | """
The purpose of this project is to provide students a helping tool. No matter if the student is no college,university,
or high school. This program offers such tools as a text summarizer, Wikipedia scraper, text-to-speech to give
presentations, text-to-PDF tool, and a chatbot which will act as extra help with pro... |
ba261049c8f36c1e41f989a03c3717d68c22a26e | adityagoenka24/python | /mainproject.py | 5,191 | 3.5625 | 4 | import mysql.connector
class Tinder:
# This is the constructor
def __init__(self):
self.conn = mysql.connector.connect(user="root",password="",host="localhost", database="tinder")
self.mycursor =self.conn.cursor()
self.program_menu()
# Welcome Menu for the user
def program_men... |
a20349f5a07a67fe23bdc4c80bf5533867438060 | pathirrus/python_intermediate_training | /sda_exercises_oop_1/dog.py | 207 | 3.53125 | 4 | class Dog:
def __init__(self, name: str, sound="hau"):
self.name = name
self.sound = sound
def make_sound(self) -> str:
return f'Dog name is {self.name} sound: {self.sound}'
|
b4d3e19be67069f37487506a473ba9bce4def0be | jeffjbilicki/milestone-5-challenge | /milestone5/m5-bfs.py | 631 | 4.1875 | 4 | #!/usr/bin/env python
# Given this graph
graph = {'A': ['B', 'C', 'E'],
'B': ['A','D', 'E'],
'C': ['A', 'F', 'G'],
'D': ['B'],
'E': ['A', 'B','D'],
'F': ['C'],
'G': ['C']}
# Write a BFS search that will return the shortest path
def bfs_shortest_path(graph, start, ... |
30e7c4a5403f6b3fd5c335ac99ba4bf9af7eda34 | vitor-fernandes/EstruturaDeDadosII | /esmeralda.py | 424 | 3.734375 | 4 | dicionario = {}
stringConhecida = input("").upper()
stringCifrada = input("").upper()
msgCifrada = input("").upper()
msgDecifrada = ""
for c in range(len(stringCifrada)):
dicionario.update({stringCifrada[c] : stringConhecida[c]})
for c in range(len(msgCifrada)):
if(msgCifrada[c] not in dicionario):
... |
398315b831fe48d48f84742b1f2d3f75fe0d4ee6 | Dhamodhiran/dhamu | /case19.py | 62 | 3.53125 | 4 | k=1
num=int(input())
for i in range(1,num+1):
k=k*i
print(k)
|
956a097e8d552b776f171fc4633d0d403761e267 | Dhamodhiran/dhamu | /case 14.py | 105 | 3.625 | 4 | b,d=input().split(' ')
b=int(b)
d=int(d)
for num in range(b+1,d+1):
if (num%2!=0):
print(num,end=' ')
|
580a215b24366f1e6dcf7d3d5253401667aa1aae | afialydia/Graphs | /projects/ancestor/ancestor.py | 2,127 | 4.125 | 4 | from util import Queue
class Graph:
"""Represent a graph as a dictionary of vertices mapping labels to edges."""
def __init__(self):
self.vertices = {}
def add_vertex(self, vertex_id):
"""
Add a vertex to the graph.
"""
if vertex_id not in self.vertices:
... |
5e1380e5e0d57d37d9c5d6aa1fc89158e0fcbeff | shocklee/python-code | /wordplay.py | 3,290 | 4.15625 | 4 | def length_greater(word, length):
"""Returns True if a given word is greater than the specified length."""
return(len(word) > length)
def avoids(word, letters):
"""Returns True if the given word doesn't contain one of the forbidden
letters in it."""
for letter in word:
if letter in letters:... |
94172700f1a681c39fb2bf5f9c551725fce2c0d9 | shocklee/python-code | /template.py | 851 | 3.515625 | 4 | """
NAME
this command does things
SYNOPSIS
command do-things nice
DESCRIPTION
things are nice when this command does them
AUTHOR
Mark Shocklee
"""
import argparse #This allows you to run: program --help
# other stuff
parser = argparse.ArgumentParser(
description='Path building ut... |
4e21512a276938c54dc5a26524338584d3d31673 | snangunuri/python-examples | /pyramid.py | 1,078 | 4.25 | 4 | #!/usr/bin/python
############################################################################
#####This program takes a string and prints a pyramid by printing first character one time and second character 2 timesetc.. within the number of spaces of length of the given string###
######################################... |
2bcd46b28bdca0b9aec6c530ab677a4edaf684e8 | Sweety310897/6053_CNF | /m12/CNF_Week_2/ex.py | 472 | 3.53125 | 4 | def main():
temp = load_file("data.csv")
print(temp)
def load_file(filename):
dic = {}
list1 = []
with open(filename, 'r') as filename:
for line in filename:
temp1 = line.split(",")
#temp1 = temp.split(",")
#print(temp1)
dic[temp1[0]] = temp1[1... |
76c008e9115f338deac839e9e2dafd583377da46 | pkongjeen001118/awesome-python | /generator/simple_manual_generator.py | 517 | 4.15625 | 4 | def my_gen():
n = 1
print('This is printed first')
yield n
n += 1
print('This is printed second')
yield n
n += 1
print('This is printed at last')
yield n
if __name__ == '__main__':
a = my_gen()
# return generator obj.
print(a)
print(next(a))
# it will resume t... |
5cb87538a3b33dd04ec2d3ded59f0524c04519c4 | pkongjeen001118/awesome-python | /data-strucutre/dictionaries.py | 480 | 4.375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# simple dictionary
mybasket = {'apple':2.99,'orange':1.99,'milk':5.8}
print(mybasket['apple'])
# dictionary with list inside
mynestedbasket = {'apple':2.99,'orange':1.99,'milk':['chocolate','stawbery']}
print(mynestedbasket['milk'][1].upper())
# append more key
myba... |
ff8bc8c1966b5211da2cba678ef60cad9a4b225d | RossySH/Mision_04 | /Triangulos.py | 1,020 | 4.25 | 4 | # Autor: Rosalía Serrano Herrera
# Define qué tipo de triángulo corresponde a las medidas que teclea el usuario
def definirTriangulo(lado1, lado2, lado3): #determina que tipo de triangulo es dependiendo sus lados
if lado1 == lado2 == lado3:
return "Equilátero"
elif lado1 == lado2 or lado1 == l... |
a3b2da8ae5604ff56d373c204b9e25d081250990 | thelyad/FinalProjects | /countingletters.py | 678 | 3.828125 | 4 | '''
Created on Nov 18, 2017
@author: ITAUser
'''
'''create a function that accepts the filename and character'''
def calculate_char(filename, mychar):
f = open(filename, 'r')
count = 0;
isDone = False
while not isDone:
char=f.read(1)
char = char.lower()
if char == mychar:
... |
772702e6a5fa8a31ce8468a8fbc8d8102674f811 | Shogo-dayo/knapsack_problem | /Memoizing_recursive_BFM.py | 1,056 | 3.75 | 4 | # coding:utf-8
import numpy as np
import random
import matplotlib.pyplot as plt
import knapsack
# シード値を設定(再現させるため)
random.seed(151)
# 商品の数
knapsack.N = 10
# ナップサックの入れられる重さ
knapsack.MAX_weight = 10
# WeightandValue[i][0]:i番目商品の重さ
# WeightandValue[i][1]:i番目商品の価値
knapsack.WeightandValue = knapsack.make_randdata(knapsa... |
5d01a0337f1d0fbee5b42b6a7573841271fb419c | JunyoungJang/Python | /Introduction/01_Introduction_python/06 Data type/2 Data type - String/2 Math operations on numbers of string type are not wise.py | 119 | 4 | 4 | # print '7' + 1 # Error
print '7' + '1' # string concatenation
print type('7')
print int('7') + 1
print float('7') + 1
|
17c2e7f062dfe62d36fce4ad3221f5ae654f23de | JunyoungJang/Python | /Introduction/01_Introduction_python/06 Data type/2 Data type - String/13 String methods.py | 1,666 | 3.984375 | 4 | '''
print 'string methods - capitalize, upper, lower, swapcase ---'
s = "hello"
print s.capitalize()
print s.upper()
print s.lower()
print s.swapcase()
'''
'''
'''
#'''
#'''
'''
print 'string methods - count ---'
dna = 'acggtggtcac'
print dna.count('g') # 4
'''
'''
'''
#'''
#'''
'''
print 'string methods - find ---'
da... |
dde1d86c4dd20e3ff2cbbfd7f5520d77d42b8f82 | JunyoungJang/Python | /Introduction/01_Introduction_python/06 Data type/3 Data type - Boolean/3 Boolean works componentwise.py | 363 | 3.5625 | 4 | import numpy as np
print np.array([3, 7]) < 5 # [ True False ]
print np.array([3, 7]) != 5 # [ True True ]
print np.array([3, 7]) == 5 # [ False False ]
print np.array([3, 7]) >= 5 # [ False True ]
# print 1 < np.array([3, 7]) < 5 # ValueError: The truth value of an array with more than one el... |
de32c9794eebe19116b22ac96b926b198ea6285e | JunyoungJang/Python | /Introduction/01_Introduction_python/09 How to create and use class, module, library, package/1 How to create and use class.py | 10,209 | 4.53125 | 5 | # -*- coding: utf8 -*-
# http://cs231n.github.io/python-numpy-tutorial/#python-basic
#
# Classes
# The syntax for defining classes in Python is straightforward:
#'''
print 'Construction of class using construct, instance, and destructor ---'
class Greeter(object):
# Constructor
def __init__(self, name):
... |
1f291ba8c19a6b242754f14b58e0d229385efe8b | JunyoungJang/Python | /Introduction/01_Introduction_python/10 Python functions/len.py | 663 | 4.1875 | 4 | import numpy as np
# If x is a string, len(x) counts characters in x including the space multiple times.
fruit = 'banana'
fruit_1 = 'I eat bananas'
fruit_2 = ' I eat bananas '
print len(fruit) # 6
print len(fruit_1) # 13
print len(fruit_2) # 23
# If x is a (column or row) vector, len(x) reports the length o... |
b800cdcea930d9bb379e96bbeaf15efbaa62a915 | JunyoungJang/Python | /Introduction/01_Introduction_python/10 Python functions/type.py | 346 | 3.5 | 4 | print type(3) # <type 'int'>
print type(3.7) # <type 'float'>
print type(3.7 + 2.5j) # <type 'complex'>
print type([1, 2, 3]) # <type 'list'>
print type((1, 2, 3)) # <type 'tuple'>
print type(set([1, 2, 3])) # <type 'set'>
print type("Hello world") # <type 'str'>
print type(True) ... |
77195fcb06462de23e1cdb0cc815168bb8716eab | JunyoungJang/Python | /Introduction/02_Introduction_numpy/10 Numpy functions/random.randn.py | 303 | 3.53125 | 4 | import numpy as np
import matplotlib.pyplot as plt
# https://plot.ly/matplotlib/histograms/
gaussian_numbers = np.random.randn(1000)
plt.hist(gaussian_numbers)
plt.title("Gaussian Histogram")
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.show() # You must call plt.show() to make graphics appear. |
3bafeb7b73587a98544f81b9c65c5eab48fb8d55 | JunyoungJang/Python | /Introduction/02_Introduction_numpy/4 np.array indexing/1 Slicing.py | 90 | 3.5625 | 4 | import numpy as np
a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
print a[:2, 1:3]
|
da611ba0eadb1a00665e94d58e04bd24e3d22a5b | JunyoungJang/Python | /Introduction/01_Introduction_python/05 Functions/13 If the function doesn't return a value, Python returns None.py | 152 | 3.75 | 4 | def sign(num):
if num > 0:
return 1
elif num == 0:
return 0
# else:
# return -1
print sign(-9) # It retruns None
|
985178a8589d59e251bbbf81267eb43b96997eca | JunyoungJang/Python | /Introduction/01_Introduction_python/06 Data type/1 Data type - Number/1 Data type - Number.py | 221 | 3.6875 | 4 | # integer
x = 3
print type(x)
print x, x + 1, x - 1, x * 2, x ** 2
# float
x = 3.7
print type(x)
print x, x + 1, x - 1, x * 2, x ** 2
# complex number
x = 3.7 + 2.5j
print type(x)
print x, x + 1, x - 1, x * 2, x ** 2
|
ba226c8ed3345758bc1dd093823a1c4f912ddb05 | LouisFettet/Sorting_Algorithms | /HeapSort.py | 2,015 | 3.890625 | 4 | # Fettet, Louis
# Heap Sort Algorithm Implementation
# 12/16/12
from random import randint
class HeapArray():
def __init__(self):
self.data = []
self.data.append(None)
def parent(self, item):
if item == (0 or 1):
return None
return item//2
def leftChild(self, ... |
e0825a3da6e68014f7288c3567b07d01f6d260ca | mannickutd/project_euler | /src/solutions/solution_12.py | 1,028 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Solution to question 12
Nicholas Staples
2014-04-15
"""
from utils.include_decorator import include_decorator
def gen_tri_num():
prev = 1
cur = 3
yield prev
yield cur
while True:
nxt = (cur - prev) + 1 + cur
yield nxt
prev = cur
cur = ... |
d49c6fcdbfcacfd90b07fc74328021fbeb60da0f | LornartheBreton/CovidTrackingApp | /python_code/main.py | 1,384 | 3.5625 | 4 | import pandas as pd
from datetime import datetime
import matplotlib.pyplot as plt
#import os
import json
#The code below was used to test the formula locally
"""
today=datetime.today().strftime('%Y-%m-%d')#Get today's date
location = input("Location: ") # Location to be monitored
people_day=1#People you meet in a day
... |
5140383e35da66e6580510032738e21154d63cd2 | minhminh12/Python-Basic-ACT | /minhduc_day03.py | 3,166 | 3.75 | 4 | print("+--------------MENU-----------------+")
print("|Chon C de tao hoa don |")
print("|Chon R de xem thong tin hoa don |")
print("|Chon T de tinh tong doanh thu |")
print("|Chon A de tinh tong hang hoa ban ra|")
print("|Chon E de thoat |")
print("+------------------------------... |
6cc1fab83327c7e6a619741a7518af151fae0e41 | wilfred321/flask_tuts | /flight.py | 757 | 4.03125 | 4 | class Flight():
def __init__(self,capacity):
self.capacity = capacity
self.passengers = []
def add_passenger(self,name):
if not self.open_seats:
return False
self.passengers.append(name)
return True
def open_seats(self):
return self.capacity - le... |
c45a94e149844e80de1ad7db8e3eb6b7a34ec717 | DocBlack89/Courbe_elliptique | /client.py | 3,113 | 3.6875 | 4 | #!/usr/bin/python3
import ecc
import config
import diffie_hellman
import chiffrement
import sys
import time
def menu():
'''
Menu permettant de choisir ce que l'on souhaite faire
'''
print("\n\n############################")
print("# #")
print("# Ceci n'est pas un men... |
739b27500108d1541b6d1a88f0f7d79d70e4db5d | psv-git/labs | /OOD/Lab1/classes/decorators/print_to_console_decorator.py | 599 | 3.640625 | 4 | from classes.decorators.base_decorator import BaseDecorator
class PrintToConsoleDecorator(BaseDecorator):
# private methods =========================================================
def __init__(self, shape):
super().__init__(shape)
# public methods ===========================================... |
b5358749a18db5e3d086f6a2c8a85602e8b28db7 | psv-git/labs | /MLITA/Lab6/src/functions.py | 2,065 | 3.890625 | 4 | # http://comp-science.narod.ru/DL-AR/okulov.htm
def read_file(file):
lines = file.read().splitlines()
return lines[0], lines[1]
def string_to_long(str_num, base_power=3):
lng_num = []
dig_count = 0
curr_num = ""
for i in range(len(str_num)-1, -1, -1):
dig_count += 1
curr_num ... |
9f91455daba127b6ce40a5037a8b3c60ca37a96f | chvjak/cj2017 | /alphabet_cake.py | 3,239 | 3.5 | 4 | f = open("alphabet_cake.txt")
#f = open("A-small-practice.in")
#
def input2():
res = f.readline()
return res
def get_res_cake(cake):
def all_distributed():
for row in res_cake:
if '?' in row:
return False
else:
return True
def is_valid_... |
384c0b886114ae094daee763a8759a8a839ec485 | pcranger/learning-Flask | /section2/unpack arguments/define 2 asterisk.py | 379 | 3.890625 | 4 | # 1. **kwargs in function call
def named(name, age):
print(name, age)
# data as dict
bob = {"name": "Bob", "age": 25}
named(**bob)
# and unpacks the dict into arguments of named()
#2. **kwargs in argument
def test(**kwargs):
print(kwargs) # kwargs in a dict
test(name="bob", age=25) # 2 pairs with be ... |
eee674be1b7bed2732ff6710e0dfda7777f8a193 | AlexJonesCU/Perceptron | /Perceptron.py | 3,279 | 4.25 | 4 | #~ various sources I used to learn how to code the perceptron
#https://www.youtube.com/watch?v=tA9jlwXglng
#https://arxiv.org/abs/1903.08519
#https://machinelearningmastery.com/implement-perceptron-algorithm-scratch-python/ -- this was an amazing tutorial page
#https://julienbeaulieu.gitbook.io/wiki/sciences/machine-... |
e30caa3a29aae2b49cb5bbb724d341b55294efc7 | AntonPushkash/ITEA_hw | /hw8/grouping.py | 1,702 | 3.71875 | 4 | """
Пользователь вводит количество групп n.
Далее вводится n строк, каждая строка начинается с названия группы,
а затем через пробел идут элементы группы.
1. Обработать строки и вывести на экран словарь, в котором
ключи - это группы, а значения - списки элементов групп.
2. Создать и вывести вто... |
eccedcff0f3131ff861b5678f6f41eeac1389c14 | AntonPushkash/ITEA_hw | /hw6/file_practice.py | 2,185 | 3.671875 | 4 | """
Выполните все пункты.
* можно описывать вложенные with open(), если это необходимо.
* работа в основном с одним файлом, поэтому имя можно присвоить переменной
"""
# 1.
# Создайте файл file_practice.txt
# Запишите в него строку 'Starting practice with files'
# Файл должен заканчиваться пустой строкой
... |
b60b480b8b349403a7413e8c806eae0b83ef8f5d | AntonPushkash/ITEA_hw | /hw4/practice.py | 1,250 | 4.0625 | 4 | """
Выполнить описанные действия над строкой.
"""
string = 'Lorem, Ipsum, is, simply, dummy, text, of, the, printing, industry.'
# 1. Изменить строку таким образом, чтоб вместо ', ' был пробел ' '
# Вывести получившуюся строку.
# 2. Вывести индекс самой последней буквы 's' в строке.
# 3. Вывести к... |
024a187aad268cb07d34fe73a7c3935002fa4f88 | novita2005490/Tugas1-PemrogramanBerorientasiobjek | /luassegitiga.py | 158 | 3.71875 | 4 | print("Menghitung Luas Segitiga")
a=float(input("Masukkan Alas : "))
t=float(input("Masukkan Tinggi : "))
luas=0.5*a*t
print("Luas Segitiga= "+ str(luas)) |
811613f48605b29b5d667e4d089e03f8a0fd0e2c | hopeniitssaa/STRING | /string3.hope.py | 352 | 3.546875 | 4 | s1 = str(input("Dati un cuvant :"))
s2 = str(input("Dati un cuvant :"))
s3 = str(input("Dati un cuvant :"))
s4 = str(input("Dati un cuvant :"))
cuvant=""
if (len(s1)>2 and len(s2)>2 and len(s3)>2 and len(s4)>2):
cuvant+=s1[0:2]+s2[0]+s3[0:3]+s4[0:len(s4)//2]
else:
print("Dati un cuvant, cu mai mult deca... |
4b76507d8f332d7c1311e6c9eed50a32510956bc | hagemon/StatLearning | /Python/mat.py | 564 | 3.546875 | 4 | import operator
import itertools
def sub(a, b):
assert len(a) == len(b)
return list(itertools.starmap(operator.sub, zip(a, b)))
def sub_square(a, b):
assert len(a) == len(b)
return itertools.starmap(operator.pow, zip(sub(a, b), [2]*len(a)))
def mul(a, b):
assert len(a) == len(b)... |
3c415f8c53d89461f2ecf7a7d5ac6adec64d1eca | qiaocco/reading-notes | /fluent-python/chap2_list/ex_2_9.py | 415 | 3.84375 | 4 | """
具名元组
"""
from collections import namedtuple
Product = namedtuple('Product', ('name', 'price', 'city'))
p = Product('手机', '5000', 'sh')
print(p.name, p.price) # 手机,5000
print(p[0]) # 手机
print(Product._fields) # ('name', 'price', 'city')
params = ('手机', '5000', 'sh')
print(Product._make(params)) # 生成实例==Produc... |
2d1967816d049233b44bbe231f18edeb42c6d7e6 | Adrian-Ng/Learning-Python | /Introduction/PrintFunction.py | 212 | 3.578125 | 4 | import math
if __name__ == '__main__':
n = int(input())
output = int(0)
for i in range(1,n+1):
output *= 10 * (10 ** math.floor(math.log(i, 10)))
output += i
print(output) |
db50c66ed6ff86e9e69a2a68f8f0ddf8f959cac6 | a01374764/Tarea_03 | /PagoDeUnTrabajador.py | 2,558 | 3.921875 | 4 | # encoding UTF-8
# Autor: Siham El Khoury Caviedes, A01374764
# Descripción: Cálculo del pago total de un trabajador.
# Calular y guardar en la variable pagoNormal el pago por las horas normales de un trabajador.
def calcularPagoNormal(horasNormales, pago):
pagoNormal = horasNormales * pago ... |
382770a30b3ea7ca77522a407d6208a8f1f0d16b | anju-netty/pylearning | /kidsquiz.py | 1,304 | 4.09375 | 4 | #!/Users/bin/python3
import random
"""
Quiz game throwing random questions at the user, continue the game if user choses and
display score at the end
"""
questionset = {
'Which animal lives in the North pole? : ': 'polar bear',
'Which is the largest animal? : ': 'elephant',
'Which is the fastest land anim... |
8ed44f676e29a187fa95e25265b30806a6d49138 | anju-netty/pylearning | /fizzbuzz_test.py | 795 | 3.578125 | 4 | import unittest
from fizzbuzz import solve_fizzbuzz
class TestFizzBuzz(unittest.TestCase):
def test_multiple_of_5(self):
list_zz = solve_fizzbuzz(5)
expected = "buzz"
self.assertEqual(list_zz,expected)
def test_solve_fizzbuzz_zero(self):
with self.assertRaises(ValueE... |
a7965122286820ecf5578b7e7c30fe6cd946220b | anju-netty/pylearning | /opening_reading_files.py | 736 | 3.84375 | 4 | #
#print("\n\nHello welcome\n\n")
#
##open the file in read only mode
#f = open('configuration.txt','r')
#
##read one character from the file to the variable 'content'
#content = f.read(1)
#
##print content
#print(content)
#
##read 3 characters from the file to the variable 'content' from the current position
#content ... |
c9ab056c96c7d1a0bf737d7268e8d2b991e59c12 | lein-g/LiaoXuefeng_Python | /3_函数_4_递归函数.py | 768 | 3.96875 | 4 | def product(a, *args):
s = 1
for x in args:
s = s*x
return a*s
print('product(5) =', product(5))
print('product(5, 6) =', product(5, 6))
print('product(5, 6, 7) =', product(5, 6, 7))
print('product(5, 6, 7, 9) =', product(5, 6, 7, 9))
if product(5) != 5:
print('测试失败!')
elif product(5, 6) ... |
12de12dc49ba043810c17210131769bb785e9918 | lein-g/LiaoXuefeng_Python | /5_函数式编程_2_返回函数_闭包.py | 3,268 | 3.96875 | 4 | """
高阶函数除了可以接受函数作为参数外,还可以把函数作为结果值返回
"""
# 当我们调用lazy_sum()时,返回的并不是求和结果,而是求和函数
# 调用函数f时,才真正计算求和的结果
def lazy_sum(*args):
def sum():
ax = 0
for n in args:
ax = ax + n
return ax
return sum
f = lazy_sum(1, 3, 5, 7, 9)
print(f)
print(f())
"""
我们在函数lazy_sum中又定义了函数sum,
并且,内部函数su... |
c7508cf5a5ac9d39a58c53b3bec473d5b2ced1b9 | seanofconnor/web-caesar | /caesar.py | 1,232 | 3.65625 | 4 | def encrypt(text, rot):
l = len(text)
i = 0
newText = ''
# cycle through chars in text
while i < l:
c = text[i]
newText = newText + rotate_character(c, rot)
i = i + 1
return(newText)
def alphabet_position(letter):
bet = ["a","b","c","d","e","f","g","h","i","j","k","l... |
ab9fa24c458013a8ea9b299552fdbdf75f3be47e | ICESDHR/Bear-and-Pig | /笨蛋为面试做的准备/leetcode/1.两数之和.py | 582 | 3.84375 | 4 | '''
给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
'''
def twoSum(nums, target):
lookup = {}
for i, num in enumerate(nums):
if target - num in lookup:
return [lookup[target - num], i]
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.