blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
acca1bdf168640ad83c0a5b28ff8782bb26a40e9 | faseehahmed26/Python-Practice | /studentslist.py | 123 | 3.578125 | 4 | l1=[]
no=int(input("Enter number of students:\n"))
for i in range (no):
a=int(input("Enter marks",i))
l1.append(a)
|
a2a5ffd066242090e100d58959ba1500e0919b44 | faseehahmed26/Python-Practice | /starfor.py | 71 | 3.953125 | 4 | num=int(input("enter num"))
for n in range(1,num+1):
print('* '*n)
|
4ac12ebd70ffc8a9b882babe386acf38efc99944 | Devesh0/210-CT-COURSEWORK | /Week3/6_reverse_string.py | 168 | 4.0625 | 4 | def reverse(string):
y = string. split ()
x = y[::-1] # "SLICING" not the reverse function
return " ". join (x)
print (reverse("This is awesome ."))
|
c956e8e31d7e5102e1cbf85f3db0350315613216 | Devesh0/210-CT-COURSEWORK | /Week3/8_vowal_removal.py | 226 | 3.796875 | 4 | def vowel_removal(s):
if (len(s) <= 1): # base case
return s
elif s[0] in "aeiouAEIOU":
return vowel_removal(s[1:])
return s[0] + vowel_removal(s[1:])
print(vowel_removal("beautiful"))
|
809492c6b23f8429aad6cea8724f95df0c4c5727 | chdlkl/python | /PythonScientificCalculation/chap2/ufunc.py | 3,577 | 3.546875 | 4 | import numpy as np
x = np.linspace( 0, 2*np.pi, 10 )
y = np.sin( x ) # ufunc函数产生的结果为数组
z = np.sin( x, out = x ) # 使用out将计算的结果存储在x数组中
# -------------------------------------------------------------------------------
# 比较运算和布尔运算
a = np.array( [1, 2, 3] )
b = np.array( [3, 2, 1] )
print( a < b ) # [ True, False, Flase... |
4c76d5a43999acf107c3d8fe0362251b404ab52d | chdlkl/python | /character/testcharacter.py | 1,329 | 3.953125 | 4 | # 访问字符串中的值
var1 = 'hello world!'
var2 = 'luk'
print ( 'var1[0]: ', var1[0] )
# 这里要注意
# 1. python中的元素下标从0开始,Fortran中默认从1开始
# 2. 引用方式也不一样,python是[],fortran是()
# 3. 引用单个元素时,比如,python是var[1],fortran是var(1:1)
# 字符串更新(替换)
var = 'lkl'
print ( 'before var:', var )
var = var[0] + 'uk'
print ( 'after var', var )
# 字符串运算符
a = ... |
fa3404e643730448011f1f4aa261431f8d2360c4 | chdlkl/python | /function/func1.py | 8,231 | 4.25 | 4 | # 函数规则:
# 函数代码块以def关键词开头,后接函数标识符名称(函数名)和圆括号()
# 任何传入参数和自变量必须放在圆括号中间
# 函数内容以冒号起始,并且缩进
# return [表达式]结束函数。不代表达式的return相当于返回none
# python1
def hello():
print ( " hello, world! " )
hello ( ) # 自定义函数用于输出信息
# python2
import math
def area( r ):
s = math.pi * r * r
return s
print ( " area = ", area(1.0) )
def print_... |
ca27691f8b714bfde6af454a4ccfb6af5064ca1f | diyinqianchang/python | /src/detail/repTest.py | 1,068 | 3.671875 | 4 | #coding:UTF8
'''
Created on 2016��6��1��
@author: Administrator
'''
import re
x = 'HELLO WORLD'
print(re.findall("hello", x,re.IGNORECASE))
print(re.findall("WORLD$", x, re.IGNORECASE))
#有转义字符
print(re.findall(r"\b\w+\b", x))
#sub先创建原变量的拷贝,然后在拷贝中替换字符串,并不会改变变量s的内容
print(re.sub("HELLO", "hi", x, 0, re.IGNO... |
1f949dccd4f245e250636ab296d45b3c69366034 | diyinqianchang/python | /src/class/__init__.py | 1,167 | 3.828125 | 4 | #coding:utf-8
'''
Created on 2016年6月12号
@author: 张国林
'''
class Fruit:
price = 0 #类属性
def __init__(self):
# self.color = 'red' #实例属性
self.__color = 'red'
zone = "China" #局部变量
self.__weight = 120 #私有属性 instance._classname__attribute
de... |
72c796cf6cf5340bd5ba4075be5a494143e0861c | AaryanRS/Odd_-_Even | /OddorEven.py | 246 | 4.09375 | 4 | def oddEven(num) :
if (num % 2 == 0) :
print("Even")
else:
print("Odd")
while True:
num = int(input("Hi welcome to my project, Please enter the number here = "))
oddEven(num)
|
65d56039fe3688d16aeb6737fbcd105df044155a | pranshulrastogi/karumanchi | /doubleLL.py | 2,884 | 4.40625 | 4 | '''
implement double linked list
'''
class Node:
def __init__(self, data):
self.data = data
self.prev = None
self.next = None
class doubleLL:
def __init__(self):
self.head = None
# insertion in double linked list
def insert(self,data,pos=-1):
assert pos >... |
c87e47793e45a54750072e9cd55e5bbc3e5ae806 | pranshulrastogi/karumanchi | /ch3p28.py | 478 | 3.921875 | 4 | # Problem: Display linked list from the last
import singleLL
def reversep(sll):
if sll.head.next == None:
# last node
print(sll.head.data)
else:
p = sll.head
sll.head = sll.head.next
reversep(sll)
print(p.data)
if __name__ == "__main__":
# create a sin... |
d813ec86a78ab66bf1bbf58ca0a5b1d992611892 | maheshganee/python-data | /8shallow copy.py | 1,142 | 4 | 4 | """shallow copy:
the process of copying the memory location from 1 variable to another variable is known as shallow copy
rules of shallow copy:
2 r more variables must share a single memory location
if 1 variable data gets change another data will get change automatically
syntax:
variable 2 = variable 1
shallow co... |
0765b7bc193f7bc799aa0b713b32b9c97ce7b3eb | maheshganee/python-data | /13file operation.py | 2,798 | 4.65625 | 5 | """
file operation:python comes with an inbuilt open method which is used to work with text files
//the text files can operated in three operation modes they are
read
write
append
//open method takes atleast one parameter and atmost two parameters
//first parameter represents the file name along with full path and sec... |
9e2e7029b391be661e4b9ff1f5abbd53aefa4840 | ActionArts/PythonPlay | /sum.py | 333 | 3.703125 | 4 | #Sum all the numbers containing a '9' between 0-50 and 100-150, non-inclusive (meaning, the upper bound of each range is not included)
totalsum = 0
counter = 0
while counter < 150:
if counter < 50 or counter > 99:
if '9' in str(counter):
totalsum = totalsum + counter
counter = counter + 1
print "total sum ... |
1e171d3183670dd0bac6ab179a3b7c13c42f834c | rronakk/python_execises | /day.py | 2,705 | 4.5 | 4 | print "Enter Your birth date in following format : yyyy/mm/dd "
birthDate = raw_input('>')
print" Enter current date in following format : yyyy/mm/dd "
currentDate = raw_input('>')
birth_year, birth_month, birth_day = birthDate.split("/")
current_year, current_month, current_day = currentDate.split("/")
year1 = int(b... |
a81a346e355d82d8132a93843f0da9f38eabb790 | ciankehoe/py-dsa | /sequences_sets_maps/previous_numbers.py | 280 | 3.734375 | 4 | seen = set()
dups = [] #duplicates
num = input().lstrip().strip() # read our input
while num != "-1":
if num not in seen:
seen.add(num)
else:
dups.append(num)
num = input().lstrip().strip()
print("Enter numbers (-1 to end): " + ' '.join(dups) + " ") |
090a6019784c9724f39ee8f99bc4c3ba16c1fab3 | chandudasari1988/Modern-Python-Cookbook-Second-Edition | /Chapter_03/ch03_r05.py | 2,271 | 3.75 | 4 | """Python Cookbook 2nd ed.
Chapter 3, Recipe 5
"""
from math import radians, sin, cos, sqrt, asin
from typing import Callable
MI = 3959
NM = 3440
KM = 6373
def haversine(
lat_1: float, lon_1: float, lat_2: float, lon_2: float, R: float = NM
) -> float:
"""Distance between points.
R is radius, R=MI comp... |
d1bbb4444af9eaf5347174a23450b5d8bf085fcc | raghu1199/Advance_Python | /OOPS/FullCalculator_usingOnly_addtion.py | 727 | 3.9375 | 4 | from utils.addition import Addition
class Calculator:
@classmethod
def add(cls, num1, num2):
return Addition.add(num1, num2)
@classmethod
def subtract(cls,num1,num2):
return cls.add(num1,-num2)
@classmethod
def mutiply(cls,num1,num2):
res=0
for x in range(0,nu... |
c987da5d77b52ff6f6cbcde57f64c53ba72fb3ab | raghu1199/Advance_Python | /Errors_Exeception_Handling/raiseErroe.py | 582 | 4.0625 | 4 | class Car:
def __init__(self,make,model):
self.make=make
self.model=model
def __repr__(self):
return f"<Car {self.make} {self.model}"
class Garage:
def __init__(self):
self.cars=[]
def __len__(self):
return len(self.cars)
def add_car(self,car):
if... |
bd9766b33dc4f0332da60352b0854b3097bcb3ae | raghu1199/Advance_Python | /File_Handling/Basic_Read_Write.py | 205 | 3.6875 | 4 |
user_name=input("Enter ur name:")
my_file=open("data.txt","a")
my_file.write(user_name)
my_file.close()
my_file_r=open("data.txt","r")
file_content=my_file_r.read()
my_file_r.close()
print(file_content) |
f62bebe6614a71a099d59c73bcbc1e8e9836420e | raghu1199/Advance_Python | /Concurrenancy/threads.py | 650 | 3.65625 | 4 | import time
from threading import Thread
def ask_user():
start=time.time()
user_input=input("Enter Your name:")
greet=f"Hello,{user_input}"
print(greet)
print(f"ask_user,{time.time()-start}")
def complex_calc():
start=time.time()
print("Started calculating..")
[x**2 for x ... |
7f5b2c724012122a57dcac79614d21205f272925 | raghu1199/Advance_Python | /OOPS/basic_class.py | 485 | 3.765625 | 4 | class Student:
def __init__(self, name, new_grades):
self.name = name
self.grades = new_grades
def average(self):
return sum(self.grades) / len(self.grades)
st1=Student("RAHUL MC",[60,55,34,21,17])
st2=Student("RAGHU HERO",[96,98,97,90,93])
print(st1.name,st1.grades)
print(st2.name,st2... |
ba131ca609c18ee3cf0d5fb5673dd4b18166df08 | van950105/leetcode | /moveZeroes.py | 537 | 3.609375 | 4 | class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
i=0
length=len(nums)
while i<length:
if nums[i]!=0:
i+=1
else:
j=i
... |
278dcd1b7a8f3807c699b26a813ce54c96b96043 | daxata/assignment_II | /11_replace_last_value_tuple.py | 389 | 3.640625 | 4 | Python 3.4.0 (v3.4.0:04f714765c13, Mar 16 2014, 19:24:06) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> lis1 = [(10,20,40), (40,50,60), (70,80,90)]
>>> lis2 = []
>>> for i in lis1:
t1 = list(i)
t1[-1] = 30
t2 = tuple(t1)
lis2.append(tuple(t2))
... |
f9baac6271366884fbb8caaf201ccb6b4e53e254 | sunilmummadi/Trees-3 | /symmetricTree.py | 1,608 | 4.21875 | 4 | # Leetcode 101. Symmetric Tree
# Time Complexity : O(n) where n is the number of the nodes in the tree
# Space Complexity : O(h) where h is the height of the tree
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Approach: To check for symmetry of a tree, check if ... |
bbb9a92005149b0c398cc11b08b64590d238abed | jenniferlim07/swap-meet | /swap_meet/vendor.py | 2,469 | 3.546875 | 4 | class Vendor:
def __init__(self, inventory=None):
if inventory is None:
inventory = []
self.inventory = inventory
def add(self, item):
self.inventory.append(item)
return item
def remove(self, item):
if item in self.inventory:
self.inven... |
5eb4e40394794a720e2e79a25a0a778bb0bcf23a | ERNESTO553/deberes | /def multiply.py | 114 | 3.59375 | 4 | def multiply(a, b):
return a*b
print(multiply(3,4))
def multiply (a,b):
return
print(multiply(3,4))
|
371d2c464ecef440e0f944b4e7f986d58bc044bf | ERNESTO553/deberes | /año bisiesto.py | 181 | 3.71875 | 4 | a=int(input("ingresa año\n"))
if(a % 4 == 0 and a % 100 != 0 or a % 400 == 0):
print("El año "+str(a)+" Si es bisiesto ")
else:
print("El año "+str(a)+" No es bisiesto ")
|
a4528243ef5de093ed02bd4299d30d69724d390c | ERNESTO553/deberes | /De 3 numeros devuelve el mayor.py | 355 | 4.0625 | 4 | numero_1= int(input("ingresar 1er numero?"))
numero_2= int(input("ingresar 2do numero?"))
numero_3= int(input("ingresar 3er numero?"))
if numero_1>numero_2 and numero_1>numero_3:
print (str(numero_1))
if numero_2>numero_1 and numero_2>numero_3:
print (str(numero_2))
if numero_3>numero_1 and numero_3>nume... |
49b1e6cf1f9b9de78fff616960864dfac3e878fe | elzup/algo-py | /dp/lcs.py | 505 | 3.5625 | 4 | def memoize(f):
cache = {}
def helper(x, y):
if x not in cache:
cache[(x, y)] = f(x, y)
return cache[(x, y)]
return helper
# 最長共通部分列
@memoize
def lcs(a, b):
if len(a) == 0 or len(b) == 0:
return 0
t = max(lcs(a, b[:-1]), lcs(a[:-1], b))
if a[-1] == b[-1]:
... |
567e790552c1ba9c1029d37d8dee7c5b0a2d6946 | jspaulino/UriQuest | /q1009.py | 811 | 3.65625 | 4 | # -*- coding: utf-8 -*-
'''
Faça um programa que leia o nome de um vendedor,
o seu salário fixo e o total de vendas efetuadas
por ele no mês (em dinheiro). Sabendo que este vendedor
ganha 15% de comissão sobre suas vendas efetuadas,
informar o total a receber no final do mês,
com duas casas decimais.
Entrada
O a... |
0d45465a22f4bd7ec5400bac785f785e36eb0dc6 | fordmay/ghosts_attack_python | /ball.py | 1,294 | 3.765625 | 4 | import pygame
from random import randint
from pygame.sprite import Sprite
class Ball(Sprite):
"""A class to manage ball fired from the wizard"""
def __init__(self, ga_game):
"""Create a ball object at the wizard's current position."""
super().__init__()
self.screen = ga_game.screen
... |
2ad249f9828ba11b7edd279358a9adb9408dae05 | MrEricL/daily-code-problem | /1.py | 527 | 3.953125 | 4 |
'''
Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
Bonus: Can you do this in one pass?
'''
'''
Explanation:
Store the complement in a set and check at O(1) time
'''
def fxn(l, k):
... |
a56252eb525ccec1d06f2e4a679758d5ed1518ce | Granc3k/PONG | /Project/project_1v1.py | 4,938 | 3.75 | 4 | """
File: project.py
-----------------
This program is an empty program for your final project. Update this comment
with a summary of your program!
"""
from graphics import Canvas
import time
import random
CANVAS_WIDTH = 1280
CANVAS_HEIGHT = 720
board_width = 100
board_height = 50
offset_paddle = 100
PADDLE_WIDTH = ... |
eff2c5d6e97d961bb24651bc688a1164310018fe | TobiObeck/CogSci-WS2020-ANNs-in-Tensorflow | /homework02/code/other/Homework2_kristina.py | 4,043 | 4.03125 | 4 | import numpy as np
import matplotlib.pyplot as plt
x = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
# targets
t_and = np.array([0, 0, 0, 1])
t_or = np.array([0, 1, 1, 1])
t_nand = np.array([1, 1, 1, 0])
t_nor = np.array([1, 0, 0, 0])
t_xor = np.array([0, 1, 1, 0])
# activation function
def sigmoid(x):
return 1 / ... |
cb57bdc71c8f61001c7cad4e5279bd389e3adf56 | jorge-armando-navarro-flores/coffee_machine | /main.py | 1,905 | 3.890625 | 4 | from machine_data import MENU, resources, coins
machine_money = 0
def print_report():
print(f"Water: {resources['water']}ml")
print(f"Milk: {resources['milk']}ml")
print(f"Coffee: {resources['coffee']}g")
print(f"Money: ${machine_money}")
def resources_sufficient(coffee_ingredients):
for key in... |
5c8bc5c3e5fbbcaac259163ee7248e97a0d5f0c2 | sherke/hacktoberfest | /2021/Python/BestPractice/enumerate.py | 196 | 3.625 | 4 | input_list = [1, 2, 3, 4, 5, 6, 7]
# bad practice
for i in range(len(input_list)):
print(i, input_list[i])
# best practice
for index, value in enumerate(input_list):
print(index, value)
|
e5ddcc0f0025db9009aa123adf1e33a5882a8756 | dltech-xyz/Alg_Py_Xiangjie | /.history/第2章/2-3/tiqu_20171113223515.py | 507 | 3.640625 | 4 | prices = {'ASP.NET': 49.9, 'Python': 69.9, 'Java': 59.9, 'C语言': 45.9, 'PHP': 79.9}
p1 = {key: value for key, value in prices.items() if value > 50}
print(p1)
tech_names = {'Python', 'Java', 'C语言'}
p2 = {key: value for key, value in prices.items() if key in tech_names}
print(p2)
p3 = dict((key, value) for key, value i... |
939f4eaebaa114dc2a4df77a2654c4b679b0e38b | dltech-xyz/Alg_Py_Xiangjie | /.history/第3章/di_20200528232637.py | 505 | 3.53125 | 4 | #!/usr/bin/env python
# coding=utf-8
'''
@version:
@Author: steven
@Date: 2020-05-27 22:20:22
@LastEditors: steven
@LastEditTime: 2020-05-28 23:26:37
@Description:
'''
fib_table = {} # memoization table to store previous terms
def fib_num(n):
if (n <= 1):
return n
if n not in fib_table:
fib_ta... |
7a619c0a23673ae7c5bf280059d9bff86419ee12 | dltech-xyz/Alg_Py_Xiangjie | /.history/第2章/2-1/chuantong_20171112223825.py | 126 | 3.75 | 4 | squares = []
for x in range(10):
squares.append(x**2)
print(squares)
squares1 = [x**2 for x in range(10)]
print(squares1) |
60e62b673f4abc12162d2560d4dd24f820214917 | dltech-xyz/Alg_Py_Xiangjie | /.history/第3章/qi_20200607165646.py | 1,351 | 3.75 | 4 | #!/usr/bin/env python
# coding=utf-8
'''
@version:
@Author: steven
@Date: 2020-05-27 22:20:22
@LastEditors: steven
@LastEditTime: 2020-06-07 16:56:46
@Description:分治算法,判断某元素是否再列表里
'''
# 子问题算法(子问题规模为 1)
def is_in_list(init_list, el):
return [False, True][init_list[0] == el]
# 不过在Python3.x 中,终于把这个两变量变成了关键字,而不再是内建... |
51315060e1221b7266f9b78e7f74a40405b4b1e9 | dltech-xyz/Alg_Py_Xiangjie | /.history/第2章/2-3/del_20171113163945.py | 185 | 3.71875 | 4 | #创建字典“dict”
dict = {'Name': 'Toppr', 'Age': 7, 'Class': 'First'}
del dict['Name'] #删除键 'Name'
print (dict) #显示字典“dict”中的元素
|
d908a2daa4ce12ec185d64cd232d1475598582a2 | dltech-xyz/Alg_Py_Xiangjie | /.history/第2章/2-2/neizhi_20171113104609.py | 561 | 4.375 | 4 | car = ['奥迪', '宝马', '奔驰', '雷克萨斯'] #创建列表car
print(len(car)) #输出列表car的长度
tuple2 = ('5', '4', '8') #创建元组tuple2
print(max(tuple2)) #显示元组tuple2中元素的最大值
tuple3 = ('5', '4', '8') #创建元组tuple3
print(min(tuple3)) #显示元组tuple3中元素的最小值
list1= ['Google', 'Taobao', 'Toppr', 'Baidu'] #创建列表list1
... |
6c8e13d208beafae5b669f07b0dadd18d1c6a2b4 | dltech-xyz/Alg_Py_Xiangjie | /第5章/huo.py | 1,953 | 3.921875 | 4 | class Node(object):
def __init__(self, value, left=None, right=None):
self.value = value
self.left = None
self.right = None
class Huffman(object):
def __init__(self, items=[]):
while len(items)!=1:
a, b = items[0], items[1]
newvalue = a.value + b.value
... |
4e1bc4ed86486ee94c63f439d96d7f663df5587c | mcfarland422/python101 | /loops.py | 277 | 4.21875 | 4 | print "Loops file"
# A for loop expects a starting point, and an ending point.
# The ending poin (in range) is non-inclusive, meaning, it will stop when it gets there
# i (below) is going to be the number of the loop it's on
for i in range(1,10):
if (i == 5):
print
|
bea97dff439a3f97b51df2e79eea4e359b20d826 | BecsMarconi/Prog2 | /Exercícios/verifica_entrada.py | 374 | 3.765625 | 4 | def lerEntrada(mensagem=" Insira um número: "):
n = int(input(mensagem))
print("Valor digitado: ", n)
return n
def tupla0 (numeros="Digite dois números separdos por espaços: "):
nu = str(input(numeros))
li = []
li.extend(nu)
print(li)
print("Valores digitados -> primeiro: {} ; segundo:... |
17ba7db92d8e3227191882f02073e45e39ab274a | Hobit2002/HigherLower | /RunMe.py | 4,219 | 3.59375 | 4 | import random
print("Welcome in Higher Lower Casiono. The higher will be your risk, the lower you'll win!")
#Prepare deck
GameDeck=[]
Table=[]
DiscardDeck=[]
for Symbol in ['♠','♥','♦','♣']:
for relValue,imageValue in enumerate(['2','3','4','5','6','7','8','9','10','J','Q','K','A']):
GameDeck.append({'image... |
8b9add441cc947f5b12a1b5377df16b0fb31edd8 | krypten/competitive-coding | /competitive-coding/spoj/iitwpcj.py | 409 | 3.734375 | 4 | def gcd ( a, b) :
if a%b == 0:
return b
return gcd(b, a%b)
def lcm( a, b):
d = gcd(a,b)
l = a*b/d;
x = l/a
y = l/b
return l,x,y
t = int(raw_input())
while (t):
t -= 1
string = []
string = str(raw_input()).split();
tmp1 = string[0]
tmp2 = string[1]
n = len(tmp1)
m = len(tmp2)
lc,x,y = lcm( n , m)
... |
843c9767375d84fbbf1f743df50952ddf23afee1 | krypten/competitive-coding | /competitive-coding/spoj/prismsa.py | 152 | 3.5625 | 4 | t = int(input())
while(t):
t -= 1
n = float(input())
#print ((18*n)/((4.0*n)**(1/3)*(3*0.5)))
print (3*(3**0.5)*((4*n)**(2/3))/2)
|
c73a278354aca1ef6b1a7daaa5c64d8722397228 | ty1996/python | /hw01/main.py | 592 | 3.921875 | 4 | def binary_search(find, list1) :
low = 0
high = len(list1)
while low <= high :
mid = (low + high) / 2
if list1[mid] == find :
return mid
elif list1[mid] > find :
high = mid -1
else :
low = mid + 1
return -1
list1 = [1,2,3,7,8,9,10,5]
list1.sort()
print "原有序列表为:",lis... |
8747da31349ada5ed58c399d9f6e4a9b6e5b42c5 | bleaz01/base-de-python | /gessing_game.py | 375 | 3.8125 | 4 | import random
print("tapé le numero\n")
guess = int(input())
nb_secret = random.randint(1,100)
while guess != nb_secret:
if guess < nb_secret:
print("ton nombre est inferieur")
else:
print("ton nombre est trop haute")
print("recommance casse pas les couille")
guess = int(input())
... |
4df919c2b292cf09bf210ea8337023dea1c63bbf | Rosswell/CS_Exercises | /linked_list_manipulation.py | 2,673 | 4.15625 | 4 | '''Prompt:
You have simple linked list that specifies paths through a graph. For example; [(node1, node2), (node2, node3)]
node 1 connects to node 2 and node 2 connects to node 3. Write a program that traverses the list and breaks any cycles.
So if node 1 links to both node 2 and node 2374, one link should be broken a... |
8e38385ce7acc7ff104fbff45c3d90dc274a897f | psg25/pachaqtecH7 | /Grupo1/salon.py | 6,032 | 3.515625 | 4 | from connection.conn import Connection
import menu
Connection = Connection('mongodb+srv://paola:pachaqtec@pachaqtec.sdvq7.mongodb.net/test', 'pachacteq')
lstSalon=[]
class salones:
collection = 'salones'
def __init__(self, nombreSalon, idAlumno, idProfesor):
self.nombreSalon = nombreSalon
s... |
ebd55dd4b65a1701b6fe57c3279285bab3ff165c | soumyap00/SID_pythonDev | /prgm9.py | 317 | 4.0625 | 4 | A = []
n = int(input("Enter number of elements in the list : "))
print("Enter elements:")
for i in range(0, n):
elm = int(input())
A.append(elm)
print("The entered list is: \n",A)
k =int(input("Enter which smallest number you want to see:"))
A.sort()
print(k,"'th smallest element is",A[k-1])
|
3cdab5157490d20386f631419f37239e9ba084b4 | psglinux/MS | /cs-265/assignment-2/assignment2.py | 1,104 | 3.828125 | 4 | #!/usr/bin/env python
def find_prime_factor(n):
for i in xrange(1,n+1,1):
d = n/i
r = n%i
if r == 0:
print "i = ", i, n,"/i = ", n/i," ", n,"%i = ", n%i
def find_one_e_or_d(tot, e):
i = 1
while 1:
p = (i*e)%tot
if p == 1:
print "e*d =", i*e, "e ... |
41585c6dca2b0c40fbdd86fecbedecfa663e306a | Shadow-Arc/Eleusis | /hex-to-dec.py | 1,119 | 4.25 | 4 | #!/usr/bin/python
#TSAlvey, 30/09/2019
#This program will take one or two base 16 hexadecimal values, show the decimal
#strings and display summations of subtraction, addition and XOR.
# initializing string
test_string1 = input("Enter a base 16 Hexadecimal:")
test_string2 = input("Enter additional Hexadecimals, else... |
50d3d8fe9a65b183a05d23919c255b71378c7af5 | alejandrox1/CS | /documentation/sphinx/intro/triangle-project/trianglelib/shape.py | 2,095 | 4.6875 | 5 | """Use the triangle class to represent triangles."""
from math import sqrt
class Triangle(object):
"""A triangle is a three-sided polygon."""
def __init__(self, a, b, c):
"""Create a triangle with sides of lengths `a`, `b`, and `c`.
Raises `ValueError` if the three length values provided can... |
c036a96d5aa70c49899f7fb514f8a5bf760880a9 | SValchev/AoC2020 | /day3/day3.py | 1,686 | 3.59375 | 4 | from pathlib import Path
class Position:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def change(self, x, y):
self.x += x
self.y += y
class MoveStrategy:
def __init__(self, move_x, move_y):
self.position = Position()
self.move_x = move_x
self.... |
5e4c5593c59e8218630172dd9690da00c7d8fc1c | CostaNathan/ProjectsFCC | /Python 101/While and for loops.py | 1,090 | 4.46875 | 4 | ## while specify a condition that will be run repeatedly until the false condition
## while loops always checks the condition prior to running the loop
i = 1
while i <= 10:
print(i)
i += 1
print("Done with loop")
## for variable 'in' collection to look over:
## the defined variable will change each iteratio... |
959aae8e60bcc42ea90447dc296262c791e18d8c | CostaNathan/ProjectsFCC | /Python 101/Try & Except.py | 298 | 4.21875 | 4 | ## try/except blocks are used to respond to the user something when an error occur
## best practice to use except with specific errors
try:
number = int(input("Enter a number: "))
print(number)
except ZeroDivisionError as err:
print(err)
except ValueError:
input("Invalid input") |
fd9bf5095ff6f4c8e34c8dbbe77f2dc7855de014 | Nguyen-Van-Huy/huynguyenydd | /8.6.py | 903 | 3.5 | 4 | from tkinter import *
def NewFile():
print("New File!")
def About():
print("This is a simple example of a menu")
def OpenFile():
print("Open File")
def Exit():
print("Exit")
def Instext():
print("Instext")
def Inspic():
print("Inspic")
root = Tk()
menu = Menu(root)
root.config(m... |
a73adef1e945ae833b52fbb37c4d35b262ae527a | Nguyen-Van-Huy/huynguyenydd | /8.5.py | 599 | 4.03125 | 4 | import tkinter as tk
root = tk.Tk()
v = tk.Intvar()
v.set(1)
languages = [
("Python",1),
("Perl",2),
("Java",3),
("c++",4),
("c",5)
]
def ShowChoice():
print(v.get())
tk.Label(root,text="""Choose your favourite programming language:""",
justify = tk.LEEF,
padx = 20).... |
11810329106c9a26112fa4b5875c3cf1e1b87ae9 | dbertho/covid-deaths-graph | /covid_deaths_graph_fra.py | 10,547 | 3.59375 | 4 | import urllib.request
from urllib.error import URLError, HTTPError
import json
import random
from PIL import Image, ImageDraw, ImageFont
import time
from sys import exit
start_time = time.time()
font_regular = ImageFont.truetype("arial.ttf", size=10)
font_small = ImageFont.truetype("arial.ttf", size=8)
def calc_mov... |
346c94b4c65d6bfc9fa2fce77954cc3ac3cf431e | JokerQyou/algorithms | /sort/_base.py | 446 | 3.640625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
class SortBase(object):
@staticmethod
def sort(l):
raise NotImplementedError('Should be implemented in subclass')
def is_sorted(l, descending=False):
'''Check whether a sequence is sorted'''
if descending:
... |
a023af20b12afd80ac5d9afe224ee7c7643fa245 | dkumor/remotecontrol | /data/parser.py | 541 | 3.578125 | 4 | from pylab import *
def getint():
a=raw_input()
isint=False
while (not isint):
a=raw_input()
try:
a=int(a)
isint=True
except:
pass
return a
#First read in data:
#First line is the startnum
i=getint()
num=800
x=zeros(2*num)
y=zeros(2*num)
total=... |
13056eb828a21ea37dc89cbd36de80d75b7bbc7e | Royz2123/Deep-Learning | /HW1/main.py | 6,148 | 3.875 | 4 | '''
Some 1 and 2 layer networks written using Python2.7 and Tensorflow
This example is using the MNIST database of handwritten digits
Authors: Roy Zohar and Roy Mezan
'''
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# MNIST data
mnist = input_data.read_data_sets("/tmp/data/", one... |
7f79f20efb60630ef7967457d761f11c40c92700 | DerekLW6/python_apps | /01_the_basics/first_app_v2.py | 430 | 3.703125 | 4 | # text_list = []
# modified_text_list = []
# #interrogatives = ('how', 'what', 'why')
# while True:
# user_input = input("Say something: ")
# if user_input == '\end':
# for element in text_list:
# x = element.capitalize() + "."
# modified_text_list.append(x)
# break
# ... |
c260bdf51bc8b68c50649f6e0e860c95513410da | fernandorssa/CeV_Python_Exercises | /Desafio 10.py | 124 | 3.8125 | 4 | n1 = float(input('Quanto você tem na carteira? R$ '))
print ('Valor convertido em Dólares: USD {:.2f}'.format(n1/3.27))
|
1af27f8fc94bb9cb268b5cd713ba73ecfcf961e9 | fernandorssa/CeV_Python_Exercises | /Desafio 82.py | 619 | 3.84375 | 4 | listaGeral = []
listaPar = []
listaImpar = []
while True:
n = int(input('Digite um número: ')) # listaGeral.append(int(input('Digite: ')))
listaGeral.append(n)
continuar = int(input('Digite 1 para continuar e 2 para sair: '))
if continuar == 2:
break
for analise in listaGeral:
if analise ... |
808eb356948dd8e2c20a7805246c50aa1d663730 | fernandorssa/CeV_Python_Exercises | /Desafio 46.py | 560 | 3.640625 | 4 | from time import sleep
print('')
print('Vai começar a contagem regressiva!!!!!')
print('')
sleep(1)
cont = 10
for tempo in range(10, -1, -1):
if cont == 0:
print('0!!!!!!!!!!!!!! AEEEEEEEEEE!!!!!!!!!!! BUUUUUUUM TCHAMMMMMMMMMMMM CATAPUMMMMMMM!!!!!')
else:
print(cont)
cont -= 1
... |
3f6098a38ca9db8e5d82696d9b9589ce68e034de | fernandorssa/CeV_Python_Exercises | /Desafio 73.py | 883 | 3.96875 | 4 | times = ('Palmeiras', 'Flamengo', 'Internacional', 'Grêmio', 'São Paulo', 'Atlético', 'Atlético - PR', 'Cruzeiro',
'Botafogo', 'Santos', 'Bahia', 'Corinthians', 'Ceará', 'Fluminense', 'Vasco', 'Chapecoense', 'América',
'Sport', 'Vitória', 'Paraná')
print('')
print('Classificação dos 5 primeiros coloc... |
c7e3a7c69635adc1fcf105d33b9cc137065f35fe | fernandorssa/CeV_Python_Exercises | /Desafio 101.py | 768 | 3.75 | 4 | # Minha solução
def voto1(x):
if 2019 - x <= 16:
print(f'Com {2019 - x} anos: Não vota.')
elif 2019 - x >= 16 and 2019 - x < 65:
print(f'Com {2019 - x} anos: Voto obrigatório.')
else:
print(f'Com {2019 - x} anos: Voto opcional.')
nascimento = int(input('Em que ano você nasceu? '))
... |
ae0c54650b8f0b0be18e527f1d50a841a20ac367 | fernandorssa/CeV_Python_Exercises | /Desafio 28.py | 883 | 3.953125 | 4 | import random
from time import sleep
lista = [1, 2, 3, 4, 5]
n = random.choice(lista)
print('')
chute = int(input('Olá, eu pensei em um número de 1 a 5. Qual é o número? '))
print('PENSANDO...')
sleep(3)
if chute == n:
print('PARABÉNS! Você acertou!')
else:
if chute <= 5:
print('ERROU! Eu pe... |
82b449bdab3b9fd097d8e83c6506b1b80e096799 | fernandorssa/CeV_Python_Exercises | /Desafio 12.py | 166 | 3.53125 | 4 | n1 = float(input('Preço do produto: R$ '))
# n1 = 100
# x = 5
# Resultado é igual N1 - 5%
print('O valor com desconto é: R$ {:.2f}'.format(n1-(n1*5)/100))
|
a55172d774791aef6d96d4059e423f6d6e659870 | fernandorssa/CeV_Python_Exercises | /Desafio 29.py | 322 | 3.75 | 4 | v = float(input('Velocidade: '))
if v <= 80:
print('Você está respeitando os limites de velocidade.')
else:
print('Você passou no radar a {} km/h e excedeu o limite de velocidade.'.format(v))
print('MULTADO no valor de R$ {:.2f}'.format((v-80)*7))
print('Tenha um bom dia! Dirija com segurança!')
|
97e9ef88bf14bd8990b1e102b24be1d1c062a512 | fernandorssa/CeV_Python_Exercises | /Desafio 94.py | 1,993 | 3.734375 | 4 | n = int(input('Quantas pessoas: '))
dict = {}
acima_da_media = {}
mulheres = []
cont = soma = 0
for i in range(n):
nome = str(input('Digite um nome: '))
sexo = str(input('Digite o sexo (m/f): '))
idade = int(input('Digite a idade: '))
if sexo == 'f':
mulheres.append(nome)
soma += idade... |
67039f2ee14bfd5044297365b8d6d5a380b068e0 | fernandorssa/CeV_Python_Exercises | /Desafio 14.py | 223 | 3.96875 | 4 | a = float(input('Digite a temperatura em °C: '))
print('A temperatura de {} corresponde à {} °F!'.format(a, 32 + (a * 1.8)))
print('A temperatura de {} corresponde à {} °F! [Versão 2]'.format(a, ((9 * a) / 5) + 32)) |
1a4bc19b9deb798a2b3e18fabb62b53babd7e101 | fernandorssa/CeV_Python_Exercises | /Desafio 63.py | 1,077 | 4.15625 | 4 | '''# Pede quantos termos da sequência Fibonacci
n = int(input('Digite quantos termos da sequência: '))
# O contador foi definido como 4 pois n0, n1 e n2 não entram no WHILE. Dessa forma, o programa roda 3 vezes a menos
cont = 4
n1 = n2 = 1
# Se o usuário pede 5 termos, o cont vai rodar 2 vezes, somado ao n0, n1 e n2: ... |
c70e08596bca769dd772cb989ad529f4fc9e3a01 | ilyakh/atsp | /atsp/encoder.py | 1,186 | 3.546875 | 4 | #!/usr/bin/env python2.7
# -*- coding: utf8 -*-
class Encoder:
pass
class LetterEncoder(Encoder):
"""
Maps chromosomes to the symbols from the ASCII table
with corresponding limitations, beginning with the letter 'A'
"""
def __init__( self, ALL_GENES ):
self.ALL_GENES = ALL_GENES
... |
df3955f45591745ac7c20b87d71d01a16f774cf1 | OlivierParpaillon/Contest | /code_and_algo/Xmas.py | 1,504 | 4.21875 | 4 | # -*- coding:utf-8 -*
"""
Contest project 1 : Christmas Tree part.1
Olivier PARPAILLON
Iliass RAMI
17/12/2020
python 3.7.7
"""
# Python program to generate branch christmas tree. We split the tree in 3 branches.
# We generate the first branch of the christmas tree : branch1.
# We will use the same... |
226b39a7fc1fa454eb949ba25471c308d7fc22e0 | frankipod/leetcode | /mergeTwoLists.py | 2,138 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Apr 07 14:58:34 2016
@author: yaoxia
"""
import linklst as ll
#Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def mergeTwoLists(self, l1, l2):
... |
118115215f5fbd91d7e85287bcc46d8c787e3f18 | liviaerxin/zipline | /dual_moving_average.py | 3,869 | 3.515625 | 4 | #dual_moving_average.py
#!/usr/bin/env python
#
# Copyright 2014 Quantopian, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless... |
d5843f3d76d55f5050dfe17e997b81ef5fbed5f4 | macs-h/326_pair | /etude06/test2.py | 954 | 4 | 4 | ''' Mersenne primes and perfect numbers '''
def primes(n):
""" Return a list of primes < n """
# From http://stackoverflow.com/a/3035188/4014959
sieve = [True] * (n//2)
for i in range(3, int(n**0.5) + 1, 2):
if sieve[i//2]:
sieve[i*i//2::i] = [False] * ((n - i*i - 1) // (2*i) + 1)
... |
20e1417f2f3199475381bf8fdefea37f2a68146c | macs-h/326_pair | /etude06/test.py | 1,825 | 4.03125 | 4 | def primes(known_primes=[7, 11, 13, 17, 19, 23, 29]):
"""
Generate every prime number in ascending order
"""
# 2, 3, 5 wheel
yield from (2, 3, 5)
yield from known_primes
# The first time the generator runs, known_primes
# contains all primes such that 5 < p < 2 * 3 * 5
# After eac... |
23bd8f9abc8622a7fba3ec85097241eacd9f3713 | DLLJ0711/friday_assignments | /fizz_buzz.py | 1,486 | 4.21875 | 4 | # Small: add_func(1, 2) --> outputs: __
# More Complex: add_func(500, 999) --> outputs: __
# Edge Cases: add_func() or add_func(null) or add_func(undefined) --> outputs: ___
# Take a user's input for a number, and then print out all of the numbers from 1 to that number.
#startFrom = int(input('Start From (... |
c41bbc8a0bf4e38e2c4a31459e26a90f6de905fb | aniruddh-acharya/Krypto | /vign.py | 895 | 3.953125 | 4 |
#Dont run this. DONT.
def key(string, key):
s = ""; i = 0
while(len(s) != len(string)):
s += key[i%len(key)]
i+=1
return s
#Just run this for cipher.
def encrypt(string, key1):
string = string.upper()
key1 = key1.upper()
key_ = key(string,key1)
cipher = ""
for i in ran... |
47f2fb1ed3fcddd40cd542a13adba1cf47addd37 | Rahul91/python | /git_gui.py | 2,298 | 3.578125 | 4 | #!/usr/bin/python2.7
import sys
import string
import base64
from Tkinter import Tk
from tkFileDialog import askopenfilename
from githubpy import github
from bs4 import BeautifulSoup
import urllib2
print "For using this app, you need to have Github auth token, please go through the link for more details:\nhttps://help... |
27908f6c8668a493e416fc1857ac8fa49e7bb255 | s3rvac/talks | /2017-03-07-Introduction-to-Python/examples/22-point.py | 353 | 4.25 | 4 | from math import sqrt
class Point:
"""Representation of a point in 2D space."""
def __init__(self, x, y):
self.x = x
self.y = y
def distance(self, other):
return sqrt((other.x - self.x) ** 2 +
(other.y - self.y) ** 2)
a = Point(1, 2)
b = Point(3, 4)
print(a.di... |
43b7db090b104f95554ae7079b0c28379a3c6c39 | s3rvac/talks | /2017-03-07-Introduction-to-Python/demos/emails.py | 331 | 3.5 | 4 | # Note: This script is just an illustration. It contains a very simple solution
# to the problem, which is far from perfect.
import sys
import re
emails = []
with open(sys.argv[1], 'r') as f:
for line in f:
for email in re.findall(r'[\w.-]+@[\w.-]+', line):
emails.append(email.rstrip('.'))
pri... |
b2aa6c8e73150c89538f50cbe8e848735c28227b | s3rvac/talks | /2020-03-02-Introduction-to-Python/examples/23-properties.py | 379 | 3.734375 | 4 | class Person:
def __init__(self, name, age):
self.name = name
self.age = age
@property
def age(self):
return self._age
@age.setter
def age(self, new_age):
if new_age <= 0:
raise ValueError('age has to be positive')
self._age = new_age
p = Perso... |
ebb63bb53f8b9ed0e1156bbc0cb6339d72a22f35 | s3rvac/talks | /2020-03-02-Introduction-to-Python/examples/23-first-class.py | 504 | 3.859375 | 4 | class Point:
...
# Python classes are first-class objects. For example, you can assign them to
# variables:
P = Point
print(P()) # <__main__.Point object at 0x7fc1f458c400>
# Pass them to other functions:
def create(cls):
return cls()
p = create(Point)
print(p) # <__main__.Point object at 0x7fc6b516d4a8>
# ... |
7baaca13abcd7fc98fd5d9b78de0bc62557f4b83 | s3rvac/talks | /2020-03-26-Python-Object-Model/examples/dynamic-layout.py | 666 | 4.34375 | 4 | # Object in Python do not have a fixed layout.
class X:
def __init__(self, a):
self.a = a
x = X(1)
print(x.a) # 1
# For example, we can add new attributes to objects:
x.b = 5
print(x.b) # 5
# Or even new methods into a class:
X.foo = lambda self: 10
print(x.foo()) # 10
# Or even changing base classes d... |
04e0458356117f0c0028d0e158edf86e528f43b3 | s3rvac/talks | /2021-03-08-Introduction-to-Python/examples/31-arguments.py | 217 | 3.59375 | 4 | def foo(x=[]):
x.append(4)
return x
print(foo([1, 2, 3])) # [1, 2, 3, 4]
print(foo()) # [4]
print(foo()) # [4, 4]
# https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments
|
a0178beb9995c302dc3ebc460b4174995f240f26 | s3rvac/talks | /2017-03-07-Introduction-to-Python/examples/23-variables.py | 209 | 3.8125 | 4 | class A:
a = 1
def __init__(self, b):
self.b = b
x = A(1)
y = A(1)
print(x.a, x.b, y.a, y.b) # 1 1 1 1
x.b = 2
print(x.a, x.b, y.a, y.b) # 1 2 1 1
A.a = 3
print(x.a, x.b, y.a, y.b) # 3 2 3 1
|
16be02fd8167d8dfc0c82f70c03a94eaf36db41c | s3rvac/talks | /2020-03-26-Python-Object-Model/examples/methods-vs-functions.py | 328 | 3.78125 | 4 | # Methods vs functions.
class X:
def __init__(self, x):
self.x = x
def add(self, other):
return self.x + other.x
a = X(1)
b = X(2)
print(a.add(b)) # 3
print(X.add(a, b)) # 3
print(X.add) # <function X.add at 0x7f83bb046040>
print(a.add) # <bound method X.add of <__main__.X object at 0x7fa9414... |
ea5836406ee848f6fde86e7eda077e6795a91c7d | flyerooo/learnpython27 | /qiwsirPython/ex1-8.py | 1,089 | 3.53125 | 4 | #!/usr/bin/env python
#coding:utf-8
#Created by Jeff on 2016/3/3 11:12
# 8、获取当前日期,并计算当前日期距离1998年5月1日由多少天、多少周(取整)、多少月(取整)、几个季度(取整)、几年(取整)。
from datetime import date
def main():
#获取当前日期
now = date.today()
d1 = date(1998, 5, 1)
#间隔天数
days_diff = (now - d1).days
#间隔星期数
weeks_diff = days_diff ... |
2bb704c44a69dac025d2d18312b9064011bf0852 | flyerooo/learnpython27 | /qiwsirPython/ex33.py | 1,046 | 4.03125 | 4 | #!/usr/bin/env python
#coding:utf-8
#Created by Jeff on 2016/3/20 9:02
'''
33、回文(palindrome)是正读或者反读都相同的单词或但与,忽略空格和字母大小写。例如,下面的示例都是回文:
warts n straw
radar
Able was I ere I saw Elba
xyzczyx
编写一个程序,判断输入的字符串是否是回文。
'''
def toLetters(string):
'''remove non letter character '''
letters = ''
for c in string:
... |
e7b44b5c6b2a9490385743f5a4b54aca28ff4728 | flyerooo/learnpython27 | /qiwsirPython/ex22.py | 1,414 | 3.546875 | 4 | #!/usr/bin/env python
#coding:utf-8
#Created by Jeff on 2016/3/13 22:58
# 22、完全数,是对具有某种特征的整数的称呼。维基百科中,对完全数有非常准确的定义和解释。如下:
# 完全数,又稱完美數或完備數,是一些特殊的自然数:它所有的真因子(即除了自身以外的约数)的和,恰好等於它本身,完全数不可能是楔形數。
# 例如:第一个完全数是6,它有约数1、2、3、6,除去它本身6外,其余3个数相加,1+2+3=6,恰好等於本身。第二个完全数是28,它有约数1、2、4、7、14、28,除去它本身28外,其余5个数相加,1+2+4+7+14=28,也恰好等於本身。后面的数是... |
42b39efbe438ae62a818b8487aedeb5d71d4cf58 | lafleur82/python | /Final/do_math.py | 1,022 | 4.3125 | 4 | import random
def do_math():
"""Using the random module, create a program that, first, generates two positive one-digit numbers and then displays
a question to the user incorporating those numbers, e.g. “What is the sum of x and y?”. Ensure your program conducts
error-checking on the answer and notifies ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.