blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
ad59ed5a6d1efa47e2e9025420dafb4aa327304e
VovoRVA/Invader_hunter
/run.py
3,453
3.578125
4
from sys import argv class InvaderRecognizer: def __init__(self, accuracy: float): self.accuracy = accuracy @staticmethod def read_file(filename: str) -> list: try: with open(filename, 'r') as file: return [list(line.strip()) for line in file] except F...
ba83571eb0bab91de4032508ff1f0810da656ea2
chomimi101/system-design
/tiny-url/tiny-url.py
1,025
3.578125
4
class TinyUrl: def __init__(self): self.long_short = {} self.short_long = {} self.char_dict = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" self.tot = 0 # @param {string} url a long url # @return {string} a short url starts with http://tiny.url/ def lo...
d668e648293f44ab766f2126349c3bb9a422f19f
Nish76ant/Multiple-Inheritence-in-Python-Code
/MultipleInheritence.py
1,386
3.6875
4
class Employee: noOfLeaves = 8 var = 8 def __init__(self,name,role,salary): self.name = name self.role = role self.salary = salary def printDetailsofEmp(self): return f'Hey your name is {self.name} and your role is {self.role} and your salary is {self.salary}...
60f24bde8f1acd6637010627b439584eb8d08f32
mosesobeng/Lab_Python_04
/Lab04_2_3.py
1,048
4.3125
4
print 'Question 2' ##2a. They will use the dictionary Data Structure cause they will need a key and value ## where stock is the key and price is the value shopStock ={'Apples ' : '7.3' , 'Bananas ' : '5.5' , 'Bread ' : '1.0' , 'Carrots ':'10.0','Champagne ':'20.90','Strawberries':'32.6'}...
8e6b5ddf4a8e8199af33626c2d5f96513002fab1
apatten001/Car_repair
/car_repair.py
678
3.703125
4
from parts import part class CarRepair: def __init__(self): self.part = input("What part do you need?: ") self.part = self.part.capitalize() self.cost = part.get(self.part) self.labor = 1.75 # this gets the part and cost from dictionary def parts_cost(self): if s...
681b30c132deb92cdb9188bfee4ab8f683f85a9e
HammadAhmedSherazi/Python-Assignment-2-3
/python assignment 3/DictionaryAdd.py
177
3.609375
4
personal_info={"Name": "Hammad Ahmed","Contact No.": "0304-********", "Email":"abc@gmail.com"} print (personal_info) personal_info["age"]=int(input("Enter your age:")) print (personal_info)
cbec5a76e403c55dacae345a07bbd42a941befd8
anahm/4word-game
/wordmatch.py
3,036
3.78125
4
import re def main(): # want to randomly print out a word. print "Insert random word here.\n" while True: user_word = raw_input("Your turn: ").upper() if (not check(user_word)): print "Try again? Word is: " + next_word + "\n" else: # add the word to known w...
e6b31f6dc70f44c41294c46fc3b262a876a8f133
CRTejaswi/Python3
/Text Processing/ROT13/rot13v1.py
1,352
3.890625
4
"""rot13v1 = Convert command-line input to ROT13 format""" ######################## IMPORT LIBRARIES ####################### import sys import string ########################## DICTIONARIES ######################### CHAR_MAP = dict(list(zip(string.ascii_lowercase, string.ascii_lowercase[13:36]+string.ascii_lowerca...
eb7a489b667d475b5808ccb20cc03604e022dba7
CRTejaswi/Python3
/Text Processing/PyPDF2/7.py
1,409
3.5
4
""" Python3: Extract text from pdf file and copy into txt file """ import PyPDF2 pdf_pages = [] # Page object container pdf_text = [] # Page text container pages = [int(i) for i in input('Enter page numbers to split text for: ').split(',')] # Initialize input pdf file in_pdf = open(r'path/to/input.pdf', 'rb') pdf_re...
52f3c8c96b86ac7d6eace0b3102b31dbec0bd750
CRTejaswi/Python3
/Basics/SimpleCalc.py
1,426
3.734375
4
""" SimpleCalc: Four-Function Calculator """ #################### FUNCTION INITIALIZATIONS ################### def Add(x,y): print('Sum = ',x+y) def Sub(x,y): print('Difference = ',x-y) def Mul(x,y): print('Product ',x*y) def Div(x,y): print('Quotient = ',x/y) ###########################################...
59372d406d16df1fb4db37440ceee32b0f466345
byunseob/python-study
/파이썬 코딩의 기술/chapter-04-mataclss & attribute/29.Use generic attributes instead of getters and setter methods/main.py
1,972
3.546875
4
# 파이썬에서는 명시적인 게터와 세터를 구현할 일이 거의 없다. class Resistor(object): def __init__(self, ohms): self.ohms = ohms self.voltage = 0 self.current = 0 r1 = Resistor(50e3) r1.ohms = 10e3 r1.ohms += 5e3 class VoltageResistance(Resistor): def __init__(self, ohms): super().__init__(ohms) ...
6ef55cc4ae921f109d089d680e7af4d2bf040574
byunseob/python-study
/파이썬 코딩의 기술/chapter-01-pythonic/08.simple comprehension/main.py
349
4.0625
4
# 리스트 컴프리헨션은 다중 루프와 루프 레벨별 다중 조건을 지원한다. # 표현식이 두 개가 넘게 들어 있는 리스트 컴프리 헨션은 가독성상 좋지 않아 지양해야한다. matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] flat = [x for row in matrix for x in row] print(flat) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
1d9273f5c011deea21d1f9c16a6a8c4f5f40181c
byunseob/python-study
/파이썬 코딩의 기술/chapter-01-pythonic/07.comprehension/main.py
830
3.640625
4
# comprehesion 이란 iterable 한 오브젝트를 생성하기 위한 방법중 하나로 파이썬에서 사용할 수 있는 유용한 기능중 하나이다. # List Comprehension (LC) # Set Comprehension (SC) # Dict Comprehension (DC) # Generator Expression (GE) # Generator 의 경우 comprehension 과 형태는 동일하지만 특별히 expression이라고 부른다. # 한 리스트에서 다른 리스트를 만들어내는 간결한 문법 # 이 문법을 사용한 표션힉을 리스트 컴프리헨션 이라고 함. a...
03ec68ab4d4d9173202c346d34313a29dbd63340
byunseob/python-study
/파이썬 코딩의 기술/chapter-06-Built-in module /47. Use decimal when precision is important/main.py
633
3.609375
4
from decimal import Decimal, ROUND_UP rate = Decimal('1.45') seconds = Decimal('222') cost = rate * seconds / Decimal('60') print(cost) rounded = cost.quantize(Decimal('0.01'), rounding=ROUND_UP) print(rounded) rate = Decimal('0.05') seconds = Decimal('5') cost = rate * seconds / Decimal('60') print(cost) rounded...
87aa6b093cf79a2d013ca7a8d2538c5af2933e54
priyansh210/Airline_Reservation_and_Management_System-python
/admin/cancel_a_flight.py
1,088
3.78125
4
import pandas as pd import menu.adminmenu as adminmenu import sql mycursor=sql.mycursor mydb=sql.mydb def cancel_flight(): df=pd.read_sql("SELECT CODE ,AIRLINE, F AS FROM_ , T AS TO_ ,DOF FROM FLIGHT",mydb) print(df) code = int(input("ENTER THE CODE OF FLIGHT YOU WANT TO DELETE : ")) code_lis...
f1006fb3f36057afe070ac8faf9f6a09de74905e
annaVR/solutions
/src/ww_coding_exercise_1.py
914
3.859375
4
#!/usr/bin/env python3 import sys def does_file_exists(path): try: f = open(path, "r") f.close() return True except Exception as e: print(e) def read_from_file(path): f = open(path, "r") text = f.read() f.close() return text def get_dictionary(text): lin...
d8b247312829600f153881f92a1bba5c36b54466
D4DeepakJain/Python
/12.py
200
3.984375
4
def fact(num): if num > 1: return num * fact(num - 1) else: return num print('enter number') a=int(input()) if(a==0): print('Not Possible') else: print(fact(a))
b09ebfb2af075572e6650fa153f8314a80db71ab
D4DeepakJain/Python
/29.py
239
3.609375
4
def check(str): a = 0 strv = 'aeiou' vowels = set(strv) for i in vowels: if i in set(str.lower()): a= a +1 if a==5: print('Accept') else: print('Not Accept') check(input())
8b49f8a95c096964da16109997761bddcaf6487b
danidassler/CloudBigData
/HOMEWORK/DanielSanzMayo-HomeworkA/P5-MeteoriteLanding/P5_reducer.py
469
3.515625
4
#!/usr/bin/python import sys previous = None sum = 0 average = 0 count = 0 for line in sys.stdin: key, value = line.split( '\t' ) if key != previous: if previous is not None: average = sum / count print (previous + '\t' + str(average)) previous = key sum = 0 ...
f63bd219bb89d94f41d8aecea52d6b87ab0ab3a7
rafaelfneves/ULS-WEB-III
/aula03/aula3.py
2,116
4.34375
4
# -*- coding: utf-8 -*- print('==============================[INICIO]==============================') #String frase=('Aula Online') #upper() - para colocar em letra maiuscula print(frase.upper()) print(frase.upper().count('O')) #lower() - para colocar em letra minúscula print(frase.lower()) #capi...
863c76edceb3d1e98acd52d7b45b114153532a1f
PreetiChandrakar/Letsupgrade_Assignment
/Day1.py
634
4.125
4
#!/usr/bin/env python # coding: utf-8 # In[4]: num=int(input("Enter Number to check prime or not:")) m=0 i=0 flag=0 m=int(num/2) for i in range(2,m+1): if(num%i==0) : print("Number is not prime") flag=1 break if(flag==0) : print("Number is prime") # In[3]: ...
348f13f98d6764633d8d2b49b2e3eb9b20d280b7
Manuel-condori/mastermind-hack-day
/codeBreaker.py
1,607
3.84375
4
#!usr/bin/python3 """ CodeBreaker class """ from constants import * class CodeBreaker: def __init__(self): """ initializes an instance """ pass def makeGuess(self, guessCount): """ returns a validated guess """ guessesLeft = MAX_NUMBER_OF_GUESSES - guessCount print('...
b72c0c78beeda2947dd05fee51dbdbb47ef0d5fa
BryceBeagle/IntelligentLanguage
/tokenizer.py
3,959
3.6875
4
def getWords(): # Position of token [line, first character (inclusive), last character (exclusive)] lineNumber = 1 for line in tester.readlines(): startChar = 1 endChar = 1 tempToken = "" # Iterate through each character for char in line: endChar +...
ca042ea9f14a92d57b1af6db4494e139c99a3423
nm4archana/parking-lot-design
/park_unpark.py
8,990
3.5
4
# Lastline parking challenge. Please see task description in accompanying PDF for details. import threading from datetime import datetime import math # define the 15 minute minimum parking interval MINIMUM_PARKING_INTERVAL_SECONDS = 15*60 # define the minimum number of spaces for each row MAXIMUM_NO_OF_SPACES_PER_ROW ...
218f8f5bc6dc213366ac36c7ae4ca39a34a0f66d
rajivsarvepalli/Python-Projects
/gmuwork/graphs_and_visuals/stack_plotter.py
2,701
3.53125
4
def bar_stack_grapher(values,bar_labels,colors,barwidth=1,legend_values=None,x_label=None,y_label=None,title=None,x_lim=None,y_lim=None,plt_show=True):#modify latetr make eay interface ''' input: values in a array that follow the format that each bar is one row\n bar_labels label what the bars and determine...
a8ffbaa72ba79b8f6ca2e90742a12814f510393d
muonictonic/poker
/Hand.py
5,546
3.609375
4
from Deck import * class Hand(object): def __init__(self, hand): self.hand = hand self.sortHand() #Sorts the hand by rank and suit def sortHand(self): self.hand.sort() #Creates a histogram of the frequencies of each rank for use #in determining the hand's type ...
4cb46d874d4f473b7275fc75e433b2e3868ecbf3
rabahbedirina/Cisco-Python
/hasattr.py
1,537
3.96875
4
"""Checking an attribute's existence""" class ExampleClass: def __init__(self, val): if val % 2 != 0: self.a = 1 else: self.b = 1 example_object = ExampleClass(2) print(example_object.a) try: print(example_object.b) except AttributeError: pass class ExampleClass:...
ba934740e3a009ec713f7c3630b71ec56d9bb699
killo21/poker-starting-hand
/cards.py
2,285
4.125
4
# -*- coding: utf-8 -*- """ Created on Wed Nov 25 17:30:27 2020 @author: dshlyapnikov """ import random class Card: def __init__(self, suit, val): """Create card of suit suit [str] and value val [int] 1-13 1 - Ace, 2 - 2, 3 - 3,..., 11 - Jack, 12 - Queen, 13 - King suit can be "clu...
0c0b9dd0631d424a7d653a38c9e6584d725240cb
sivaneshl/python_ps
/breakcont.py
220
4.0625
4
# break and continue for index in range(10): if index == 5: print("Hello") break print(index) for index in range(10): if index == 5: continue print("Hello") print(index)
87afa5b77ae77a307a71769f6b4b40cd089fcb18
sivaneshl/python_ps
/dict_compr.py
348
3.890625
4
country_to_capital = {'United Kingdom': 'London', 'France': 'Paris', 'India': 'New Delhi', 'Sri Lanka': 'Colombo'} captital_to_country = {capital: country for country, capital in country_to_capital.items()} print(captital_to_country) # duplicate keys are overwritten words = ['hi', 'hello', 'welcome', 'hey'] d = {x[0]...
141b6d72a3890b96f51838d1b4806763f0c60684
sivaneshl/python_ps
/tuple.py
801
4.25
4
t = ('Norway', 4.953, 4) # similar to list, but use ( ) print(t[1]) # access the elements of a tuple using [] print(len(t)) # length of a tuple for item in t: # items in a tuple can be accessed using a for print(item) print(t + (747, 'Bench')) # can be concatenated using + operator print(t) # imm...
a29a778e801e3ca3e9a5904fafca8310de0b0b43
sivaneshl/python_ps
/range.py
541
4.28125
4
# range is a collection # arithmetic progression of integers print(range(5)) # supply the stop value for i in range(5): print(i) range(5, 10) # starting value 5; stop value 10 print(list(range(5, 10))) # wrapping this call to the list print(list(range(0, 10, 2))) # 2 is the step argument # enumerate -...
b1460f656250aecfb1dc62d391618a46bcb93667
Wilgy/SLIScripts
/zipunzipper.py
6,014
3.8125
4
#!/usr/bin/env python """ zipunzipper.py - Given a zip directory of student submissions pulled in bulk from myCourses, unzips them and puts them in directories with the students' user names. Author: T. Wilgenbusch """ import sys import os.path from subprocess import call, check_output from os import listdir...
f23cc417d38bd75d21ff607bd109011b7eda2703
katahiromz/SphereDist
/__main__.py
1,887
3.625
4
#!/usr/bin/env python3 import __init__ as SphereDist def show_version(): print("SphereDist version 0.8.3 by katahiromz") def show_help(): print( "SphereDist --- Equal distance distribution of vertexes on a sphere or a hemisphere.\n" + "Usage: SphereDist [options] [output.tsv]\n" + ...
cd8f008e8959b50487c0c732cf0b5286116df7c9
IDDeltaQDelta/crpyt
/creator.py
1,146
3.734375
4
""" This module will be used for creating image """ from PIL import Image from randcolor import randomColor def imageCreator(): a = randomColor() b = randomColor() c = randomColor() d = randomColor() e = randomColor() img = Image.open("image/SZE3.png") # img contain image. should contain path...
9c4cd21023e4cd188ede34775b9cf9dce033ec19
imimali/rieud
/version3/game/util.py
258
3.96875
4
''' created on 06 April 2019 @author: Gergely ''' import math def distance(point_1=(0, 0), point_2=(0, 0)): """Returns the distance between two points""" return math.sqrt((point_1[0] - point_2[0]) ** 2 + (point_1[1] - point_2[1]) ** 2)
149e32d2ea991a06c3d6a7dd1c18c4cc85c3d378
CcccFz/practice
/python/design_pattern/bigtalk/Behavioral/11_visitor.py
1,326
4.15625
4
# -*- coding: utf-8 -*- # 模式特点:表示一个作用于某对象结构中的各元素的操作。它使你可以在不改变各元素的类的前提下定义作用于这些元素的新操作。 # 程序实例:对于男人和女人(接受访问者的元素,ObjectStructure用于穷举这些元素),不同的遭遇(具体的访问者)引发两种对象的不同行为。 class Action(object): def get_man_conclusion(self): pass def get_woman_conclusion(self): pass class Success(Action): def get_m...
e4892689a5d2ee4fabd2fb2cc9e0940e5f64d67c
CcccFz/practice
/python/structure_and_algorithm/04_tree.py
2,255
3.734375
4
class Node(object): def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right tree = Node(1, Node(3, Node(7, Node(0)), Node(6)), Node(2, Node(5), Node(4))) tree_bak = Node(1, Node(3, Node(7, Node(0)), Node(6)), Node(2, Node(5), Node(4))) # 层次遍历...
aee0198cb560125d50e9fdfa09543b9b092bed42
FarimaM/python-class
/EX4.py
336
3.734375
4
"chandomin rooze separi shode az saal" d = int(input('rooz: ')) m = int(input('mah: ')) y = int(input('sal: ')) days=[31,28,31,30,31,30,31,31,31,30,31,30] days_passed = 0 if y%400 == 0 or (y%4 == 0 and y%100 != 0): days[1] = 29 for months in days[:m-1]: days_passed += months days_passed += d prin...
c5b55c5da804cc7c5094b67509407820b4907656
poofcefnunsj/Unidad2POO
/claseFecha.py
907
3.515625
4
# -*- coding: utf-8 -*- """ Created on Mon Jan 20 19:30:52 2020 @author: morte """ class Fecha: __dia=0 __mes=0 __anio=0 def __init__(self, d=1,m=1,a=1900): self.__dia=d self.__mes=m self.__anio=a def formato(self, tipo='es'): '''por defecto genera ...
a6f8ed7c9dfc5d35047e5ab30b4347cd45811f46
poofcefnunsj/Unidad2POO
/destructorCicloDeVida.py
873
3.84375
4
# -*- coding: utf-8 -*- """ Created on Wed Jan 22 07:35:11 2020 @author: morte """ class A: __b=None def __init__(self, unObjetoB): self.__b=unObjetoB def __del__(self): print('Chau objeto A') class B: __a=None def __init__(self): self.__a=A(self) def _...
400cca5cff7b1b6d01f6f0bb413918b8e9a39540
jasonminsookim/multimedia_test
/classic_corners_test.py
5,144
3.859375
4
# libraries import pygame import random class Circle: """ This is our simple Circle class """ # color and radius globals WHITE = (255, 255, 255) RED = (255, 0, 0) YELLOW = (255, 255, 0) RADIUS = 50 def __init__(self, circle_number, x, y): self.color = self.WHITE s...
a46fd0382038742dc0b3df9f70b93cb22294c2e7
wboler05/AdventOfCode2020
/day09/part2.py
888
3.703125
4
#!/usr/bin/env python3 import argparse, os, sys import numpy as np from part1 import find_invalid_number, load_data def find_encryption_weakness(input_filename, preamble_size): fail_number = find_invalid_number(input_filename, preamble_size) if fail_number is not None: data = load_data(input_filename) fo...
d3febd6b9c2199638fa4b0c25b8f928a766aaacf
sajalrustagi/Wiki_Of_Words_Using_Pdf_Wiki_Parser
/WordCountProcessor.py
490
3.875
4
# Takes a fileName, parses the file whether pdf/wiki, convert it to keywords and return # the count of words import FileContentParser import TextProcessorAndTokenizer from collections import Counter def get_word_count(filename): # get the text content present in file text = FileContentParser.parse(filename) ...
048b4f0751d17ca9930ce5c5309d5351527769b6
DaniSestan/testing-algorithms-in-python
/exercises/01_basic_algorithms.py
5,103
4.125
4
# Testing the following: # - binary search # - basic performance timing # - measure performance of (deterministic) brute force algorithm versus pure random algorithm import time import random import os # common number guessing game, with the typical roles reversed # -- rather than prompting the user to guess the num...
5f843ed9fa8dc5a986db693c63056bdd9f2950d4
priyankapanda78/dataScienceProjects
/letter_count.py
657
3.71875
4
# def letter_counter(filename,to_count): # newFile=open(filename,'r') # inpFile=newFile.read() # word={} # for i in inpFile: # i=i.lower() # if i in to_count and i not in word: # word[i]=1 # elif i in to_count and i in word: # word[i]=word[i]+1 # retur...
3052ee9cd3eebd578dcc6e90f155c25e6c9d8360
VishnuGopireddy/Data-Structures-and-Algorithms
/Bit Magic/Find first set bit.py
422
3.765625
4
# author : vishnugopireddy # find first set bit from right def findfirstSetbit(num): pos = 1 # counting the position of first set bit for i in range(32): if not (num & (1 << i)): pos += 1 else: break if pos > 32: return 0 else: return pos ...
3c4fd3ce7601761a8d0e1acd9c73c8f8b7db71ad
Ryanless/CodeWars
/kyu5678/kyu6.py
5,800
3.671875
4
def queue_time(customers, n): if n == 0: return "invalid n!" queues = [[] for i in range(n)] for c in customers: queues[shortest_queue_index(queues)].append(c) return max(sum(q) for q in queues) def shortest_queue_index(queues): minSum = sum(queues[0]) index = 0 for q in...
aeb75cc44055faf3222ec8ba6aba504ce2602456
git-ysz/python
/day12-递归,高阶函数/00-递归.py
262
4.03125
4
""" 递归特点 1、函数自调用 2、必须有出口 """ # 应用:3以内数字累加和 3 + 2 + 1 def sum_numbers(n): if n == 1: # 必须存在出口,否则报错 return 1 return n + sum_numbers(n - 1) print(sum_numbers(3))
9f467500632ad90051263cb2282edacfe1258b1b
git-ysz/python
/day5-字符串/05-字符串的查找方法.py
934
4.46875
4
""" 1、字符串序列.find(子串, 查找开始位置下标, 查找结束位置下标) 返回子串出现的初始下标 1.1、rfind()函数查找方向和find()相反 2、字符串序列.index(子串, 查找开始位置下标, 查找结束位置下标) 返回子串出现的初始下标 2.1、rindex()函数查找方向和find()相反 3、字符串序列.count(子串, 查找开始位置下标, 查找结束位置下标) 返回子串出现的次数 ...... """ myStr = 'hello world and itcast and itheima and Python' # find() 函数 print(myStr...
fe00e79bf104bc4cb8dae4d4d5ba652e89780e28
git-ysz/python
/day19-学员管理系统/StudentManagerSystem/student.py
475
3.984375
4
class Student(object): """ 学员角色类 name:学员姓名; gender:学员性别; tel:学员联系方式 """ def __init__(self, name, gender, tel): self.name, self.gender, self.tel = name, gender, tel def __str__(self): return f'该学员姓名为:{self.name},性别:{self.gender},联系方式:{self.tel}' if __name__ == '__main__': _...
5c8e53bc40566dfe596ecf26e8425f65dae57a6a
git-ysz/python
/day15-继承/04-子类调用父类的同名方法和属性.py
1,549
4.3125
4
""" 故事演变: 很多顾客都希望既能够吃到古法又能吃到学校技术的煎饼果子 """ # 师傅类 class Master(object): def __init__(self): self.kongfu = '古法煎饼果子配方' def make_cake(self): print(f'运用{self.kongfu}制作煎饼果子 -- 师父') # 学校类 class School(object): def __init__(self): self.kongfu = '学校煎饼果子配方' def make_cake(self): ...
d06e4c4c9cda208bba4ea94437e71d3a25157616
git-ysz/python
/day6-列表、元组/08-综合应用-随机分配办公室.py
398
3.890625
4
""" 需求: 1、有8位老师 2、有三个办公室 3、将八位老师随机分配到三个办公室 4、验证结果 """ import random # 1. 准备数据 teachers = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'] offices = [[], [], []] # 2.分配老师到办公室 -- 取每个老师放到offices中 for name in teachers: num = random.randint(0, 2) offices[num].append(name) print(offices)
a469aa835b15c7f5e419df7d083b83d2500f2787
git-ysz/python
/day13-文件操作/02-文件的读取函数.py
919
3.8125
4
# 1、文件对象.read(num) """ num表示要从文件中读取的数据的长度(字节),如果没有传入num,表示读取文件中所有的数据 """ f1 = open('02-test.txt', 'r') # print(f1.read()) print(f1.read(10)) # 文件内容如果换行,程序底层是需要\n才能完成换行,所以\n(换行)占一个字节 f1.close() # 2、文件对象.readlines() """ 按照行的方式去读取文件所有内容,返回列表,列表的每一项为内容的一行 """ f2 = open('02-test.txt', 'r') print(f2.readlines()) # 返回结果中换...
eadb9454aeedd0dff94404ac92f9e6e43f4089c8
git-ysz/python
/day7-字典/04-字典的循环遍历.py
335
4.25
4
dict1 = { 'name': 'Tom', 'age': 20, 'gender': '男' } # 遍历keys for key in dict1.keys(): print(key) # 遍历values for val in dict1.values(): print(val) # 遍历键值对 for item in dict1.items(): print(item, item[0], item[1]) # 键值对拆包 for key, value in dict1.items(): print(f'{key}:{value}')
b5bdd6a7b80e23823c3a97def9717da822c0b3b7
git-ysz/python
/day18-模块包/00-导入模块的方法.py
565
4.1875
4
""" 模块: Python模块(module),是一个python文件,以.py结尾,包含了python对象定义和python语句。 模块能定义函数,类和变量,模块里面也能包含可执行的代码 """ import math # 导入指定模块 # from math import sqrt # 导入指定模块内的指定功能 from math import * # 导入指定模块内的所有功能 print(math.sqrt(9)) # 开平方 -- 3.0 print(sqrt(9)) # 开平方 -- 3.0 导入指定模块内的所有功能 print(pi, e) # 3.141592653589793... ...
511f5e71a988213812fe04a44b1d08bc2fb10ecf
git-ysz/python
/day17-异常处理/01-捕获异常.py
1,261
4.25
4
""" 语法: try: 可能发生错误的代码 except 异常类型: 如果捕获到该异常类型执行的代码 注意: 1、如果尝试执行的代码的异常类型和要捕获的类型不一致,则无法捕获异常 2、一般try下发只放一行尝试执行的代码 """ # 捕获指定异常类型 try: # 找不到num变量 print(num) except NameError: print('NameError:', NameError.__dict__) try: print(1 / 0) except ZeroDivisionError: print('0不能做被除数') # 捕获多个指...
8c10fa45abe684d15408e9f6fcd32d3d39106ed2
git-ysz/python
/day10-函数/05-函数的参数-关键字参数.py
500
3.71875
4
# 2、关键字参数 键=值 的方式传参 # **kw 代表多余的传入的参数,类型为字典 def user_info(name, age, gender, **kw): print(f'您的姓名是{name},年龄为{age},性别为{gender}') print(kw) dict1 = { 'age': 21, 'name': 'Yao', 'gender': '男' } list1 = ['小明', 25, '男'] user_info('Tom', age=18, gender='男') user_info('Rose', gender='女', age=20) user_inf...
a5eac9492d089bbf1658cc44bd066f662af8ce0d
git-ysz/python
/day17-异常处理/00-了解异常.py
532
3.921875
4
""" 当检测到一个错误时,解释器就无法继续执行了,反而出现了一些错误的提示,这就是所谓的"异常"。 例如:以r方式打开一个不存在的文件 语法 try: 可能发生错误的代码 except: 发生错误的时候执行的代码 注意: 1、如果尝试执行的代码的异常类型不一致,则无法捕获异常。 2、一般try下方只放一行尝试执行的代码 """ try: f1 = open('test.txt', 'r') f1.close() except: print('except') print(123)
b5f859c64a9b05aa5188a2f8b831298fd870ec7b
git-ysz/python
/day6-列表、元组/01-列表体验案例in.py
412
3.953125
4
name_list = ['Tom', 'Lily', 'Rose'] # 需求:注册邮箱,用户输入一个账户名,判断这个账户名是否存在,如果存在,提示用户,否则提示可以注册 """ 1、用户输入账号 2、判断if...else... """ name = input('请输入您的邮箱账号名:') if name in name_list: print(f'您输入的名字为{name},该用户名已经存在') else: print('可以注册')
e07b9d4a1f29f73ee0288a637eecfbf60f3d0f9b
git-ysz/python
/day6-列表、元组/11-元组数据的修改.py
324
3.828125
4
""" 元组数据不支持修改,只支持查找 """ t1 = ('aa', 'bb', 'cc', 'dd') # 出错:'tuple' object does not support item assignment # t1[0] = 'aaa' # 特例 -- 元组内部的可更改数据类型不会因为元组的特性而不可变 t2 = ('aa', ['bb', 'cc', 'dd']) t2[1][0] = 'bbb' # 更改成功 print(t2)
026950e2888b6502ea595395cdfafa80fdfd1b05
git-ysz/python
/day10-函数/04-函数的参数-位置参数.py
227
3.765625
4
# 1、位置参数 -- 传参个数和顺序必须一致 def user_info(name, age, gender): print(f'您的姓名是{name},年龄为{age},性别为{gender}') user_info('Tom', 18, '男') # user_info('Tom', 18) # 报错
4faed1f02855f8954b31445b7827c0f4a70e7842
lanzam/ISM-4402
/Line Plot.py
1,219
4.0625
4
#!/usr/bin/env python # coding: utf-8 # # Line Plot # Dataset used in an example from the book. Then, we'll add an annotation to Bob's 76 that will says "Wow!". # In[1]: import pandas as pd names = ['Bob','Jessica','Mary','John','Mel'] grades = [76,83,77,78,95] GradeList = zip(names,grades) df = pd.DataFrame(data ...
701391a6956c3c9dad884792eeb11f9074cb8657
pasalu/TicTacToe
/AI.py
464
3.609375
4
import random class AI: RANDOM = "RANDOM" def __init__(self, strategy): self.strategy = strategy def random(self, actions): """ Randomly select an action. :param actions: A list of valid actions a player can make. :return: A single action. """ retu...
1f0e2612abcb9d4e537074be265f9fca0c059c30
magnethus/Test-AL
/src/com/jalasoft/ShoppingCart/model/billing.py
1,059
3.75
4
class Billing: """metodo que devuelve el billing id de la tabla purchase""" def getBillId(self): return self.__billId def setBillId(self, billId): self.__billId = billId """metodo usado para obtener el nombre de un producto para ser mostrado en el billing detail""" def getProdNam...
c3d92fcc7f25bd9097d9a1c08a51121b84978a51
athul-santhosh/Leetcode
/274. H-Index.py
473
3.53125
4
class Solution: def hIndex(self, citations: List[int]) -> int: if not citations: return 0 index = len(citations) count = 0 citations.sort() while index > 0: if index <= citations[count]: re...
c085827df602a90b1d9c2e55ba2c8437260f7979
athul-santhosh/Leetcode
/Integer Palindrome.py
386
3.5
4
class Solution: def isPalindrome(self, x: int) -> bool: temp = x p = 0 if x<0: return False while x != 0: p =p*10 + x%10 x=x//10 if p == temp: return True else: return False ...
2f1decfec222a93f69fed1106f2f7f7b6e2ba1de
athul-santhosh/Leetcode
/83 remove duplicates .py
935
3.65625
4
def deleteDuplicates(self, head: ListNode) -> ListNode: #this solution works even if the list is sorted or unsorted but uses an #additional memory space for dictionary cur = head map = {} prev = head while cur: if cur.val in map: prev.next = cu...
b9d1034e19ba3741afde74c462cac25f58061961
lauraikoeva/cheap_airtickets_bot
/validation.py
454
3.828125
4
def validate_date(date): try: day = int(date.split(".")[0]) month = int(date.split(".")[1]) year = int(date.split(".")[2]) except: return False if day>31: return False if month>12: return False if month == 2 and year % 4 !=0 and day>28: return...
461c94991055250ad2b48ba7ef00c46d6d3eb68a
nancy-cai/Data-Structure-and-Algorithm-in-Python
/linked-list.py
2,097
4.09375
4
class Node: def __init__(self, value): self.value = value self.next = None class LinkedList: def __init__(self): self.head = None def append(self, value): if self.head is None: self.head = Node(value) return node = self.head ...
26a9c9a4c99c424e9732fa1788c495f58140fc2e
giselemanuel/programa-Ifood-backend
/modulo-1/exercicios/dicionario_jogo.py
433
3.796875
4
print('\n') fases_jogo = {'Fase1': 'Intrudução de Conceitos', 'Fase2': 'Diversidade no mundo dos negócios', 'Fase3': 'O Grande Desafio'} print(fases_jogo) print('-' * 40) print('\n') personagens = {'personagem1': 'Denise', 'personagem2': 'Paulo', 'personagem3': 'Gabriela'} print(personagens) print('-' * 40) print('\n...
9605013db14a55234a8f79a0f50833ce6f9af675
giselemanuel/programa-Ifood-backend
/modulo-1/exercicios/animal.py
1,227
4.34375
4
""" Programa VamoAI: Aluna: Gisele Rodrigues Manuel Desafio : Animal Descrição do Exercício 3: Criar um programa que: 1. Pergunte ao usuário qual aninal ele gostaria de ser e armazene em uma variável. 2. Exiba na tela o texto: "Num primeiro momento , eu gostaria de ser o <animal> 3. Pergunte ao usuário qual animal ele ...
f288d7e1e1eeef42d3a8effadcf20585cd253a4a
giselemanuel/programa-Ifood-backend
/modulo-2/exercicios/ex_class.py
1,177
3.921875
4
""" Descrição do Exercício: Escrever as classes gato, caneta e relogio, atribuindo suas características e métodos, e colocar o print no Discord. Aluno: Gisele Manuel """ # classe gato class Gato: def __init__(self, cor, sexo, raca, idade): # construtor com os atributos self.cor = cor self.sexo ...
abf1cd991eb9acb1b94912929eefeb84b471c448
giselemanuel/programa-Ifood-backend
/qualified/sem10_qualified_4.py
4,682
3.640625
4
""" Descrição Utilizando a classe Pessoa criada na atividade Parentesco entre Pessoas, crie a função encontre_os_irmaos(lista_pessoas) que recebe uma lista de objetos do tipo Pessoa e retorna uma lista apenas com o nome das pessoas que são irmãos. Se não houver irmãos na lista, a lista retornada deve ser vazia ([]). ...
fdc4109862d6acdaaf3b28b259407310172e9973
giselemanuel/programa-Ifood-backend
/qualified/sem7_qualified_3.py
2,466
4.21875
4
""" Descrição Utilizando as mesmas 4 funções da atividade Pilha - Funções Básicas: cria_pilha() tamanho(pilha) adiciona(pilha, valor) remove(pilha): Implemente a função insere_par_remove_impar(lista) que recebe uma lista de números inteiros como parâmetro e retorna uma pilha de acordo com a seguinte regra: para cada e...
3b831b55e3fc2796d52d1a3298b690cfbe41fdf7
giselemanuel/programa-Ifood-backend
/qualified/sem5_qualified_2.py
1,078
4.4375
4
# função para somar as duas listas """ Descrição Eu sou novo na programação e gostaria da sua ajuda para somar 2 arrays. Na verdade, eu queria somar todos os elementos desses arrays. P.S. Cada array tem somente numeros inteiros e a saída da função é um numero também. Crie uma função chamada array_plus_array que receb...
c39d37c177f12f17b10ff8618d40b2d9bcc00b55
giselemanuel/programa-Ifood-backend
/modulo-2/exercicios/classe_pilha2.py
704
3.75
4
class Pilha: def __init__(self): self.lista_filmes = [] def tamanho(self): return len(self.lista_filmes) def pop(self): return self.lista_filmes.pop() def push(self, item): return self.lista_filmes.append(item) # instancia o objeto na classe gisele = Pilha() # ...
e07cd5a1719c796c980b06b003c83df9d57457f3
giselemanuel/programa-Ifood-backend
/qualified/sem7_qualified_1.py
1,757
4.65625
5
""" Descrição Crie quatro funções básicas para simular uma Pilha: cria_pilha(): Retorna uma pilha vazia. tamanho(pilha): Recebe uma pilha como parâmetro e retorna o seu tamanho. adiciona(pilha, valor): Recebe uma pilha e um valor como parâmetro, adiciona esse valor na pilha e a retorna. remove(pilha): Recebe uma pilh...
003112e87a05bb6da91942b2c5b3db98d082193a
joshua-hampton/my-isc-work
/python_work/functions.py
370
4.1875
4
#!/usr/bin/python def double_it(number): return 2*number def calc_hypo(a,b): if (type(a)==float or type(a)==int) and (type(b)==float or type(b)==int): hypo=((a**2)+(b**2))**0.5 else: print 'Error, wrong value type' hypo=False return hypo if __name__ == '__main__': print double_it(3) print double_it(3....
a748f2008bc9aed1eccb121f2a909bd24ea61e4b
1raviprakash/P342-Assignment-4
/F_B_SUB.PY
747
3.515625
4
# Function for finding F&B Substitution def func(a, b): n = len(a) m = len(b[0]) # Doing forward substitution first # For getting [[0,0,0,m times],for getting this n times] y = [[0 for y in range(m)] for x in range(n)] for i in range(n): for j in range(m): s = 0 ...
37e3f89dcc79e475518d57428281a62d859ee40c
ixinit/architecture_pc
/sistem_schisl.py
688
4
4
# -*- coding: utf-8 -*- a = input("Введите число: ") b = int(input("Из какой системы счисления конверировать? ")) c = int(input("В какую систему счисления? ")) def convert_base(num, to_base=10, from_base=10): # first convert to decimal number if isinstance(num, str): n = int(num, from_base) else: ...
7ec3bd5424a62f25ab1c973a6d90a1b1fb65d9d5
felipegust/canal
/exerciciosLogica/logica2.py
271
3.734375
4
# dizer se um número é primo ou não def ehPrimo(numero): for n in range(2, numero): if numero % n == 0: print(numero, "não é primo") return print(numero, "é primo") ehPrimo(10) ehPrimo(7) ehPrimo(23) ehPrimo(30) ehPrimo(29)
e2018cb94d6973716664d60f1dd10a528ee6bc24
picopicogame/Practice_Cipher
/src/Caesar_cipher.py
1,506
4.03125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- class CaesarCipher: """シーザー暗号""" def __init__(self, plain_text, key=3): self.plain_text = plain_text self.key = key self._check_input() def _check_input(self): if len(self.plain_text) == 0: print("入力エラー。英字小文字a-zを入力して...
a7fa93eefd7c705fda3a6cd793a74afb3c902264
JacksonEckersley/cp1404practicals
/prac_02/randoms.py
275
3.71875
4
""" Line 1 produced random integers between and including 5 and 20. Line 2 produced random odd integers between 3 and 10. It would not produce a 4. Line 3 produced a random number of 15 decimal places between 2.5 and 5.5. """ import random print(random.randrange(1, 101))
5aae18dd6addca502355ec33019eaafb40f95dfb
DaniilStepanov2000/test_tasks_data_engineer
/main.py
5,626
4.0625
4
import math import os import argparse def create_parser() -> argparse.ArgumentParser: """Create parser to get arguments from console Args: None. Returns: Parser object. """ parser = argparse.ArgumentParser() parser.add_argument('name') parser.add_argument('--em_sue_name',...
eda28e4cdf9e141b4cf1f4c05dd5cbc9bd8d7e40
MarjoHysaj/betaPlan
/users_bankaccount/userstobankaccount.py
1,128
3.78125
4
class BankAccount: def __init__(self, int_rate=0, balance=0): self.int_rate=int_rate self.balance=balance def deposit(self, amount): self.balance += amount return self def withdraw(self, amount): self.balance += amount return self def display_acc...
33527a98f48b44c0711a97a7545965786d4d64d3
RobotGyal/Captian-Rainbow-Checklist
/checklist.py
4,266
3.640625
4
class colors: purple = '\033[30m' green = '\033[32m' yellow = '\033[93m' grey = '\033[37m' red='\033[31m' checklist = list() # CREATE def create(item): checklist.append(item) # READ def read(index): if in_scope(index): print(checklist[index]) return checklist[index] ...
763cf249bb354d13bc6f271456a26e56d68e2a9a
shadkaiser/demos_n_stuff
/mac_address_changer
3,066
4.3125
4
#!/usr/bin/python # The subprocess call method allows us to executed the commands in the shell # Python3 would use input instead of raw_input import subprocess import optparse import re def get_arguments(): # creates an object called parser in the OptionParser class # This will parse the arguments that are...
1b816c2a4c68ddadd488de7ea758018d61e4a43e
briennehayes/ClickbaitSummarizer
/sumbasic.py
1,497
3.578125
4
import spacy import operator from collections import Counter def sumbasic(doc, sum_length = 1): """ Implementation of sumbasic text summarization algorithm. Picks representative sentences based on high word frequencies. Args: doc (spacy.tokens.doc.Doc): spacy document to summarize sum_length (...
6102ef9f156e84f8fdea6bf7016802a5e415e103
KubaWasik/object-oriented-programming-python
/student.py
4,962
3.953125
4
class Pupil: """Klasa Pupil zawierająca dane o uczniu oraz jego ocenach i wagach""" grades = [1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0] def __init__(self, name="Nieznane", surname="Nieznane"): self.name = name self.surname = surname self.marks = {} @property de...
5340a4aab74a71aec9cf30b6f0a3487e5e9ae22e
anahitha/c-106
/graphs.py
762
3.859375
4
import plotly.express as px import csv import numpy as np import pandas as pd def data(): temp = [] sales = [] with open("icecreamdata.csv") as data: df = csv.DictReader(data) for row in df: temp.append(float(row['Temperature'])) sales.append(float(row['I...
a15f72482720e16f831f6e44bece611910eec4d5
Katakhan/TrabalhosPython2
/Aula 5/aula5.2.py
505
4.125
4
#2- Mercado tech... #Solicitar Nome do funcionario #solicitar idade #informar se o funcionario pode adquirir produtos alcoolicos #3- #cadastrar produtos mercado tech #solicitar nome do produto #Solicitar a categoria do produto(alcoolicos e não alcoolicos) #exibir o produto cadastrado nomef = input('informe o nome d...
aaca340072fbd4a1893ab6c49546aa10f5d7457c
Katakhan/TrabalhosPython2
/Aula 27/exercicios/exercicio1.py
2,616
3.953125
4
# Aula 21 - 16-12-2019 #Funções para listas from geradorlista import lista_simples_int from random import randint lista1 = lista_simples_int(randint(5,100)) lista2 = lista_simples_int(randint(5,75)) lista3 = lista_simples_int(randint(5,70)) # 1) Com as listas aleatórias (lista1,lista2,lista3) e usando as funções p...
637a4a941cd877a8a0283d65b1bf4c779960b3fe
Katakhan/TrabalhosPython2
/exercicios/exercicio2.py
3,434
3.796875
4
#--- Exercicio 2 - Input, Estrutura de decisão e operações matemáticas #--- Crie um programa que leia os dados de um cliente #--- Cliente: Nome, Sobrenome, ano de nascimento #--- Exiba uma mensagem de boas vindas para o cliente #--- Exiba um menu: Produtos alcoolicos e Produtos não alcoolicos, Sair #--- Caso o cliente...
e1602fcc8c1c145b7a8cdc495c0f26ff657f42d8
Katakhan/TrabalhosPython2
/Exercicios Modulo 16/Exercicio 2.py
517
3.90625
4
#--- Exercício 2 - Funções - 1 #--- Escreva uma função que leia dois números do console #--- Armazene cada número em uma variável #--- Realize a soma entre os dois números e armazene o resultado em uma terceira variável #--- Imprima o resultado e uma mensagem usando f-string (módulo 3) n1 = '' n2 = '' r = '' def ler (...
34fb94928b4521a02ee32683fcc1369b36a03697
Katakhan/TrabalhosPython2
/Aula59/A59C1.py
1,478
4.3125
4
# ---- Rev Classe # ---- Métodos de Classe # ---- Método __init__ # ---- Variáveis de classe # ---- Variáveis privadas # ---- Metodos Getters e Setters class Calc: def __init__(self, numero1, numero2): # Variável de classe self.__n1 = numero1 self.__n2 = numero2 self.__resultado = 0...
60f6598ba438e4ebb1d8210d5ebf7a0a9557a2f5
Katakhan/TrabalhosPython2
/Aula 15/Ex 1 .py
1,081
3.8125
4
marca = input('Informe a marca da cerveja') teor = float(input('informe o teor alcoolico da cerveja')) tipo = input('Informe o tipo da cervaja(Alcoolico(1) e não alcoolico (0))') cerva_dicionario = {'marca':marca, 'teor':teor, 'tipo':tipo} def salvar_cerva(cerva_dicionario): arquivo = open ('Banco de cerva.txt',...
bbadb83a9436c4fb543e3a703638449549af44e6
Katakhan/TrabalhosPython2
/Aula59/Classe.py
501
4.15625
4
#---- Métodos #---- Argumentos Ordenados #---- Argumentos Nomeados def soma(n1,n2): resultado = n1+n2 return resultado res = soma(10,20) print(res) def multiplicacao(n1,n2,n3): resultado = n1 * n2 * n3 return resultado res = multiplicacao(10,20,30) print(res) def subtracao(n1,n2,n3): resultad...
ac8a36d86281a5bcec872f04ce37a10a9600bea5
Katakhan/TrabalhosPython2
/Aula 16/Aula 16.py
431
3.640625
4
## 29/11/2019 - Aula 16 ## ## Cadastro de playlist ## Lendo Musica, Artista E album from Faixa import faixa,salvar,ler musica = input('Informe o nome da Musica \n') artista = input('Informe o nome do Artista \n') album = input('Informe o nome do Album \n') faixa = faixa(musica,album,artista) salvar(faixa) lis...
bbb99b2724b90a7bdf25c8a63d2d073a653089f5
pjy08062/Winterschool2018
/자동다각형2.py
157
3.546875
4
import turtle t=turtle.Turtle() t.shape('turtle') n=int(input('몇각형을 그리시겠어요?(3-6):')) for i in range(n): t.fd(100) t.lt(360/n)