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
21f141bbd269f85b302c1950cc0f2c8705f97854
tejasgondaliya5/advance-python-for-me
/class_variable.py
615
4.125
4
class Selfdetail: fname = "tejas" # this is class variable def __init__(self): self.lname = "Gondaliya" def printdetail(self): print("name is :", obj.fname, self.lname) # access class variable without decorator @classmethod # access class va...
07013de3f14615a03d737d1724e8207690e95be5
tejasgondaliya5/advance-python-for-me
/moduleprog/First.py
347
3.71875
4
class Myclass: def name(self): print( "this is first module Myclass method" ) class Myschool: def show(self): print( "thid is First module Myschool show method" ) # ..... After this line code is used 'module_oop2' program ....... a = "First Module" def name(): print("name ...
1926c4bba2ff690719692e1f11fbaeeed2857548
tejasgondaliya5/advance-python-for-me
/Files/opening_File.py
487
3.640625
4
''' - open :- If we want to use a file or its data, first we have to open it. - Syntax:- open('filename', mode='r', buffrering, encoding=None,errors=None, newline=None, closefd=True, opener=None) - EX:- f1 = open('student.txt', mode='w,r,rb,a') encoding = None or uft-8 ''' f = open('student.tx...
aa15aaab98490ba56c8e5c4862bb52056175185e
tejasgondaliya5/advance-python-for-me
/Thread/Thread_Syncronization_solve_racecondition.py
1,802
3.625
4
''' a) Lock b) RLock c) Semaphore --> a) Locks:- 1) acquire() :- acquire() jya lagavi e tya Lock gali jay and jay sudhi release na karo tya sudhi tema lock reyu. Syntax:- acquire(blocking = True, timeout = -1) 2) release():- ...
298c5f852cc317067c7dfcceb529273bbc89ec66
tejasgondaliya5/advance-python-for-me
/Method_Overloding.py
682
4.25
4
''' - Method overloding concept is does not work in python. - But Method ovrloding in diffrent types. - EX:- koi ek method ma different different task perform thay tene method overloading kehvay 6. ''' class Math: # def Sum(self, a, b, c): def Sum(self, a = None, b=None, c=None): # this one method b...
1d10025e853223352536c513a2258ecb5db5f7e2
tejasgondaliya5/advance-python-for-me
/pickling_and _unpickling/pickl.py
410
3.921875
4
# pickling method import pickle, pickling_and_unpickling as cl n = int(input("Enter Number of student : ")) with open('pickling_File.txt', 'wb') as f: for i in range(n): name = input('Enter student name :') roll = int(input('enter studebt roll number : ')) address = input('Enter cit...
08421cdc822d1ee9fb6a906927bb4836f1bc691f
YuanchengWu/coding-practice
/problems/1.4.py
605
4.1875
4
# Palindrome Permutation: Given a string, write a function to check if it is a permutation of a palin­ drome. # A palindrome is a word or phrase that is the same forwards and backwards. # A permutation is a rearrangement of letters. # The palindrome does not need to be limited to just dictionary words. def palindrome_...
7650000b8ef5f368933f9ba3c4c00cfa3bdc5ebb
XiaoQiSAMA/Python
/Data_StructuresAlgorithms/linked_list.py
3,815
3.953125
4
"""链表""" '''单向链表实现栈 用链表的头部实现栈顶,因为只有在头部才能在一个常数时间内有效的插入和删除元素,因为所有的栈操作都会影响栈顶 ''' class LinkedStack: class _Node: # 创建的私有类 __slots__ = '_element', '_next' # 约束,提高内存利用率 def __init__(self, element, next): self._element = element self._next = next def __init__(self...
9a472fda5e011998c4230663f2d0a5b4a5dba929
XiaoQiSAMA/Python
/create_design_mode/abstract_method.py
285
3.875
4
''' 类似接口,在基类中实现的方法 ''' import abc class fruits(metaclass=abc.ABCMeta): @abc.abstractclassmethod def eat(self): """基类方法,不用实现""" class apple(fruits): def eat(self): print('eat!') apple_1 = apple() apple_1.eat()
767b3239ad235c29906cc7f903713ac0c67712c7
laboyd001/python-crash-course-ch7
/pizza_toppings.py
476
4.34375
4
#write a loop that prompts the user to enter a series of pizza toppings until they enter a 'quit' value. As they enter each topping, print a message saying you'll add that to their pizza. prompt = "\nPlease enter the name of a topping you'd like on your pizza:" prompt += "\n(Enter 'quit' when you are finished.) " ...
0872ecc5a6af618e68bb09096e24db52d509dfb9
namanarora00/red-cross
/utils/utils.py
688
3.59375
4
import csv import re regex = re.compile(r"[^\w]", re.IGNORECASE) def read_csv(file_path=None) -> list: if file_path is None: file_path = "resources/test.csv" # test file with open(file_path, "r") as f: reader = csv.DictReader(f) data = [dict(row) for row in reader] cleane...
74b79a2cea03e7b3d979a10c4fe83f838a643262
vietphuong452/SESSION-PYTHON
/SESSION10/drill9.py
1,152
3.84375
4
# loop_count= 0 # while loop_count < 2: # print("How many legs an octopus has:") # a = ['one leg','two legs','six legs','eight legs'] # for i,a in enumerate(a): # print(i+1,a,sep = ".") # b= int(input("Your answer : ")) # if b== 4: # print("You are correct") # else: # pri...
db91962d99f755598cfa0137d8097c740ff0fe1b
vietphuong452/SESSION-PYTHON
/SESSION8/delete.py
307
3.8125
4
# items = ['phone','food','dog'] # items.pop(1) # print(items) # items.remove('dog') # print(items) # items = ['phone','food','dog'] # a = int(input("number : ")) # items.pop(a) # print(items) # items = ['phone','food','dog'] # a = input("Delete what : ") # items.remove(a) # print(items)
06233191fa28329f6994628c041e1f2a5a649db2
vietphuong452/SESSION-PYTHON
/SESSION9/Minihack-part1.py
334
4.03125
4
# colour = ['red','blue','freen','teal'] # print(colour) # colour = ['red','blue','green','teal'] # print("Our colour list : ",*colour,sep=",") # colour =['red','blue','green','teal'] # print("Our colour list: ",*colour,sep=",") # a = input("Something : ") # colour.append(a) # print("Our colour list: ",*colo...
f141441a6a9fe1765ce15e3b8e950768b32e8024
vietphuong452/SESSION-PYTHON
/SESSION6/homework.py
1,541
3.875
4
# while True: # name = input( "Your name is :") # print(name) # if name.isalpha(): # print("Done") # break # else: # print("Rewrite your name") # while True: # passw = input("Enter your password : ") # if passw.isdigit(): # print("Done") # break # ...
66d8f58f42022366d6b34fe4498c4adb852e6f45
vietphuong452/SESSION-PYTHON
/SESSION9/Minihack-part5.py
473
3.609375
4
districts=['ST' ,'BD' ,'BTL','CG ','DD '',HBT'] population=[150.300,247.100,330.300,266.800,420.900,318.000] km2=["117.43","9.224","43.55","12.04","9.96","10.06"] d=[] a1=list(population) a2=list(districts) print("Quan| Dan So | Km2") for a,b,c in zip(districts,population,km2): print(a,"|",b,"|",c) print("The ...
2b5b7dc7a4dcdef1e663e7aacdc4d3cefdb3c846
Dev49199/Turtle_race
/turtle_race.py
1,433
4.0625
4
import turtle from random import randint ts=turtle.Screen() tur2=turtle.Turtle() tur2.hideturtle() tur=turtle.Turtle() tur.hideturtle() tur3=turtle.Turtle() tur3.hideturtle() screen=turtle.Turtle() screen.hideturtle() def start_screen(): screen.penup() screen.goto(-130,130) screen.write("Welcome to ...
f8ba2e3e3c6eec410d11125c5ff8cbf9889eda0d
KimTaeHyun-GIT/Study
/사전.py
642
3.515625
4
cabinet = {3:"유재석", 100:"김태호"} print(cabinet[3]) print(cabinet[100]) print(cabinet.get(3)) print(cabinet.get(5)) print("hi") print(3 in cabinet) # True print(5 in cabinet) # False cabinet = {"A-3":"유재석", "B-100":"김태호"} print(cabinet["A-3"]) print(cabinet["B-100"]) # 새 손님 print(cabinet) cabinet["A-30"] = "김종국" cabi...
ba1539fc9de376407534ba7a80da2dffcf440ef4
KimTaeHyun-GIT/Study
/WebCrawing Example/kyobo.py
1,072
3.515625
4
from urllib.request import urlopen from bs4 import BeautifulSoup # 교보문고의 베스트셀러 웹페이지를 가져옵니다. html = urlopen('http://www.kyobobook.co.kr/bestSellerNew/bestsellr.laf') bsObject = BeautifulSoup(html, "html.parser") # 책의 상세 웹페이지 주소를 추출하여 리스트에 저장 book_page_urls = [] for cover in bsObject.find_all('div',{'class':'detail'}):...
630dd6b75782bdf5917ecd82ccc77bbfd472aabe
KimTaeHyun-GIT/Study
/응용해서 만든거/if문.py
541
3.9375
4
case = int(input('password : ')) if case==3102: print("Password Correct") select = int(input('Enter the number : ')) if select == 1: print("You Enter the 1") elif select == 2: print("You Enter the 2") elif select == 1023: print("New Password Detected") new_password = int(input('Enter the...
a4115af4507e50e01fa7bbe17b06f2e3f141f42f
Yoenn/Study
/Python/Function/Function_4.py
460
4.09375
4
#-*- coding: utf-8 -*- #test 1 def fact(n): if n == 1: return 1 return n * fact(n-1) print(fact(5)) #test 2 def fact_iter(num, product): if num == 1: return product return fact_iter(num - 1, num * product) print(fact_iter(5,1)) #汉诺塔 def move(n,a,b,c): if n==1: print (a, '-->' ,c) else: ...
d0bd63888d218d9bd0bba6c777e396f58947b62b
Yoenn/Study
/Python/Python_Basic/Python_Basic_5.py
465
3.546875
4
# -*- coding: utf-8 -*- #test 1 names = ['yoen','oliver','justin'] for name in names: print (name) L = list(range(10)) print(L) sum = 0 for x in range(101): sum = sum + x print(sum) sum = 0 n = 99 while n > 0: sum = sum + n n = n - 2 print(sum) #test 2 for name in names: print('Hello,%s!'%name) #test 3 n = 1 ...
58df2b56355d4fea5fa061bb116b9982c498274f
jovi-yang/workplace
/zuoye1.17.py
876
3.90625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2018-03-25 23:16:24 # @Author : jovi yang (jovi_yang@yeah.net) """ 习题一: 1 用while语句的2种方法输出数字:1到10 2 用for语句和continue 输出结果:1 3 5 7 9 """ x = 1 while x <= 10: print(x) x += 1 else: pass a = [] for x in range(1, 10): if x % 2 == 0: continue...
dedd912785210f13f287d89c6afdb7c62c62bfe5
jovi-yang/workplace
/zuoye2.3.py
1,753
3.65625
4
#coding=utf-8 # 1 定义一个方法get_num(num),num参数是列表类型,判断列表里面的元素为数字类型。其他类型则报错,并且返回一个偶数列表:(注:列表里面的元素为偶数)。 def get_num(num): l = [] for i in num: if not isinstance(i, int): return '你所输入的参数列表不是全INT整型!' elif i % 2 == 0: l.append(i) return l q1 = get_num([1,2,3,4,5]) print(q1) q2 = get_num([1,2,3,4,'a',5...
77a0cf7be579cd67bf2f9a449d8615c682924d6f
dipeshdc/PythonNotes
/loops/for.py
782
4.125
4
""" For Loop """ sentence = "the cat sat on the mat with"# the rat cat and rat were playing in the mat and the cat was happy with rat on the mat" ''' print("Sentence is: ",sentence) print("Length of sentence:", len(sentence)) print("Number of Occurrences of 'cat': ", sentence.count('t')) #3 ''' count=0 for char in s...
c0b23c7641198243b884f08243e7c6cddeb794ff
dipeshdc/PythonNotes
/generator_decorator/decorators.py
3,169
4.59375
5
#https://realpython.com/blog/python/primer-on-python-decorators/ #Decorators allow you to make simple modifications to callable objects like functions, #methods, or classes #decorators wrap a function, modifying its behavior #http://www.python-course.eu/python3_decorators.php print("1------Functions inside Function :...
e7185c2278b9214bf1520b1850ac2914e8b381f3
Prinitha/LinkedList
/LinkedListDeletion.py
1,305
4
4
class Node: def __init__(self, data): self.data = data self.address = None class Head: def __init__(self): self.head = None def PrintNodes(self): printPointer = head while printPointer is not None: print(printPointer.data) printPointer = prin...
34087fb0f92f0a8722eb07877852d07392d0a24c
sarangacharya/LearnPython
/one.py
145
3.65625
4
print("hello this is new world programme") dog_name = "rex" print(dog_name) dog_name = 'T-' + dog_name print(dog_name) range(10) list(range(10))
e6fe9740e0d4eda6a56353df41a5f53833b953ec
vinaybisht/python_tuts
/FirstClass.py
332
3.546875
4
def list_benefits(): return ["One", "Two", "Three", "Four"] def build_sentence(args): return "%s is argument of function" % args def print_pattern(): for k in range(5): print("*"*k) tempList = list_benefits() for i in range(len(tempList)): print(build_sentence("Function calling")) print_...
014db87928669d171b65f3c43c09aca9345843bc
MrLVS/PyRep
/HW5.py
621
4.15625
4
print("Введите неотрицательные целые числа, через пробел: ") answer = input("--> ") def find_min_int_out_of_string(some_string): """ A function to find the minimum number outside the list. """ int_list = list(map(int, some_string.split())) for i in range(1, max(int_list)+1): if i not in int_list: ...
35d0fce23734caccf4dc22ddec7175a2230b3c5d
MrLVS/PyRep
/HW10.py
496
4.21875
4
# Solution of the Collatz Hypothesis def сollatz(number): """ A function that divides a number by two if the number is even, divides by three if the number is not even, and starts a new loop. Counts the number of cycles until the number is exactly 1. """ i = 0 while number > 1: if numbe...
ba9c30a0aedc8693aefdb1c1f3f4e011bdde51d8
frederatic/Python-Practice-Projects
/fibonacci.py
500
4.03125
4
# iterative function using loop def fibo(n): current = 0 after = 1 for i in range(0,n): current, after = after, current + after return current # recursive function def fibonacci(n): if n == 0: return 0 if n == 1: return 1 else: result = fibonacci(n-1)+fibon...
4dc8fcf6c516ca8bf19c652eef0ab235aa0dc1c4
frederatic/Python-Practice-Projects
/palindrome.py
509
4.3125
4
# Define a procedure is_palindrome, that takes as input a string, and returns a # Boolean indicating if the input string is a palindrome. def is_palindrome(s): if s == "": # base case return True else: if s[0] == s[-1]: # check if first and last letter match return is_palin...
14fe5a7828bccd7cf1787e5110381dd6fd47d538
olimpiojunior/Estudos_Python
/Section_14/teste_memoria.py
499
3.6875
4
''' Teste de memória com generator sequência de fibonacci: 1,1,2,3, 5, 8, 13, 21... ''' #Com lista consome muita memoria ~449MB def seq_fib(max): nums = [] a, b, = 0, 1 while len(nums) < max: nums.append(b) a, b, = b, a + b return nums print(seq_fib(9)) #Com generator consome muito me...
99b5497ff112f5e787afb9231b50d29d18e1b71d
olimpiojunior/Estudos_Python
/Section_18/lendo_csv.py
982
4
4
""" CSV - Comma Separeted Values (Valores Separados por Virgula) with open("original.csv") as arquivo: dados = arquivo.read() print(dados) dados = dados.split()[3:] print(dados) A linguagem Python possui duas formas diferentes para ler dados em aquivos csv; - reader -> Permite que iteremos sobre a...
1db378b15ee9977bc858dfae83ca2e168536960b
olimpiojunior/Estudos_Python
/Section_10/reduce.py
480
3.859375
4
''' Reduce Obs: A partir do Python 3+ a função reduce não é mais uma função Built in. Agora temos que importar a partir do módulo 'funtools' A função reduce recebe dois parametros, a função e o iterável - reduce(função, dados) ''' from functools import reduce #Usando função def soma(x,y): return x+y l = [1,2,3,4,...
6a141c1e62a9565c54b544ea6ec058d650d03e0d
olimpiojunior/Estudos_Python
/Section_9/list_comprehension_p1.py
1,062
4.1875
4
""" list Comprehension Utilizadando list comprehension nós podemos gerar ovas listas com dados processados a partir de outro iterável #Parte 01 #1 num = [1,2,3,4,5] res = [i * 10 for i in num if i%2 != 0] print(res) #2 print([i**2 for i in [1,2,3,4,5]]) #3 nome = 'olimpio' print([l.upper() for l in nome]) #4 lista...
2c8aaddc8adb1e71d2d44161c44e2842a686354e
olimpiojunior/Estudos_Python
/testes/Teste4.py
1,376
4.28125
4
""" mypy só funciona quando se utiliza o type hinting type hinting é a utilização de atributos com os tipos sendo passados dentro da função, como abaixo """ import math def cabecalho(texto: str, alinhamento: bool = True) -> str: if alinhamento: return f"{texto.title()}\n{'-'*len(texto)}" else: ...
da3d214c93118d4ba3947536ca5dd7163298b59a
olimpiojunior/Estudos_Python
/Section 8/funcoes_com_parametros.py
1,002
4.34375
4
''' Funções com parametros funções que recebem dados para serem processados dentro da função entrada -> processamento -> saida A função é feita com parametros, Ao usar essa funão é passado os argumentos ----------------------------------------------------- def quadrado(x): return x**2 print(quadrado(2)) print(qu...
9f6e71d2b6edee357d69aef795a686b0ce85e1ff
olimpiojunior/Estudos_Python
/Section_10/map.py
1,110
4.5
4
""" map - função map realiza mapeamento de valores para função function - f(x) dados - a1, a2, a3 ... an map object: map(f, dados) -> f(a1), f(a2), f(a3), ...f(an) ------------------------------------------------------------------- import math def calc(r): return math.pi * (r**2) raios = [1, 2.2, 3., 4, 5.7, 8] l...
02b22f6251045db4e79b12b340b01cf1c92a68c5
olimpiojunior/Estudos_Python
/Section_10/len-abs-sum-round.py
753
3.796875
4
''' len() - retorna tamanho, ou seja, a qtd de elementos abs() - retorna o valor absoluto de um inteiro ou real sum() - retorna a soma total dos elementos round() - retorna um numero arredondado para n digito de precisão ''' lista = [1,2,3,4,5,6,7] tupla = (1,2,3,4,5,6,7) conjunto = {1,2,3,4,5,6,7} dict1 = {'a':1, 'b'...
8f21b3298fee58ecd8324ab0a5b61405b3af9956
antondelchev/First-Steps-in-Coding---Lab
/09. Yard Greening.py
238
3.875
4
sq_meters = float(input()) total_sq_m_price = sq_meters * 7.61 discount = total_sq_m_price * 0.18 final_price = total_sq_m_price - discount print(f"The final price is: {final_price} lv.") print(f"The discount is: {discount} lv.")
ed9f95a6170b0477fa4ea6a336b336735a452702
abidtkg/Practices
/python/json.py
680
4.3125
4
# full_name = input("Enter your name: ") # birth_year = int(input("Enter your age: ")) # print(f'Hi, {full_name}. How are you today?') # feeling = input("Type: ") # print(f'Hey {full_name}, your birth year is {birth_year} ? is it true?') # age_confirm = input("y/n? :") # print(f'you are {feeling} tody so, it\'s a good ...
9212fe976f29142f2c678acb874964aacafed87f
Shrubabati777/ANN_model
/main.py
1,276
3.5625
4
#importing libraries import pandas as pd import numpy as np import tensorflow as tf from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler import csv_def #read the dataset and import dataset = pd.read_csv('city.csv') x=dataset.iloc[:,2:-1].values #everything taken into ...
56ea91c4338133d3684dd6811f157a588ccc8b0b
portfolio-y0711/2021_algo
/_basic/map/_02_/index.py
516
3.734375
4
# https://www.acmicpc.net/problem/1157 # 알파벳 대소문자로 된 단어가 주어지면, 이 단어에서 가장 많이 사용된 알파벳이 무엇인지 알아내는 프로그램을 작성하시오. 단, 대문자와 소문자를 구분하지 않는다. word = input().upper() chars = list(set(word)) counters = [] for x in chars : cnt = word.count(x) counters.append(cnt) if counters.count(max(counters)) > 1: print('?') else ...
029818b50ae1d127a24e7037a8eb1c1ab7bb0ec5
dipanshu231099/CS308-Lab3-Text-Software
/API.py
7,590
4.09375
4
from string import punctuation import nltk nltk.download('punkt') from collections import defaultdict #defining set of words to skip will calculating various actions articles = ['a','an','the',"i","is","and","are","in"] def removePunctuations(string): """ removing punctuation marks from a string """ f...
6665351a779b18d896bbf81f7405bcfe32fc9635
Bluemi/rl_testbed
/src/update_rules.py
1,952
3.625
4
from typing import Callable def sample_average_update_rule(current_action_value: float, reward: float, number_of_action_tries: int) -> float: """ Implements the sample average update rule with new_action_value = old_action_value + (1.0 / (number_of_action_tries + 1)) * (reward - current_action_value) ...
bb5fda0bc5a0f19a832a4eda328d40f87d48f59a
dlangleychi/Highly-Divisible-Triangular-Number
/sample.py
3,510
3.890625
4
''' This is a Project Euler problem with a neat solution that combines efficient design and Python functionality. I like it how you can do all steps, including generating primes, in one pass. The Counter object makes the code extra clean. Simple problem: Given N <= 1000, find the first triangle number with more tha...
a5c984ed5eee1a4a31b2fd20da7121bbcbf916de
mnulll/operating-system-lab
/Lab 6 OS/lab6.py
1,504
3.703125
4
import threading import random import time class Person(threading.Thread): running = True # to make person prepare def __init__(self, index, left_fork, right_fork): threading.Thread.__init__(self) self.index = index self.left_fork = left_fork self.right_fork = right_fork ...
9eb9add72964e7d145a239db6ef5a303871be1af
prince749924/PythonFundamentals
/LabPractice/userage.py
249
3.515625
4
#write a program to take a input from the users age. #if the users age is below 15 print a message(u r a child). #if the users age is greater than 15 and lesser than 40 print a message(u are adult),if user is greater than 40 print a message u r old
8efc44209c494fa50387717b2d5db3b788e6dfe9
Aiden-Jeon/Algorithm
/src/leetcode/1122.py
1,095
3.859375
4
""" title: relative-sort-array date: 2021-04-04 - problem number: 1122 - difficult: Easy - https://leetcode.com/problems/relative-sort-array/ --- ## Define input, output - Input: - Two arrays are given, arr1 and arr2 - arr2 is distinct and it is subset of arr1 - Output: - arr2_1: ordered values whi...
9be0fcb8ccdc02e140520d06c44ca0dfc4cbd808
Aiden-Jeon/Algorithm
/src/programmers/p_12963.py
428
3.796875
4
n = 3 k = 3 def solution(n, k): def factorial(n): result = 1 for i in range(2,n+1): result*=i return result answer = [] arr = [i for i in range(1,n+1)] k -= 1 for i in reversed(range(1,n)): m = k // factorial(i) k = k % factorial(i) answe...
9a0126fbde149ded3fc586221d93970bea8ec77d
truongnuhoan/Linux
/solonhon.py
111
3.59375
4
a = input ('a = ') b = input ('b = ') if ( a>b ): print 'so lon nhat :',a else : print 'so lon nhat :',b
09ccd08afaa39a40a29af698910261366e10aa9c
truongnuhoan/Linux
/swap.py
112
3.609375
4
a = input ('a=') b = input ('b=') a = a+b b = a-b a = a-b print 'ket qua sau khi doi' print 'a=',a print 'b=',b
403b81228bddbef52cd6695d1143cc15e5050724
FreemanGud/TileTraveller
/tile_test.py
3,183
4.21875
4
def move_north(location): location[1] +=1 return location def move_east(location): location[0] +=1 return location def move_south(location): location[1] -=1 return location def move_west(location): location[0] -=1 return location def move(movement, location): if movement == "n" o...
6fae3075ff871603f1f05d122f1327735ae922fd
AlanEstudo/Estudo-de-Python
/ex005.py
220
4.0625
4
# faça um programa que leia um numero inteiro e mostre seu sucessor e o antecessor n = int(input('Digite um numero: ')) a = n - 1 s = n + 1 print('O Antecessor do numero {} é {}, e seu Sucessor é {}'.format(n, a, s))
2ecb97c622ad8cebccad822733bc009dbcdd0638
AlanEstudo/Estudo-de-Python
/ex085.py
576
4
4
# Crie um programa onde o susuário posso difitar sete valores numéricos. # Cadastre-os em uma lista única que matenha separados os valores pares e impares. # No final mostra os valores pares e impares em ordem crescente. numeros = [[], []] valor = 0 for c in range(0, 7): valor = int(input(f'Digite o {c + 1}ª valo...
7c13a88930aaecd9fc9473c108fc8d257443f3a1
AlanEstudo/Estudo-de-Python
/ex054.py
518
3.84375
4
# Crie um programa que leia o ano de nascimento de sete pessoas. # Mostre quantas pessoas ainda nao atingiram a maioridade, # Quantoas pessoas ja são maiores from datetime import date atual = date.today().year maior = 0 menor = 0 for c in range(1, 8): vlNascimento = int(input('Digite o {}º ano de nascimento: '.for...
399f2b45dc8a16cf9aa73798f82a2cf1ed8fc064
AlanEstudo/Estudo-de-Python
/ex069.py
1,130
3.890625
4
# Crie um programa que leia a idade eo sexo de várias pessoas. # A cada pessoa cadastrada o programa deverá perguntar se o usuário quer ou não continuar. No final mostre: # Quantas pessoas tem mais de 18 anos. # Quantos homens foram cadastrado. # Quantas mulheres tem menos de 20 anos. pessoas_mais_18 = quantos_homens ...
916c450d31f5c5cc27f4aa1158f53be1ae761e2b
AlanEstudo/Estudo-de-Python
/aula17a.py
905
4.1875
4
# Variáveis Compostas (Listas) # .append(' ') => adiciona um elemento no final da lista # .insert(0, ' ') => adiciona um elemento no inicio ou no indice da lista # del variavel[3] => apaga o elemento na indice 3 # variavel.pop(3) => apaga o elemento no indice 2, caso não passa o indici apaga o ultimo elemento # variav...
1854d18a1bffe3f0666f1fa8b6e4f0301f95da51
AlanEstudo/Estudo-de-Python
/ex025.py
192
3.9375
4
# Crie um programa que leia o nome de uma pessoa e diga se eka tem "Silva" no nome. vlNome = str(input('Nome: ')).strip() print('Tem "SILVA" no nome? {}'.format('SILVA' in vlNome.upper()))
ee21611e706e00e00cd30315eaf04f8217791b60
AlanEstudo/Estudo-de-Python
/ex020.py
344
3.828125
4
#Faça um programa que leia o nome de quatro alunos e mostre a orde sorteada import random vlA1 = str(input('Primeiro aluno: ')) vlA2 = str(input('Segundo aluno: ')) vlA3 = str(input('Terceiro aluno: ')) vlA4 = str(input('Quarto aluno: ')) vlLista = [vlA1, vlA2, vlA3, vlA4] random.shuffle(vlLista) print('Ordem sortead...
84c376e47821e9ffe7ebfb067a0a99e865f5bd57
AlanEstudo/Estudo-de-Python
/ex096.py
506
4
4
# Crie um programa que tenha uma função chamada area(), que receba as dimensões de um terreno retangular(largura e comprimento) # e mostre a area do terreto. def calculo_area(largura, comprimento): area = largura * comprimento print(f'A area de um terreno {largura} x {comprimento} é de {area}m².') # Programa ...
b6fe10e17b9e4aa330841cb6a82c5719d85bc2b9
AlanEstudo/Estudo-de-Python
/ex075.py
768
4.1875
4
# Desenvolva um programa que leia quatro valores pelo teclado e guarde-os em uma tupla.No final mostre: # quantas vezes apareceu o valor 9. # Em que posição foi digitado o primeiro valor 3. # Quais foram os números pares. numeros = ( int(input('Digite um número: ')), int(input('Digite outro númeror: ')), i...
fdd8631f3a686b2701a91e313588b332a6ed1b71
AlanEstudo/Estudo-de-Python
/ex031.py
544
4.03125
4
# desenvolva um programa que pergunte a distância em uma viagem em KM. # Calcule o preço da passagem, cobrando R$0.50 por km para a viagens de até 200 km e R$0.45 para viagens mais longas km = float(input('Qual a distância da viagem em Km: ')) print('------ Tabela de preço -------') print('Até 200Km R$0.50 por Km ---...
967625d9311f8887929ea19f31acceecd203fd3f
AlanEstudo/Estudo-de-Python
/ex078r.py
809
3.625
4
maior = manor = 0 lista_numeros = [] for posicao in range(0, 5): lista_numeros.append(int(input(f'Digite o valor para a posição {posicao}:'))) if posicao == 0: maior = menor = lista_numeros[posicao] else: if lista_numeros[posicao] > maior: maior = lista_numeros[posicao] i...
5166afd1634e9c3819f4dec733cec78be4f5de4d
AlanEstudo/Estudo-de-Python
/ex027.py
385
4
4
#Faça um programa que leia o nome completo de uma pessoa, mostrando em seguida o primeiro e o ultimo nome separadamente vlNome = str(input('Nome: ')).strip() vlLista = vlNome.split() print('Nome completo: {}'.format(vlNome)) print('Primeiro nome: {}'.format(vlLista[0])) #print('Último nome: {}'.format(vlLista.pop())...
50558d02725abf9c04eff5efe7806cca7510bfc2
ukrduino/PythonElementary
/Lesson02/Exercise2a1.py
553
4.15625
4
# Write a bubble-sort function def bubble_sort(un_list): """ Bubble-sort function >>> unsorted_list = [54, 26, 93, 17, -77, 31, 44, 55, 200000] >>> bubble_sort(unsorted_list) >>> print unsorted_list [-77, 17, 26, 31, 44, 54, 55, 93, 200000] """ for pass_number in range(len(un_list) - 1...
9185f60dee9625d663bcecea816da0255507f7a3
ukrduino/PythonElementary
/Lesson02/Exercise2_1.py
724
4.65625
5
# Write a recursive function that computes factorial # In mathematics, the factorial of a non-negative integer n, denoted by n!, # is the product of all positive integers less than or equal to n. For example, # 5! = 5 * 4 * 3 * 2 * 1 = 120. def factorial_rec(n): """ Computing factorial using recursio...
032e94645610d7ccbc37f131d60fdc325290c432
ukrduino/PythonElementary
/Lesson02/Exercise2_4.py
777
3.890625
4
# Write a decorator that computes the execution time of the decorated function import time from Lesson02.Exercise2_1 import factorial_loop from Lesson02.Exercise2_1 import factorial_rec def wrapped_with_timer(func): """ Computes the execution time of the decorated function """ def wrapper(*args, **kw...
5113c9cf56e92a7ecacd68d7053b519fc5c6f0c8
ghasem336/webrobber
/Classes/myClasses.py
1,358
3.59375
4
import time, os from colorama import Fore as Color class Psentense: def printer(self, sentense): #Get a input from the user and Type print it out sentense_len = len(sentense) for letter in range(sentense_len): print(Color.CYAN + sentense[letter], end='', flush = True);time.sleep(0.1) ...
a273d9b05d584d3818c2cfbd2a020d11c8d927f9
rootzilopochtli/python-notes
/programming_in_python/classes.py
1,205
4.1875
4
# 15. Classes # class class Car: def __init__(self,name,gear,miles): self.name = name self.gear = gear self.miles = miles def drive(self,miles): self.miles = self.miles + miles def shift_gear(self,gear): self.gear = gear car = Car("Tesla", 0, 0) car.shift_gear(6) de...
4c289536721da7f0aacf1d7a09483102add0d98d
rootzilopochtli/python-notes
/programming_in_python/comparison_operators.py
590
4.125
4
# 10. Comparison operators # compare n1 = 5 n2 = 10 # greater than n1_gt_n2 = n1 > n2 # return a boolean #print(n1_gt_n2) # less than n1_lt_n2 = n1 < n2 #print(n1_lt_n2) #print(83 < 120) # greater than eqal #print(n1 >= n2) #print(99 >= 99) # less than eqal #print(5 <= 5) # not eqal to #print( 5 != 9 ) # eqal to #print...
8610ae2a0a5dcb50e7ac978502ca9534ac8e89e0
adahany/EDX-Code
/EDX-Problems/Problem set 1/#1.py
253
3.765625
4
def isVowel(s): s = s.lower() list1 = ['a', 'e', 'i', 'o', 'u'] count = 0 for letter in s: if letter in list1: count +=1 print 'Number of Vowels: '+str(count) return count z = isVowel('azcbobobegghakl')
d01cea9f98089ba4e755e461277a1b294910f54f
Magott300/ByLearnJornadaPythonFaixaPreta
/Faixapreta3.py
4,864
4.21875
4
#Laços de repetição """ É uma excelente forma de evitar repetição de código Ele vai executar n vezes uma operação n => Quatidade de vezes definidas # for => Nossa palavra-chave para repetição # variavel => O dado que estamos trabalhando no momento atual # in => nossa palavra chave para "onde vamos repetir"? ...
ac9710732862b340c9d0fd874d9e098e2fb1b110
Anku-0101/Python_Complete
/Function_And_Recursion/03_first_Nnatural_Recursion.py
267
3.9375
4
def Natural_Number_Sum(n): if(n < 1): return "Please enter a natual number" if(n==1): return 1 else : return n + Natural_Number_Sum(n-1) print(Natural_Number_Sum(8)) #print(Natural_Number_Sum(0)) #print(Natural_Number_Sum(3))
ec90fa2fe745ef77be5573534260e1261f3a0d87
Anku-0101/Python_Complete
/String/03_StringFunction.py
329
4.15625
4
story = "once upon a time there lived a guy named ABC he was very intelliget and motivated, he has plenty of things to do" # String Function print(len(story)) print(story.endswith("Notes")) print(story.count("he")) print(story.count('a')) print(story.capitalize()) print(story.find("ABC")) print(story.replace("ABC", ...
23b7d349bf78e95a29d036bd3fab4462b26fcdce
Anku-0101/Python_Complete
/DataTypes/04_Input.py
159
4.25
4
''' input() function This function allows user to take input from the keyboard as a string ''' a = input("Enter your name: ") print(a) print(type(a))
f48ad084c38a7023a5850dc1452b2534e620e776
Anku-0101/Python_Complete
/DataTypes/03_TypeCasting.py
229
4.1875
4
a = "3433" # Typecasting string to int b = int(a) print(b + 1) ''' str(31) --> "31" => Integer to string conversion int("32") --> 32 => string to integer conversion float(32) --> 32.0 => Integer to float conversion '''
1d8479254cbe4a936f1b7c21715fc58638f61f84
Anku-0101/Python_Complete
/DataTypes/02_Operators.py
591
4.15625
4
a = 3 b = 4 print("The value of a + b is", a + b) print("The value of a*b is", a * b) print("The value of a - b is", a - b) print("The value of a / b is", a / b) print("The value of a % b is", a % b) print("The value of a > b is", a > b) print("The value of a == b is", a == b) print("The value of a != b is", a != b) p...
2fd0beafe0b17f346bcc7f750cbefd27260d87eb
Anku-0101/Python_Complete
/Inheritance_And_More_In_OOPs/03_multiple_inheritance.py
428
3.734375
4
class Freelancer: company = "Fiverr" level = 0 def upgradeLevel(self): self.level = self.level + 1 class Employee: company = "Visa" eCode = 120 class Programmer(Freelancer, Employee): name = "Aman" p = Programmer() p.upgradeLevel() print(p.company) # Company attribute is pres...
6bce6ad7f0155501fcf7d0b170eecc385f64b163
Langsheng0716/zhangsan
/demo03.py
2,164
3.671875
4
'''a = input("请输入你的名字:") b = input("请输入你的年龄:") try: if int (b) >= 18: print(a,"成年了") else: print(a,"未成年") except Exception as e: print("请输入正确的年龄!")''' #处理用户输入的数据 '''代码的单位 包 自带的包 import 第三方的 pip install 包名 pip uninstall 包名 pip list 常见的第三方的包pymysql ...
13031b94c9821d73b42c7ddc81c997f382569f49
sputnikpetrinets/project_sputnik
/tau_leap.py
23,346
3.671875
4
from algorithm import Algorithm import tau_leap_data import numpy as np import random import math class TauLeap(Algorithm): """ Subclass of Algorithm, allows Tau Leap algorithm to be run, for a specified run time or number of iterations, for a specified number of runs. Instance Variables: - epsilo...
05f486e4dac5d903bd5ec01c15c0835caa59a8b2
Weenz/software-QA-hw2
/bmiCalc.py
1,631
4.3125
4
import math #BMI Calculator function def bmiCalc(): print ("") print ("BMI Calculator") print ("------------------") #Loop to verify integer as input for feet while True: try: feet = int(input("Enter your feet part of your height: ")) except ValueError: ...
12491cc31c5021a38cb40799492171c2d5b6b978
muneel/url_redirector
/redirector.py
2,194
4.25
4
""" URL Redirection Summary: Sends the HTTP header response based on the code received. Converts the URL received into Location in the response. Example: $ curl -i http://127.0.0.1:5000/301/http://www.google.com HTTP/1.0 301 Moved Permanently Server: BaseHTTP/0.3 Python/2.7.5 Date: Wed, 19 Apr 2017 20:06:11 GMT Locat...
38d6d920f60fe3999d694edcec66fd42f3571c9d
AswinT22/Code
/Daily/DailyCodingProblem/DailyCodingProblem#4.py
1,080
3.8125
4
# This problem was asked by Stripe. # Given an array of integers, find the first missing positive integer in linear time and constant space. # In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well. # For example, the input [3,...
94c39abb57532962ca90b9df933800cfa6d1b3b3
AswinT22/Code
/Daily/Vowel Recognition.py
522
4.1875
4
# https://www.hackerearth.com/practice/basic-programming/complexity-analysis/time-and-space-complexity/practice-problems/algorithm/vowel-game-f1a1047c/ def count_vowel(string,): vowel = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"] count = 0 length=len(string) for i in range(0, length): i...
42cabba01a970d08c4c32244e27b8406875b17bc
AswinT22/Code
/Daily/DailyCodingProblem/DailyCodingProblem#8.py
1,211
4.03125
4
# https://codezen.codingninjas.in/practice/102975/4406/interview-shuriken-7:-unival-trees # A unival tree (which stands for "universal value") is a tree where all nodes under it have the same value. # Given the root to a binary tree, count the number of unival subtrees. # For example, the following tree has 5 unival...
572673715fe9aa87286950bed7a40eb001bbde0a
Heegene/learning_python_200627
/conditionalStatement_0709.py
353
3.71875
4
# 중첩if 예제 appleQuality = input("사과의 상태를 입력하세요 :") applePrice = int(input("사과 1개의 가격을 입력하세요 : ")) if appleQuality == "신선" : if applePrice < 1000: print("10개를 삽니다.") else: print("5개를 삽니다.") else: print("사지 않습니다.")
5bd8eaa46aa586dc9917c92f5ecdd170cd375430
Heegene/learning_python_200627
/tuple_demo_200724.py
763
3.65625
4
# 튜플: 변경될 수 없는 리스트 colors = ("red", "green", "blue") # 둥근 괄호로 됨 # colors[0] = "redddd" # 컴파일에러 발생 tuple 변경 불가 # dictonary 키와 값을 가지는 객체 # 딕셔너리 = { 키1:값1, 키2:값2, ... } contacts = {'Kim':'01012341234', 'Kong':'02234', 'kongE':'12323'} if "Kim" in contacts: print("해당 키가 딕셔너리에 있습니다. ") # 딕셔너리의 순회 for ...
2fc4a2ce774a034b2d84a6f93ad21efde5913b08
spencerkee/experiments-in-topic-extraction
/functions.py
2,407
3.578125
4
def create_user_rating_history(filename='ratings.csv'): """ Returns: user_rating_history ( dict - {string:[[string,float]]} ) - {user_id:[(movie_id,rating)]} """ user_rating_history = {} with open('ratings.csv','r') as f: for line in f: if 'userId,movieId,rating,t...
9438ef6944b88ff927844b8ee9b1a127c12a04ab
jofuspei/2020-hackathon-zero-python-retos-pool-3
/src/kata1/rps.py
1,502
3.84375
4
from random import randint options = ["Piedra", "Papel", "Tijeras"] # El resultado de salida son las siguientes String draw = "Empate!" #'Empate!' win = "Ganaste!" #'Ganaste!' lose = "Perdiste!" #'Perdiste!' def quienGana(player, ai): print(player, ai) player = player.title() ai = ai.title() print(...
0a611a07ab13f551b4a0d79709095a10e443a822
jonnyboy1241/Handwritten_Digits
/utilities.py
1,117
3.6875
4
# This file includes various utilities that are helpful for visualization/accuracy computation import matplotlib.pyplot as plt import numpy as np import time import random # This funciton displays an MNIST handwritten digit as a 28x28 pixel image def view_image(image): image = image.reshape(28, 28) plt.gray()...
8299f3f9b8ae5f7f1781d56037247da67de61ddd
Cpano98/Ejercicios-Clase
/PruebaWhile.py
329
4.125
4
#encoding: UTF-8 #Autor: Carlos Pano Hernández #Prueba ciclo while import turtle def main(): radio=int(input("Radio:")) while radio>0: x=int(input("x:")) y = int(input("y:")) turtle.goto(x,y) turtle.circle(radio) radio=int(input("Radio:")) turtle...
1beb52c55f313d9c36fa845995322d698475f93f
mitchCarmen/Code_Bucket
/CODE_Py_3_Manipulation.py
12,002
3.6875
4
############################################################### ############### RESOURCES https://developers.google.com/edu/python/introduction https://docs.python.org/3/tutorial/index.html ############################################################### ####################### GETTING STARTED # SLICING # BOOLEAN IND...
d1d062ae8b080b5e94fe45f8af2285c84d554691
paraggattani28/AI_LAB
/LAB3-8_puzzle_bfs/8puzzle_bfs.py
2,504
3.625
4
def bfs(src,target): # Use brute force technique visited_states=[] visited_states.append(src) arr = [src] c = 0 while arr: c += 1 if arr[0] == target: ret...
cda13d7e2f11640058f6b4a5636c540efd21a165
jeffersonvital20/AprendendoPython
/DataScience/capitulo5.py
287
3.640625
4
class Livro(): def __init__(self): self.titulo = 'O monge e o executivo' self.isbn = 9988888 print('Construtor criado') def imprime(self): print('Foi criado o livro {} e ISBN {}'.format(self.titulo, self.isbn)) Livro1 = Livro() Livro1.imprime()
af2da4c121fae1fdd825e8ff1b3384a61cd20430
Sleeither1234/t04_huatay_chunga
/EJERCICIO_07.py
492
3.890625
4
# CALCULO DE LA VELOCIDAD FINAL velocidad_inicial_1,gravedad_1,ALTURA=0.0,0.0,0.0 # ASIGNACION DE VALORES velocidad_inicial_1=56.3 gravedad_1=9.78 ALTURA=54 # CALCULO import math velocidad_final=math.sqrt((velocidad_inicial_1**2)+2*(gravedad_1*ALTURA)) # MOSTRAR VALORES print("La velocidad inicial del objeto es: "+...
8c60b24dc470961829f6b861891d23626eaf4cf4
morgenvera/test_100
/test037.py
237
3.75
4
''' 实例037:排序 题目 对10个数进行排序。 程序分析 同实例005。 a = [3, 2, 1] a.sort() print(a) ''' a = [] print("Please input 10 characters: ") for i in range(10): a.append(int(input(""))) a.sort() print(a)
d02f066e52a4d9d09df966d63f3504fbeb2939b3
benwatson528/advent-of-code-20
/main/day22/crab_combat.py
691
3.53125
4
from typing import List def solve(player1: List[int], player2: List[int]) -> int: winning_deck = take_turn(player1, player2) return sum((a + 1) * b for a, b in enumerate(reversed(winning_deck))) def take_turn(player1: List[int], player2: List[int], ) -> List[int]: if len(player1) == 0: return pl...