blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
d272e8386bb0e1f6a465bb64bfa269ad27c63c4e | kotalbert/learnpython | /codecademy/anti_vowel.py | 494 | 4.1875 | 4 | def is_vovel(character):
vovels = "aeiouAEIOU"
for v in vovels:
if v == character:
return True
else:
return False
def anti_vowel(text):
letters_list = []
for letter in text:
if not is_vovel(letter):
letters_list.append(letter)
new_text = "".join... |
3b9defa466461c21925b9179317766680be1f975 | kotalbert/learnpython | /utility/print_range.py | 123 | 3.84375 | 4 | def print_range(x):
print "Printing for %d" %x, range(1, x-1)
xs = range(1,25);
for x in xs:
print_range(x)
|
d3b90c124f87051c8bdd21e83dca649c3d58dda0 | angelaliu2015/mycode | /lab05.py | 814 | 4 | 4 | #!/usr/bin/env python3
dic = {"Flash":{"Speed": "Fastest", "Intelligence": "Lowest", "Strength": "Lowest"}, "Batman":{"Speed": "Slowest", "Intelligence": "Highest", "Strength": "Money"}, "Superman":{"Speed": "Fast", "Intelligence": "Average", "Strength": "Strongest"}}
char_name = input("which character do you want to k... |
45219f769275b1babae48ba5df9c53a28c6bcf1c | 99Moshiur/basic-python-code | /if_elseif_else.py | 238 | 4.15625 | 4 | name = input(str())
if name == "Rm khan":
print("Yes, you are Rm khan.")
elif name == "sagor":
print("Yes, you are Sagor")
elif name == "Rabbi":
print("Yes, you are Rabbi")
else:
print("We are not found your name.") |
6d04b0a184b63e2cff6c680757190682cdd47510 | char-exe/Train-ticket-chatbot | /chatbot/db.py | 2,555 | 3.953125 | 4 | import sqlite3
import csv
# Path to database
static = 'static/stations.csv'
# Connect to database
conn = sqlite3.connect('static/stations.db')
# Create cursor to execute SQL commands
cur = conn.cursor()
# Create new station name and station code tables if they don't exist
create_station_table = "CREATE... |
ec354df6780f93c9746dbf9f6db5cf6cef0b91ab | bleamer/practice | /Python/matChnOrd.py | 1,198 | 3.921875 | 4 | # The program tries to determine the order in which multiple
# a chain of matrices be mulliplied to have minimum number of
# multiplications
# DP approach to reduce number of count calculations
import sys
def MatrixChainOrder(p, n):
# Not using element 0
# m is the array used to remember the number of
# calcul... |
d8b2111b67520c825206f7174eebb0d0ce7c9f9c | bleamer/practice | /Python/CoinChange.py | 1,123 | 3.828125 | 4 | ''' Solution to Coin change problem https://www.hackerrank.com/challenges/coin-change '''
import os,sys
def solutions(expectedTotal, denominations):
NSol = [0 for x in range(expectedTotal+1)] # Number of solutions for all totals
#print(NSol)
#print(denominations)
NSol[0] = 1
# for all denomination... |
bf0ed613a2fa243e916811cbc6953b33e1f5aec1 | k8376654/test | /hw1-3.py | 1,072 | 4.15625 | 4 | # 3. 選擇性敘述的練習-electricity
# 輸入何種用電和度數,計算出需繳之電費。
# 電力公司使用累計方式來計算電費,分工業用電及家庭用電。
# 家庭用電 工業用電
# 240度(含)以下 0.15元 0.45元
# 240~540(含)度 0.25元 0.45元
# 540度以上 0.45元 0.45元
kind = eval(input("輸入您是何種用電戶,家庭用電=1,工業用電=2 :\n"))
if kind ==1 :
house = eval(input("輸入您的家庭用電度數 :\n... |
58763a54961521bd9c34a310d53010c2c8150fe9 | Yokto13/MikulasBotTO | /bot/tasks/scraper/timetable/models/teachers.py | 1,410 | 3.796875 | 4 | from .teacher import Teacher
class Teachers:
def __init__(self, teachers_path: str):
self._teachers_path = teachers_path
self.teachers = []
self.teachers_from_abbreviation = {}
self.teachers_from_name = {}
self._load_teachers()
def _load_teachers(self) -> None:
... |
d20fb6a2a48f71606391ad4e753cb63e44d9b99c | Sammion/DAStudy | /src/DAWithPython/ch07/Test09.py | 726 | 4 | 4 | '''
@author Sam
@date 2017-12-29
@des 第七章数据规整化:清理、转换、合并、重塑
这里主要练习计算指标/哑变量
另一种常用于统计建模或机器学习的转换方式是:将分类变量转换为哑变量矩阵或指标矩阵。
如果DataFrame的某一列中含有k个不同的值,则可以派出一个k列矩阵或DataFrame
'''
import pandas as pd
import numpy as np
df = pd.DataFrame({'key': ['b', 'b', 'a', 'c', 'a', 'b'],
'data1': range(6)})
print(df)
print... |
a3aacac935ea9f3322a143a80012ca7a38bead82 | Sammion/DAStudy | /src/DAWithPython/ch05/Test03.py | 2,691 | 3.671875 | 4 | '''
@author Sam
@date 2017-12-22
@des 第五章pandas入门
这里主要练习一下Index索引对象
pandas的索引对象负责管理轴标签和其他元数据(比如轴名称等)。
'''
import pandas as pd
import numpy as np
obj = pd.Series(range(3), index=['a', 'b', 'c'])
print(obj)
print('================>我就是分割线<==============')
data = {'state': ['hello', 'good', 'morning'],
'year': [... |
d0f534d2952598681463761f59784d88b7bd5e33 | mutasemalsallout/neural_network | /NN.py | 1,456 | 3.53125 | 4 | import numpy as np
class NN:
def __init__(self,x,y):
self.w1 = np.random.rand(x.shape[1], 3)
self.w2= np.random.rand(3,1)
self.a2 = np.zeros(y.shape)
def sigmoid(self,z):
return 1.0 / (1 + np.exp(-z))
def sigmoiddertive(self,z):
return z * (1.0 - z)
def ... |
94a2642e45aa007c91945ab279d13e39ded8f028 | tturin/PropertyAnalysis | /main/tester.py | 306 | 3.5625 | 4 | import pandas as pd
import numpy as np
## testing
df1 = {
'State': ['Arizona AZ', 'Georgia GG', 'Newyork NY', 'Indiana IN', 'Florida FL'],
'Score': [62, 47, 55, 74, 31]}
df1 = pd.DataFrame(df1, columns=['State', 'Score'])
print(df1)
df1['state_substring'] =df1.State.str.slice(0, 7)
print(df1)
|
7f0fa9ec6a3bb4ce96071d82eb9ecd8fc421ef5d | hadzaki/pizypwm | /opi.gpio/example.py | 1,416 | 3.53125 | 4 | # -*- coding: utf-8 -*-
import time
from pizypwm import *
# Set GPIO pin #11 as PWM output with a frequency of 100 Hz
pwm = PiZyPwm(100,'PA11') #сдесь 100 - частота, PA11 - ножка на гребенке
# Start PWM output with a duty cycle of 20%. The pulse (HIGH state) will have a duration of
# (1 / 100) * (20 / 100) = 0.002 seco... |
18ac5ef71bbaa2792712f23c9335e2d692f0be82 | sycLin/LeetCode-Solutions | /125.py | 384 | 3.5 | 4 | class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
# process input string
s = s.lower()
s = "".join([c for c in s if 'a' <= c <= 'z' or '0' <= c <= '9'])
for i in range(len(s) / 2):
if s[i] != s[len(s) - i ... |
969731fa973f98f905b8db12c617f3a1bfd4282b | sycLin/LeetCode-Solutions | /508.py | 1,419 | 3.53125 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def findFrequentTreeSum(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
... |
68d1ae2d4a6561ee0e19cef60e6d85bd0733cc73 | sycLin/LeetCode-Solutions | /056.py | 1,104 | 3.84375 | 4 | # Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""
# boundary case
... |
288fe4e05af7e2f8f0331dcc347dccfb2e53917d | wzqq5517992/pythonDemo | /第四节课程/作业/昨日优秀作业/黄丽萍-day3/storygame.py | 1,690 | 3.828125 | 4 | print("你好,我是机器人小U,现在和你玩一个游戏:抽签写故事。具体要素如下:\n"
"时间(1-3):早上、中午、半夜\n"
"人物(1-4):小明、小李、小白、小黑\n"
"地点(1-4):在房上、在地下、在电梯里、在厕所里\n"
"事件(1-4):吃饭、遛狗、飞翔、看书\n"
"请根据提示输入对应的数字")
def check_a():
global a
while True:
a = int(input("请输入对应的时间,数字1-3:"))
if a>3 or a<1:
print("输入... |
a2f8b5d800466dea638d95ef94a442328a950bbb | wzqq5517992/pythonDemo | /第三节课程/Demo5.py | 430 | 3.75 | 4 | #coding:utf8
#全局变量
a=100
def test1():
#局部变量和全局变量同名,会只用局部变量值
a=300
print("----test1---修改前----a={}".format(a))
a=400
print("----test1---修改后----a={}".format(a))
#test2读取的还是全局变量,不会受到test1的影响
def test2():
print("-----test2---a={}".format(a))
test1()
test2()
#在函数里面声明的变量,叫做局部变量
|
09c0e1a0132605da1f24f9b248f99aaa2ce687c6 | wzqq5517992/pythonDemo | /day7mysql/代码/untitled18/Demo9.py | 810 | 3.578125 | 4 | #coding:utf8
#综合练习
#如何做到我要插入一个同学,这个同学存在就不插入,如果不存在,就执行插入操作
#思路
#先查询这个同学在不在
#如果不存在执行插入语句
import mysql.connector as mysql
cnx=mysql.connect(user='root',password='MyNewPass4!',host='47.93.248.15',database='mystudent',port=20010)
#获得操作语句的游标
cursor=cnx.cursor()
#执行插入
sqlstr="select * from student where stu_name='全村的希望'"... |
65a11474e8294eb67b7e0de0fe9e417179f4df4f | wzqq5517992/pythonDemo | /ThirdOperation.py | 1,737 | 3.625 | 4 | print("抽签游戏马上要开始喽,请大家积极参与!")
while True:
time_num = int(input("1.你现在是否要随机生成时间(YES:1,NO:2):"))
time_one = ["情人节", "今天", "端午节", "清明节", "前几天", "除夕夜里", "劳动节", "国庆节"]
time_two = ["早上", "中午", "晚上", "半夜"]
if time_num == 2:
print("你选择了否 游戏结束了!")
break
place_num = int(input("2.你现在是否要随机生成地点(Y... |
95d7886ec7192f00d54dbb377da2cad39d5f72b9 | wzqq5517992/pythonDemo | /第四节课程/作业/上期优秀代码/王延克/main.py | 1,512 | 3.65625 | 4 |
#导入获取资源文件的module
from module_resource import *
def main():
"""程序的主方法"""
while True:
time=get_num("请输入时间(1-4),输入q退出程序:")
if time == 0 :
print("谢谢使用,程序退出。。。。。。")
break
time_str=get_time(time)
person = get_num("请输人物(1-4),输入q退出程序:")
if person == 0:
... |
6e85f745577db3124c504c98a30bff21e8ed699e | muskaan-codes/leetcoding-challenges | /SeptemberCodingChallenge/Day-12-Insert-Interval.py | 867 | 3.546875 | 4 | class Solution(object):
def insert(self, intervals, newInterval):
"""
:type intervals: List[List[int]]
:type newInterval: List[int]
:rtype: List[List[int]]
"""
from collections import deque
intervals.append(newInterval)
intervals.sort()
length ... |
4f02a434c9323d1155ca307d8f60c7e9fcc92a36 | abir-taheer/learnination-fruition | /hw40.py | 3,619 | 4.40625 | 4 | # Abir Taheer
# IntroCS pd1
# HW40 -- Oh, Give Me a Home Where the Buffalo Roam
# 2019-04-15
import random
def merge(L1, L2):
"""
Returns a new list containing the elements of both lists, in sorted (ascending) order.
Assumes each input list is sorted. Length of output list must equal sum of lengths of inp... |
e170641ef11f4d10aca307cc91d9c095aa87cb00 | abir-taheer/learnination-fruition | /hw31.py | 1,983 | 4.25 | 4 | # Team Bet, Thanks A Lot
# Abir Taheer, Shah Wafi, Alex Tang
# IntroCS pd1
# HW31 -- Cereal-Grade Encryption
# 2019-03-28
alphabet = "abcdefghijklmnopqrstuvwxyz"
def rot_char(c, shft):
"""
A helper function that encodes a character by allowing you to set the character rotational offset to any number
:par... |
d503bac274d46643c0d8e6485c60464295587ee7 | abir-taheer/learnination-fruition | /hw30.py | 1,859 | 3.96875 | 4 | # Abir Taheer
# IntroCS pd1
# HW30 -- 000 000 111, v11
# 2019-03-25
def tablefyASCII():
"""
:return: HTML code that generates a table containing all uppercase and lowercase letters alongside their ASCII code
"""
letters = "abcdefghijklmnopqrstuvwxyz"
html = "<table>\n\t<tr>\n\t\t<th>Letter</th>\n\... |
5d85d857ea45fbe28e84e5ecf1b4bd1c2bd7cfaa | JaySRT/Python_Calculator | /src/Calculator.py | 877 | 3.765625 | 4 | def addition(a, b):
return a + b
def subtraction(a, b):
return b - a
def multiplication(a, b):
return a * b
def division(a, b):
return round((b / a), 9)
def square(a):
return a * a
def sqrt(a):
return round(a**(1/2), 8)
class Calculator:
result = 0
def __init__(self):
pass... |
f425184a898889340bc8bad877d3a17641ffa758 | mursigkeit22/py_weekly_charm | /long_integers/1_size.py | 765 | 3.65625 | 4 | import sys
print(sys.version) # есть разница, 64бит или 32бит. На 32бит размеры меньше: инт - 14
# размер int: 0 занимает 24 байта, далее 28 байт, + 4 байт на каждый новый блок (2**30)
print(sys.int_info)
list_of_int_values = ['0', '1', '10', '257', '2**30-1', '2**30', '2**30+1', '2**60', ]
list_of_negative_int_valu... |
4b908d5b2306e9bcc2d3e1a10981f45dd2e8fdc5 | mursigkeit22/py_weekly_charm | /asynchronous/asynch_beginners/_1_count_async.py | 982 | 4.15625 | 4 | import asyncio
import codetiming
import time
# A coroutine is a specialized version of a Python generator function:
# a function that can suspend its execution before reaching return,
# and it can indirectly pass control to another coroutine for some time.
async def count(name):
print(f"One {name}")
await as... |
3e97dd4c6b35b6d426f4ae50c9456a9cd0d1f135 | mursigkeit22/py_weekly_charm | /asynchronous/concurrency/_2_treading_local_Pool_map.py | 2,765 | 3.640625 | 4 | import concurrent.futures
import requests
import threading
import codetiming
thread_local = threading.local() # Threading.local() creates an object that look like a global but is specific to
# each individual thread.
# a threading.local() object only needs to be created once,
# not once per thread nor once per func... |
974f4d9bfc64012a6863a26546ce933390355102 | youguanxinqing/Six_Sort | /MergeSort.py | 635 | 3.84375 | 4 | """
归并排序
"""
def separate(array):
if len(array)<=1:
return array
n = int(len(array)/2)
left = separate(array[:n])
right = separate(array[n:])
return merge_sort(left, right)
def merge_sort(left, right):
l, r = 0, 0
result = []
while l<len(left) and r<len(right):
if ... |
84fae1107690c8a6d64e70431b56b13c2863fc15 | enzofc/ECAS_11243774-CEN0336 | /script_hipotenusa.py | 898 | 4.21875 | 4 | #!/usr/bin/env python3
print('Insira os lados do triangulo')
a = int(input("a: "))
b = int(input("b: "))
import sys
a = sys.argv[1] # obter primeiro cateto
b = sys.argv[2] # obter segundo cateto
isinstance(a, int) # confirmar que o valor inserido e um inteiro
isinstance(b, int) # confirmar que o valor inserido e um int... |
7969943dbae4e23d63be5b1dc25a3e4a35efec1a | Tbones41/python_Mentorship_Tolulope | /Week_2/Challenge_2-3.py | 615 | 4.21875 | 4 | def sum_odd(a, b):
output = 0
while 0 < a < b < 10000:
for number in range(a, (b+1)):
if number % 2 == 1:
output += number
return output
else:
if a > b:
return "Number A should not be greater than Number B"
elif a or b < 0:
... |
aff85452c57d2ea3764bb5982d43d9046ce1d210 | Tbones41/python_Mentorship_Tolulope | /Week_1/Challenge_4.py | 237 | 4.0625 | 4 | def check_nums(num1, num2):
if num2 > num1:
return "True"
elif num2 == num1:
return "-1"
else:
return "False"
check_nums(float(input("Input Number 1: ")), float(input("Input Number 2: ")))
|
070625103602fda01112f3bbdde62d95bc7a3edc | steezkelly/TkInter | /classes.py | 1,235 | 4.0625 | 4 | from tkinter import *
class StevesButtons:
#__init__(self) special function, initialize automatically an object
#master means root/mainwindow pass it in for GUI, creates root/mainwindow
def __init__(self, master):
frame = Frame(master)
frame.pack()
#use self to create widgets/buttons
self... |
1cd3a4334a9722577c1f6fcde444d687425725f7 | steezkelly/TkInter | /functionslayout.py | 790 | 4.28125 | 4 | from tkinter import *
#Calls Tk class, root is "main window"
root = Tk()
#Prints Hello my name is Steve!
#event is something a user can do, mouse click, key pressed, etc.
def printName(event):
print("Hello my name is Steve!")
def printNumber(event):
print("5")
#When passing in function, make sure not to do ... |
7e78bb50d584d53638b77717c0cf1a2fc2174679 | nkint/projectEuler | /seventeen.py | 1,387 | 3.859375 | 4 |
wordnumber = {
0: "zero",
1: "one",
2: "two",
3: "three",
4: "four",
5: "five",
6: "six",
7: "seven",
8: "eight",
9: "nine",
10: "ten",
11: "eleven",
12: "twelve",
13: "thirteen",
14: "fourteen",
15: "fifteen",
16: "sixteen",
17: "seventeen",
18: "eighteen",
19: "nineteen",
20: ... |
4642700cc5778a26ee26fcfc7bf5c626e413b351 | nkint/projectEuler | /fiftyone.py | 2,005 | 3.640625 | 4 | def maxprimes(max):
'''thanks riko! get all primes under max.
'''
max = int(max)
limit = int(max**0.5 + 1.5)
s = set(range(3, max, 2)).difference(
j for i in range(3, limit, 2) for j in range(i*i, max, i))
s.add(2)
return s
def combine(s, k, m):
#print("combine", s, k, m)
if k==0:
return [s]
if k==len(s)... |
0cbf85fa9b31a62e4b4cdd8910716fabddbda0f8 | iambrookedrake/DS-Unit-3-Sprint-2-SQL-and-Databases | /module1-introduction-to-sql/AssnPt2/buddymove_holidayiq.py | 2,135 | 3.796875 | 4 | import pandas as pd
import os
import sqlite3
df = pd.read_csv("module1-introduction-to-sql/assnpt2/buddymove_holidayiq.csv")
# print(df)
DB_FILEPATH = os.path.join(os.path.dirname(__file__),
"buddymove_holidayiq.sqlite3")
connection = sqlite3.connect(DB_FILEPATH)
print("CONNECTION:", conne... |
57060593d0c9ccbc18382132b350266d14850e01 | robynsen/adventofcode2016 | /aoc13-part2.py | 1,126 | 3.53125 | 4 |
def isSpace(x, y):
return (bin(x*x + 3*x + 2*x*y + y + y*y + 1364).count("1") % 2 == 0)
def getNextSteps(myPos):
myNextSteps = []
x = myPos[0]
y = myPos[1]
if (x - 1 >= 0) and isSpace(x-1, y):
myNextSteps.append((x-1, y))
if isSpace(x+1, y):
myNextSteps.append((x+1... |
158b95287b0e3e033ec3f5dba2d9ca112df850a8 | romeojha/turtles | /selfdraw_turtle.py | 1,229 | 3.96875 | 4 | # from blackjack.blackjack import you_won
from turtle import Turtle, Screen, clear, color, fillcolor
import turtle
import random
screen = Screen()
screen.setup(height=800, width=1000)
turtle1 = Turtle()
turtle1.penup()
turtle1.setposition(300, 300)
turtle1.pendown()
turtle1.right(90)
turtle1.fd(600)
user_ans = scree... |
bf80ebef8124ae74647e39a22e9ac57deb623330 | jamil2gomes/uri-python | /uri1001/uri1020.py | 211 | 3.546875 | 4 | anos = meses = dias = 0
a = int(input())
anos = int(a / 365)
meses = int((a % 365) / 30)
dias = int((a % 365) % 30)
print("{:d} ano(s)\n"
"{:d} mes(es)\n"
"{:d} dia(s)".format(anos, meses, dias))
|
bb8640cd32e71f472659eab9c7df9f07678d373e | chelsea-shu/codingHW | /float_increment.py | 2,042 | 4.15625 | 4 | import argparse
def counter(start, end, inc):
list = []
if start < end:
while start < end:
list.append(start)
start += inc
else:
while start > end:
list.append(start)
start += inc
print(", ".join(str(ii) for ii in list))
def main():
... |
a24b930b05b472dbb80a880c6f78550afaa2b145 | chelsea-shu/codingHW | /word_frequency.py | 2,481 | 4.125 | 4 | def parse_file(input_filename):
# """This function reads from an input file and returns all the
# words in a list. This is a helper function; treat as black box.
# """
word_list = []
# to save each line as a string in a list
input_file = open(input_filename).readlines()
for line in input_... |
b1463903fed06ebbb23ec0b8262c139246f19c4d | Mahdi24w/LearningProjects | /pyramid.py | 254 | 4.09375 | 4 |
x = int(input("enter the height from 1 to 10: \n"))
while x < 1 or x > 10:
x = int(input("enter the height only between 1 and 10: \n"))
if (x >= 1 and x <= 10):
for i in range(1,x+1):
print(" "*x + "#"*i + " "*2 + "#"*i)
x-=1
|
ff8bb506333f14154135af012b822af3490f57ad | superdicdi/fisher | /app/libs/helper.py | 532 | 3.5625 | 4 | __author__ = "TuDi"
__date__ = "2018/12/17 上午11:29"
def is_isbn_or_key(word):
"""
根据 word 判断用户是 sbin 查询还是关键字查询
"""
isbn_or_key = "key"
# isbn 由13个0~9的数字组成
# isbn 含有10个0~9的数字组成,可能额外包括一些"-"
if len(word) == 13 and word.isdigit():
isbn_or_key = "isbn"
short_word = word.replace("-",... |
9f186830e7d09eb9a99de317914fe49da97c1800 | lyyljs/learnpython2.7 | /pybasic/tuple.py | 179 | 3.59375 | 4 | classmates = ('lyy','ljs','floyd')
t = (1,2)
print t
# t[1] = 3
print t
t = ()
print t
a = ()
print a
b = (1,)
print b
c = ('a','b',['A','B'])
c[2][0] = 'X'
c[2][1] = 'Y'
print c
|
e0ea0679975b1dc6b26d4723bd1ac4ec95a8f46e | lyyljs/learnpython2.7 | /pybasic/charencode.py | 500 | 3.734375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
print 'ord(\'A\') =',ord('A')
print 'chr(65) =',chr(65)
print 'Then use unicode:'
print u'中文'
a = u'中'
print 'a =',a
t = u'ABC'.encode('utf-8') #utf to utf-8
t = u'中文'.encode('utf-8') #utf to utf-8
print 'len(u\'ABC\') =',len(u'ABC')
print 'len(\'ABC\') =',len('ABC')
print ... |
ee56bd687ba22cd692482612f4b6285cc8269d56 | lyyljs/learnpython2.7 | /special/generator.py | 194 | 3.5 | 4 | g = (x * x for x in range(10))
#print g.next()
#for n in g:
# print n
def fib(max):
n,a,b = 0,0,1
while n < max:
yield b
a,b = b,a + b
n = n + 1
print fib(6)
for n in fib(6):
print n
|
56b6e7ee2893fc20d367ae4973f378b3a0f2a138 | gabreuvcr/curso-em-video | /mundo2/ex057.py | 309 | 4 | 4 | ## EX057 ##
sexo = ''
while (sexo != 'F') and (sexo != 'M'):
sexo = str(input('Digite o seu sexo (M/F): ')).strip().upper()
if (sexo != 'F') and (sexo != 'M'):
print('ERROR: Valor invalido.\n')
if sexo == 'F':
print('\nSeu sexo é feminino!')
else:
print('\nSeu sexo é masculino!')
|
251bc63945b4a3d673ff54dca892375ac0ed1a19 | gabreuvcr/curso-em-video | /mundo1/ex006.py | 204 | 3.96875 | 4 | ## EX006 ##
num = int(input('Digite um numero: '))
print('O seu dobro é: {}'.format(num * 2))
print('O seu triplo é: {}'.format(num * 3))
print('A sua raiz quadrada é: {:.2f}'.format(num ** (1 / 2)))
|
9aa180b99a0474c2fffb4d2c087acc744b88c820 | gabreuvcr/curso-em-video | /mundo1/ex023.py | 1,171 | 4.125 | 4 | ## EX023 ##
print('Com matematica: ')
num = int(input('Digite um numero entre 0 e 9999: '))
unidade = (num // 1) % 10
dezena = (num // 10) % 10
centena = (num // 100) % 10
milhar = (num // 1000) % 10
if num > 9999 or num < 0:
print('Valor invalido.')
else:
print('unidade: {}'.format(unidade))
print('dezena... |
96193ff6a47ef57fae3ca0f16b2eb572e2cd8569 | gabreuvcr/curso-em-video | /mundo3/ex089.py | 837 | 3.578125 | 4 | ## EX089 ##
geral = []
while True:
nome = str(input('Nome: ')).strip().upper()
nota1 = float(input('Nota 1: '))
nota2 = float(input('Nota 2: '))
resp = str(input('Quer continuar [S/N]? ')).strip().upper()[0]
media = (nota1 + nota2) / 2
geral.append([nome, [nota1, nota2], media])
print()
... |
86e926b42900a21c8dbca409daeba6f488357837 | gabreuvcr/curso-em-video | /mundo3/ex092.py | 584 | 3.578125 | 4 | ## EX092 ##
from datetime import date
geral = {}
geral['nome'] = str(input('Nome: ')).strip().capitalize()
ano = date.today().year
nascimento = (int(input('Ano de nascimento: ')))
geral['idade'] = ano - nascimento
geral['ctps'] = int(input('Carteira de trabalho (Digite 0, se não tiver): '))
if geral['ctps'] > 0:
g... |
b28c41ed39c693f61eb913e86a20bf12f2985a38 | gabreuvcr/curso-em-video | /mundo3/ex104.py | 287 | 3.828125 | 4 | ## EX104 ##
def leiaInt(msg):
while True:
n = input(msg)
if n.isnumeric():
n = int(n)
break
print('ERRO! Digite um valor inteiro válido.')
return n
n = leiaInt('Digite um numero: ')
print(f'O numero que você digitou foi {n}')
|
a3097847855751bbf03ac7658ec677a06824fad6 | gabreuvcr/curso-em-video | /mundo3/ex093.py | 724 | 3.71875 | 4 | ## EX093 ##
aproveitamento = {}
gols = []
aproveitamento['nome'] = str(input('Nome do jogador: ')).strip().capitalize()
partidas = int(input(f'Quantas partidas {aproveitamento["nome"]} jogou? '))
for i in range(1, partidas + 1):
gols.append(int(input(f' Quantos gols na {i}º partida? ')))
aproveitamento['gols'] = ... |
f6e310a2b578e525b1d66d572e7b4374873080a6 | gabreuvcr/curso-em-video | /mundo2/ex059.py | 909 | 3.875 | 4 | ## EX059 ##
opcao = 4
while opcao != 5:
if opcao == 4:
print('')
n1 = int(input('Digite o 1º numero: '))
n2 = int(input('Digite o 2º numero: '))
print('''\n[1] Soma
[2] Multiplicar
[3] Maior
[4] Novos digitos
[5] Sair do programa''')
opcao = int(input('>>> Digite uma opção: '))
... |
9db817e62034fea0b01adfe64a2ff5483fcc0b90 | gabreuvcr/curso-em-video | /mundo1/ex012.py | 180 | 3.765625 | 4 | ## EX012 ##
preco = float(input('Digite o preço do produto: '))
#5% de desconto
desconto = preco * 0.95
print('O preço com 5% de desconto é de {:.2f} reais.'.format(desconto))
|
0cc1f0281d72d9077b1436a094bffa13db99b3d7 | gabreuvcr/curso-em-video | /mundo2/ex049.py | 149 | 3.96875 | 4 | ## EX049 ##
num = int(input('Digite o numero para saber sua tabuada: '))
for i in range(0, 21):
print('{} x {:2} = {}'.format(num, i, num * i))
|
5d3704268b69890d20de7799f6d3d980088d4c36 | gabreuvcr/curso-em-video | /mundo3/ex099.py | 554 | 3.78125 | 4 | ## EX099 ##
from time import sleep
def maior(* numeros):
print('\nAnalisando os valores passados...')
tam = len(numeros)
maior = 0
for k, v in enumerate(numeros):
print(v, end = ' ', flush = True)
sleep(0.1)
if (k == 0) or (v > maior):
maior = v
print(f'\nForam i... |
28c3a33436203db55c59ede6835dfbf5091b942d | gabreuvcr/curso-em-video | /mundo1/ex015.py | 218 | 3.578125 | 4 | ## EX015 ##
km = float(input('Digite a quantidade de km rodados: '))
dias = int(input('Digite a quantidade de dias que foi alugado: '))
preco = (60 * dias) + (0.15 * km)
print('Total a pagar: R${:.2f}'.format(preco))
|
770a74f76a5213c746c63a9c51a7e5ad45778dfe | DavidLewinski/CA117 | /week03/a/qnou_031.py | 226 | 3.75 | 4 | #!/usr/bin/env python3
import sys
low = sys.stdin.readlines()
def qnou(s):
s = s.replace("qu", "")
return "q" in s
qnous = [word.strip() for word in low if qnou(word.lower())]
print("Words with q but no u:", qnous) |
eb954e2407d0d8a0d749f44b79e49d1a5a74dcc8 | DavidLewinski/CA117 | /week02/a/anagram_021.py | 324 | 3.921875 | 4 | #!/usr/bin/env python3
import sys
def anagram(left, right):
for c in left:
if c in right:
right = right.replace(c, "", 1)
else:
return False
return right == ""
for line in sys.stdin:
tokens = line.strip().split()
left, right = tokens
res = anagram(left, right)
print(re... |
987e720b2e0e162b53489a565f45084ae77089f2 | DavidLewinski/CA117 | /week11/graph_111.py | 977 | 3.640625 | 4 | #!/usr/bin/env python3
class Graph(object):
def __init__(self, V):
self.adj = {}
self.V = V
for v in range(V):
self.adj[v] = list()
def addEdge(self, v, w):
self.adj[v].append(w)
self.adj[w].append(v)
class DFSPaths(object):
def __init__... |
e445b729e365d96a0a74c7f08707db1403b91bb0 | DavidLewinski/CA117 | /week10/reverse_102.py | 116 | 3.96875 | 4 | #!/usr/bin/env python3
def reverse_list(nums):
if len(nums) == 0:
return 0
return nums[::-1]
|
35e65cf25ba43f24f821cd0fd4ac9b7f1f2bebaa | DavidLewinski/CA117 | /week01/a/middle_011.py | 225 | 3.875 | 4 | #!/usr/bin/env python3
import sys
for words in sys.stdin:
words = words.strip()
mid = len(words) // 2
if len(words) % 2 == 1:
print(words[mid])
else:
print("No middle character!")
|
7649129554b432621fe67e2a8f12a80be8f9559a | DavidLewinski/CA117 | /week03/a/birthday_021.py | 817 | 3.734375 | 4 | #!/usr/bin/env python3
import sys
import calendar
line = sys.stdin.readlines()
daysoftheweek = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
lines = ["Monday's child is fair of face", "Tuesday's child is full of grace", "Wednesday's child is full of woe", "Thursday's child has far to ... |
2a0f450cbed88a4b3ba0a585ef9fd0133b36e9ab | DavidLewinski/CA117 | /week01/a/substring_011.py | 250 | 3.734375 | 4 | #!/usr/bin/env python3
import sys
lines = sys.stdin.readlines()
for a in lines:
s = a.rstrip().lower().split()
character = s[0]
word = s[1]
if character in word:
print("True")
else:
print("False")
|
8f45d23ef3025d0a27a23e047903f0c59a788359 | tcbegley/advent-of-code | /2021/day12.py | 2,157 | 3.59375 | 4 | import sys
from collections import defaultdict
class Graph:
def __init__(self):
self.nodes = {}
self.edges = defaultdict(set)
def add_edge(self, node1, node2):
self.nodes[node1] = node1 == node1.lower()
self.nodes[node2] = node2 == node2.lower()
self.edges[node1].add(n... |
0d53b3fe2fb423470b088bc0a8246d85d7ace535 | tcbegley/advent-of-code | /2021/day03.py | 1,300 | 3.5625 | 4 | import sys
def load_numbers(path):
with open(path) as f:
numbers = [line.strip() for line in f.readlines()]
num_digits = len(numbers[0])
return [int(num, base=2) for num in numbers], num_digits
def part_1(numbers, num_digits):
gamma = sum(
1 << i
for i in range(num_digits - 1... |
caef30c002ef05d1cc7098aef977b099c4803362 | tcbegley/advent-of-code | /2016/day09.py | 1,523 | 3.546875 | 4 | import sys
def load_data(path):
with open(path) as f:
return f.read().strip()
def decompress(characters):
result = ""
left, right = 0, 0
while "(" in characters[left:]:
left = characters[left:].index("(") + left
result += characters[right:left]
right = left + 1
... |
71e39e5afd2a4d57f9880fe815610d1b016a73d9 | tcbegley/advent-of-code | /2018/day10.py | 2,114 | 3.515625 | 4 | import re
import sys
from dataclasses import dataclass
NUMBER = re.compile(r"-?\d+")
@dataclass
class Particle:
position: tuple[int, int]
velocity: tuple[int, int]
def pos(self, t):
x, y = self.position
vx, vy = self.velocity
return (x + t * vx, y + t * vy)
def load_data(path):... |
1bb83d3c17f42af4b93aa99aa947dc0b1609b79f | Pergamene/cs-module-project-algorithms | /sliding_window_max/sliding_window_max.py | 703 | 4.21875 | 4 | from collections import deque
'''
Input: a List of integers as well as an integer `k` representing the size of the sliding window
Returns: a List of integers
'''
def sliding_window_max(nums, k):
maxes = []
dq = deque()
for i in range(k):
while dq and nums[i] >= nums[dq[-1]]:
dq.pop()
dq.append(i)
... |
f26c004a2d3c67424d113c623e8d185da44e94b7 | rammonzito/stackoverflow-helping | /python/sintaxe/stackoverflow.py | 3,561 | 3.984375 | 4 | import os
def painel():
print('1 - inserir outro nome\n2 - contar nome\n3 - remover o último nome\n4 - inserir nome em índice específico')
print('5 - remover nome específico\n6 - remover o último nome\n7 - remover a primeira ocorrência do nome')
print('8 - retornar índice de nome específico\n9 - reverter to... |
f468706c7182b8f4842affd2dedd1919c4b2df54 | SnZhdanov/Python_Crypt | /SimpleCaesarC.py | 3,064 | 3.9375 | 4 |
#turn text into list of numbers (ASCII values)
import random
def encode(text):
#turn to lower case
text = text.lower()
#only keep letters
lst = [(ord(letter) - ord('a')) for letter in text if letter.isalpha()]
return lst
#turn list of ASCII values into text
def decode(lst):
t... |
7c95933d530310d5c05ea5d90c21284711879952 | HashanDilhara1996/Application-using-B-tree-Merge-Sort-Binary-Search | /B Tree,_Merge_Sort_and_Binary_Search(31)/MergeSort.py | 1,283 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Merge Sort.
Created on Fri Oct 16 17:00:27 2020
@author:
"""
def mergeSort(myList):
if len(myList)>1:
return mergeSubList(mergeSort(myList[:len(myList)//2]),mergeSort(myList[len(myList)//2:]))
else:
return myList
def mergeSubList(list1,list2):
new... |
90e13721f25478514eedc8e2c8d021b0cb53056d | tiliv/advent-of-code | /2019/04 Secure Container.py | 404 | 3.53125 | 4 | from collections import Counter
password_range = (272091, 815433)
candidates = []
for password in range(*password_range):
password = str(password)
if ''.join(sorted(password)) != password:
continue
repeats = [common[1] for common in Counter(password).most_common(len(password))]
if 2 not in rep... |
6cc44bfe7282e00364feff37c25586211fe9a05b | DorotaPawlowska/programming-practice | /books/Z.A.Shaw/ex21-30/ex21.py | 1,280 | 3.953125 | 4 | def add(a, b):
print(f"DODAWANIE {a} + {b}")
return a + b
def substract(a, b):
print(f"ODEJMOWANIE {a} - {b}")
return a - b
def multiplay(a, b):
print(f"MNOŻENIE {a} * {b}")
return a * b
def divide(a, b):
print(f"DZIELENIE {a} / {b}")
return a / b
print("Wykonajmy kilka operacji mate... |
0c7899789d28bacb77d19db1418414c9c7a74542 | DorotaPawlowska/programming-practice | /books/Z.A.Shaw/ex31-40/ex39.py | 1,597 | 3.6875 | 4 | # tworzymy mapowanie nazwy stanu na skrót
states = {
'Oregon': 'OR',
'Floryda': 'FL',
'Kalifornia': 'KA',
'Nowy Jork': 'NJ',
'Michigan': 'MI'
}
# tworzymy podstawowy zestaw stanów i znajdujących się w nich miast
cities = {
'KA': 'San Francisco',
'MI': 'Detroit',
'FL': 'Jacksonville'
}
... |
edaf2492618dca1bb9a3a0eaba8cce0da276ddf0 | DorotaPawlowska/programming-practice | /books/Z.A.Shaw/ex31-40/ex31.py | 1,787 | 3.921875 | 4 | print("""Wchodzisz do ciemnego pokoju z wieloma drzwiami.
Przechodzisz przez drzwi na 1 czy nr 2 czy nr 3?""")
door = input("> ")
if door == "1":
print("Widzisz tam wielkiego niedźwiedzia, który zajada sernik.")
print("Co robisz?")
print("1. Zabierasz sernik.")
print("2. Krzyczysz na niedźwiedzia.")
... |
37fb651be3e780eb273e09b7243c408d86fed3e1 | Kerrin631/homie | /Pylot/app/models/WelcomeModel.py | 917 | 3.828125 | 4 | """
Sample Model File
A Model should be in charge of communicating with the Database.
Define specific model method that query the database for information.
Then call upon these model method in your controller.
Create a model using this template.
"""
from system.core.model import Model
class Wel... |
82fd6cee999375a60b124cf6e962b4bd231c1b91 | Amaankit/Tic-Tac-Toe | /tic_tac_toe.py | 4,363 | 3.75 | 4 | cc=0
def playermove(): #TO READ PLAYERS MOVE
run=True
while(run):
move=input("ENTER A POSITION TO PLACE 'X' IN POSITION (1-9) ")
try:
move=int(move) #STRING ENTER HONE PR ERROR NAHI AAYE ISILIYE
if move>0 and move<10:
if(issapcefree(move)): ... |
9e89e61b9cdaa89b4b53ab8fcabee24b87b73813 | MohamedAshikAnwar/codekata1 | /set1-7.py | 61 | 3.640625 | 4 | i=0
an=int(input())
for i in range(i,an):
print("hello")
|
cde6c827e133c4be5c2ca085d12ceb31dce879f2 | untxi/IA | /tareas/Neurona/Neuron.py | 1,840 | 3.890625 | 4 | # Tecnologico de Costa Rica
# Escuela de Ing en Computacion
# Curso de Inteligencia Artificial
# Neurona
# Problema de Categorizacion, Redes Neuronales
# Samantha Arburola, Mayo 2018
# Library
import random
class Neuron:
def __init__(self):
self.realDataC1 = []
self.realDataC2 = []
self.r... |
a679cbb77b69713545d41a8f9e45ee8942fa3c85 | jshams/Tweet-Generator | /markov_chain.py | 5,499 | 3.671875 | 4 | str = ['one', 'fish', 'two', 'fish', 'red' ,'fish', 'blue', 'fish']
from dictogram import Dictogram
from linkedlist import LinkedList
import random
def markov_chain(word_list):
mc = {}
for i, word in enumerate(word_list):
if i == len(word_list) -1:
return mc
if word in mc:
... |
7836e58cc371a2756344560b04cb46e4652a7d98 | Shahbaz-mahmood123/Python-GUI-project | /LaundryService/skylaundryOrder.py | 1,641 | 3.640625 | 4 | #Emil Sofrone Customer GUI
from tkinter import *
import tkinter.messagebox
##root = Tk()
#image
root = tkinter.Toplevel()
img = PhotoImage(file = ("laundry.gif"))
panel = Label(root, image = img)
panel.pack(side = "bottom", fill = "none", expand = "no")
panel.grid(row=6,column=0)
#
file = open("Customer.txt", "w"... |
05f24ece9bbcec00d4ce08fec99622590e7d9fff | jwl317/ProblemSolvingAndAlgorithms | /week9/prob3.py | 700 | 3.53125 | 4 | def bigger5(nums): #나는 새로운 리스트를 만들어서 반환하고 싶다.
result = []
for i in nums:
if i > 5:
result.append(i)
return result
def bigger5_version2(nums): #나는 원본리스트 자체에서 빼내고 싶다.
for i in range(len(nums)-1, -1, -1): #리스트를 거꾸로 조회하면서 삭제해야
... |
c676762e974e30355dc8ca448691941fdf6b8b54 | jwl317/ProblemSolvingAndAlgorithms | /week5/week5_problem3.py | 464 | 3.59375 | 4 | num = [8, 7, 3, 2, 9, 4, 1, 6, 5]
Min = num[0] # Min = 8로 시작
Max = num[0] # Max = 8로 시작
for i in range(1, len(num)): #num의 2번째 ~ 마지막 값까지만 비교
if num[i] < Min:
Min = num[i] #최소값 갱신
if num[i] > Max:
Max = num[i] ... |
e5467be0c10469f5ab7e54e20ef97742a3281d1d | jwl317/ProblemSolvingAndAlgorithms | /week2/week2_problem2.py | 693 | 3.84375 | 4 | '''
1. 영어 점수와 수학 점수를 정수형태로 입력 받는다.
2. 둘 중에 하나라도 40미만의 점수인 경우 불합격 출력
3. 모두 40을 넘었을 경우 110점 이상(초과) 인 경우만 합격 출력
4. 110점 미만인 경우에는 불합격 출력
'''
eng = int(input('영어 점수를 입력하세요: '))
math = int(input('수학 점수를 입력하세요: '))
if eng < 0 or math < 0: #필수 코드는 아닙니다.
print('입력이 잘못 되었습니다')
if... |
09bca5e874a527b4dc75401bba9016ef828f0a4f | Rodriguevb/INFO-F206-Informatique-Project-201415 | /src/projetINFOF206.py | 1,868 | 3.828125 | 4 | import sys
import random
def createDNA (n):
"""
Crée un brin d'ADN sans aucune répétition en tandem.
"""
sigma = []
alphabetgenetique = ["A","C","G","T"]
while len(sigma) < n: # Tant qu'on obtient pas la longueur de brin d'ADN voulu, la boucle continue à tourner.
print (sigma)
sigma . ... |
024ffbd9d3b6d322bc289818df467b6d5a980b82 | anida21/python-minibankomat-studenti | /studenti.py | 2,288 | 3.984375 | 4 | class Student:
def __init__(self, ime, pismeni=0, usmeni=0, prosjek=0):
self.ime = ime
def PostaviPis(self, b):
self.pismeni = b
def PostaviUsmeni(self, b):
self.usmeni = b
def Dajime(self):
return self.ime
def DajProsjek(self):
return self.prosjek
de... |
ca8a8a1c769e10f4750562220e04ae0984df5a5e | lorinmiley/NewProject | /_main_.py | 3,929 | 4.1875 | 4 | #Computational Geometry Project
#The purpose of this project is to create a python application where the user can input a text file
# that contains a header with a type of problem to solve, line segment intersection, closest pair points,
# convex hull, or largest empty circle followed by a given set of points seper... |
c116d4af4460f91aa248bac680248efd3feb5021 | Sagar3195/Django-demo | /mpgapp.py | 2,489 | 3.515625 | 4 | ## Importing required libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings('ignore')
## Loading datasets
data = pd.read_csv("mpg_data_example.csv")
print(data.head())
print(data.shape)
##Let's check missing values... |
93bd9b2d5171e5fb8125119a3dfcd672c6b4062b | OcarinGit/KagglePandas | /Pandas1SeriesDataFramesTest.py | 1,154 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Sep 20 18:41:54 2019
@author: User
"""
import pandas as pd
#(https://i.imgur.com/Ax3pp2A.png)
# Your code goes here. Create a dataframe matching the above diagram and assign it to the variable fruits.
fruits = pd.DataFrame({"Apples":[30],"Bananas":[21]})
print(fruits)
# Yo... |
1dde4ed7100097741824f1f70407054df11e05b1 | aakimbaeva/Chapter1Part2Task13 | /task13.py | 92 | 3.890625 | 4 | num = int(input('Write a number: '))
print([i ** 2 for i in range(1, num) if i ** 2 <= num]) |
6bbca2fc63f7bb8c08950a096158cce752e32528 | jmccann2000/Algorithms | /insertionSort.py | 603 | 4.15625 | 4 | #Insertion sort is optimized for a small seqence size, similiar to
#sorting cards in a hand. Usually runs in O(n^2) time. Best case with
#partially sorted sequence.
nums = [5,2,4,6,1,3,9,7,10,8]
print(nums)
print('Sorting...')
<<<<<<< HEAD
#At the start of each iteration of the for loop, the subarray num[1..j-1]
#cons... |
40f018b98eb2e274174c60c63e1170bc66cfc641 | Daegybyte/studyGuide1030 | /finalExam/exam1/trueFalseChecker.py | 140 | 3.875 | 4 | num = [-20,0,7,10,]
for x in range(len(num)):
if (7 < num[x] and num[x] >= -8):
print("true")
else:
print("false")
|
fce1c59d3bf899ef2ffbbdf23e42700f7544d908 | dom-0/python | /ohwell/dictbyval.py | 180 | 3.796875 | 4 | #!/usr/bin/env python
d = {"a": 2, "b": 4, "c": 1}
for i in sorted(d.keys()):
print ("{}\t{}".format(i, d[i]))
for dic in sorted(d.items(), key=lambda x: x[1]):
print(dic)
|
894c3d1ce41ac6e2ec74a14dfa958bcf4fea7aec | dom-0/python | /Munich/.idea/fun.py | 89 | 3.625 | 4 | a = 2
b = 3
a, b = b, a
print (a, b)
a = [1, 2 ,3]
print (a)
c, d, e = a
print(c, d, e) |
7f3ffa59e5e87e724001bbc50181bbf9ba19f4ed | dom-0/python | /oldstuff/dict1.py | 258 | 4.1875 | 4 | #!/usr/bin/env python
first = "first_name"
info = {first: 'Hector', 'second_name': first, 'age': 56}
first_name = "first_name"
print ("The full name of the person is : " + info[first].upper() + " " + info["second_name"].upper() + " !")
print (info.items())
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.