blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
308649ded4b51d883a1b4e258068c8bf583f07a5
karandevgan/Algorithms
/SortLinkedList.py
1,618
4
4
import pdb class Solution: # @param A : head node of linked list # @return the head node in the linked list def sortList(self, A): length = self.getLength(A) if length == 1 or length == 0: return A mid = length / 2 mid_node = A for i in x...
7cf99d340eaeb32c073159f44278f3465d9d8f9c
KyleFontaine/animals
/src/Dog.py
462
4
4
class Dog: def __init__(self, name): self.name = name # A simple class # attribute attr1 = "mammal" attr2 = "dog" # A sample method def Bark(self): print('Woof from', self.name) return self.name if __name__ == "__main__": print("I'm called from Dog.py") ...
3f0aef3e19c67e77d149ce9a02e48f3556729679
ASMcap/url_shortner
/url_shortner.py
347
3.609375
4
import pyshorteners import time # Introduzir o link link = input(" link: ") shortener = pyshorteners.Shortener() # Variável x = shortener.tinyurl.short(link) # Imprimir variável print(x) time.sleep(90) # biblioteca python para encurtar os links # biblioteca time para pausar o programa 90 segundos para po...
aa96a011cd60547fa8c448aa49d6b586c45401c9
Chenzk1/leetcode
/leetcode/61.旋转链表.py
1,648
3.625
4
# # @lc app=leetcode.cn id=61 lang=python3 # # [61] 旋转链表 # # @lc code=start # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def rotateRight(self, head: ListNode, k: int) -> ListNode: ''' 一次移一位,移k次...
4170eba692cdf0e66643ddb0cf48c3264dd68053
albertsuwandhi/Python-for-NE
/Misc/SQLITE3/simple_db_operation.py
1,828
3.703125
4
#/usr/bin/env python3 from dbutils import db_connect import sqlite3 import os import sys conn = db_connect("db_router.sqlite3") #SELECT and print the records try: print("Query INVENTORY Table and print the results") print("-"*50) cursor = conn.execute("SELECT IP, LOCATION, BRAND, USERNAME, PASSWORD from INV...
4a36d92befb52bd11a4e2844e6e3f369c1bd55f6
jaychsu/algorithm
/leetcode/215_kth_largest_element_in_an_array.py
341
3.59375
4
from heapq import heappop, heappush class Solution: def findKthLargest(self, A, k): """ :type A: List[int] :type k: int :rtype: int """ heap = [] for a in A: heappush(heap, a) if len(heap) > k: heappop(heap) ...
8f54155a36effd3c0842668f5fc464f26ece7569
gabriellaec/desoft-analise-exercicios
/backup/user_041/ch74_2019_04_04_18_16_35_774192.py
209
3.53125
4
def conta_bigramas(palavra): i=0 dic={} while (i<len(palavra)-1): bi=palavra[i]+palavra[i+1] if bi in dic: dic[bi]+=1 else: dic[bi]=1 i+=1 return dic
ddeaad4ec26e6af42c8800c021f8ba9fbbb21ec1
kirigaikabuto/Python13Lessons
/lesson9/1.py
127
3.515625
4
import os # tuple data = input() # Hello # 01234 print(data[0]) print(len(data)) for i, v in enumerate(data): print(i, v)
25fa32cf42e8f720202bd8e72fb2709822c406bf
851984709/Junjie-Hu
/code/python/study/Python/5.分支.py
324
3.875
4
score = int(input('请输入分数\n')) if (score > 100) or (score < 0): print('输入错误') elif score >= 90: print('A') elif score >= 80: print('B') elif score >= 70: print('C') elif 70 > score >= 60: print('D') elif 60 > score >= 0: print('E') else: print('输入错误')
c84b7312302b0ea2093b16420a3146f4bbe4d87c
indranik/Python-Challenge
/PyPoll/main.py
2,771
3.890625
4
# -*- coding: utf-8 -*- """ Created on Wed Feb 21 21:32:56 2018 @author: Ind """ import os import csv #candidates = {"name": "Candidate", "Votes": 0} #listResults=({}) List of candidates listResults = [] numVotes = 0 with open("election_data_1.csv","r")as csvfile: csvreader = csv.reader(csvfile) next(csvrea...
f2afeed00baa0dd404bd6696a26937f53f969dcf
abenitezherrera/TechnicalTestScripts
/Exercise1.py
938
4.21875
4
user = {'document': 'rx','email':'red@gmail.com','address': 'ST JOHN 21 AR'} def harmonizer(user): """Returns a list of emails of a user""" #This block of code is to validate if there any emails in the source, so we can include them in a list and then return the list of emails of a user #This could include a l...
834c05f26e8e270b64397c0d48cb15f7975a46a6
birnbera/holbertonschool-machine_learning
/math/0x00-linear_algebra/3-flip_me_over.py
380
3.953125
4
#!/usr/bin/env python3 """Transpose a list-based matrix""" def matrix_transpose(matrix): """Perform matrix transpose""" nrows = len(matrix) ncols = len(matrix[0]) transpose = [[0 for _ in range(nrows)] for _ in range(ncols)] for i in range(len(matrix)): for j in range(len(matrix[i])): ...
1bd066ee9f3c3150b8b1a60eb236afb9d50a7323
wintangd/day-2
/user input.py
133
3.921875
4
# name = input ("Enter name : ") # print("Your name is : " + name) grade = input ("Enter grade : ") print("Your grade is : " + grade)
2460957f17f2d610d733252793095498b502a99e
frederichtig/python-chat-server
/client/client.py
3,320
3.9375
4
#/bin/python # This is a simple chat client used to test the chat server. # You can open as many instances of it as you want. import sys import socket from threading import Thread class Client(Thread): def __init__(self, port=888, host=socket.gethostname(), name=raw_input, output=sys.stdout.write): """ ...
72deb5a607adfdcaa3642a100e56dea9a7719012
Rohanarekatla/python-basics
/#SWAPING.py
329
3.671875
4
a = 3 b = 6 #method-1 temp = a a = b b = temp print(a) print(b) #method-2 c = 9 d = 2 c,d = d,c print(c) print(d) #method-3 p = 8 q = 5 p += q q = p - q p = p - q print(p) print(q) #method-3 p = 8 q = 5 p ^= q # ^ = XOR q = p ^ q p = p ^ q print(p) pri...
52d5e77b312d54a894dd5ecc84853316ad07cb58
akshat7/Codechef_Python_Solutions
/ERROR.py
147
3.5
4
import re t = input() for _ in range(t): s = raw_input() pattern = r'(101)|(010)' if re.search(pattern, s): print "Good" else: print "Bad"
431f07069ab55bac254abc0f8254f2cc254bd2ca
congzhang2018/Course_project
/tencent_test1.py
1,846
3.609375
4
# #coding=utf-8 # # 本题为考试单行多行输入输出规范示例,无需提交,不计分。 # import sys # def lcm(alist): # greater = max(alist) # length = len(alist) # counter = 0 # # print(counter, length,greater) # while(True): # for i in alist: # if (greater % i == 0): # counter += 1 # if count...
6abd2cd29407c3d6f5a684e46667ba2e0bd72432
johnsanc/wb-cohort3
/week-1/surrounded-regions.py
1,142
3.578125
4
from collections import deque class Solution: def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ if not board: return q = deque([]) rows, cols = len(board), len(board[0]) ...
09e3dde912c9b1129a5e2db627aee12fc0d07cd3
EraSilv/day2
/day5_6_7/calcu.py
747
4.0625
4
# num1 = input(' give 1st number:') # num2 = input(' give 2nd number:') # num1 = int(num1) # num2 = int(num2) # print(type(num1)) # print(type(num2)) # print('sum:', num1 + num2) # print('sum:', num1 / num2) # print('sum:', num1 - num2) # print('sum:', num1 * num2) # print('sum:', (num2 / num2) * num1 + num2) # pr...
d65c7d463c28e3c81e4293a2a152f5e7eb7fad43
brunofonsousa/python
/pythonbrasil/exercicios/listas/LT resp 17.py
1,616
4.21875
4
''' Em uma competição de salto em distância cada atleta tem direito a cinco saltos. O resultado do atleta será determinado pela média dos cinco valores restantes. Você deve fazer um programa que receba o nome e as cinco distâncias alcançadas pelo atleta em seus saltos e depois informe o nome, os saltos e a média dos sa...
cc8e66798d50a665e933e57aef6bdc6b0524c079
YavorYanchev/Programming101-Python
/week01/firstday.py
1,176
3.796875
4
def sum_of_digits(n): return sum([int(i) for i in str(n) if i != "-"]) def to_digits(n): return [int(i) for i in str(n)] def to_number(digits): return int(''.join(map(str, digits))) def fact_digits(n): total = 0 for index in str(n): fact = 1 for x in range(1, int(index)+1): ...
9ffd4ac1cf30a6c2ebb122a1459f504f924a0521
rheehot/Algorithm-53
/Programmers/Level1/수박.py
246
3.796875
4
# ( if가 참일때 값 ) if (조건문) else (if가 false일때 값) def solution(n): # return ('수박'*n) [:n] -> 이게 더 느림 return ('수박'* int(n/2) ) if n % 2 == 0 else ('수박'* int(n/2) ) + '수' n = 3 print(solution(n))
5855c7857ddb5d06e0aa792ba1886907bff13eec
m4tux/py-tools
/K/py-tools/K/py-tools/K/py-tools/Basic/regexp.py
1,512
3.546875
4
import re print "***************************** REGULAR EXPRESSION ***************************" def reghelp(): f = open("regexp.help","r") contents = f.read() print contents reghelp() print "************************************************************************************...
0a383a62c24064229bdc84cf69a22e34b66fc023
cvtoro/Coursework
/cs262Algorithms/quiz03/graphClass.py
1,404
3.65625
4
#Cecilia Villatoro #COSC 262 #class which represents an undirected or directed graph in adjacency list format class Graph: def processString(self, graph_string): result = ["","","",""] graphRows = graph_string.splitlines() i = 0 numVertices = 0 adjacency_list = [] for line in graphRows: line = lin...
b7d524a83205c2e153283b7b7933828becf05366
daniel-reich/turbo-robot
/pfn6QRn6eiTHEPpSs_23.py
751
3.796875
4
""" Python got _drunk_ and the built-in functions `str()` and `int()` are acting odd: str(4) ➞ 4 str("4") ➞ 4 int("4") ➞ "4" int(4) ➞ "4" You need to create two functions to substitute `str()` and `int()`. A function called `int_to_str()` that converts **integers into strings** and a...
f5f488fdec183ca8ec1fe177f900179abce5e85d
tony-andreev94/hackerrank
/list_comprehensions.py
524
3.765625
4
# List Comprehensions # https://www.hackerrank.com/challenges/list-comprehensions/problem max_x = 1 max_y = 1 max_z = 2 n = 3 combinations = [[x, y, z] for x in range(max_x+1) for y in range(max_y+1) for z in range(max_z + 1) if not x + y + z == n] print(combinations) # without comprehension: all_combinations = [] ...
a7d98727a67558e980e58e63ca594dbf6c2952a3
Timofeitsi/Repo_dz
/lesson3/less3_1.py
1,687
4.25
4
""" Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление. Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль. """ def my_f1(): while True: try: x = int(input("Введите делимое: ")) break except ValueErro...
60503bafb6b2587a68d83fe3663277cc24386780
josecoene/ufms
/Listas Nota/bloggo.py
884
3.609375
4
def main(): while True: try: texto = input() resultadoFinal = "" comeco = 0 fim = 0 for i in range(len(texto)): if texto[i] == "_": if comeco == 0: resultadoFinal += "<i>" ...
705685358b8970f71359e71e904a5bc35afa2335
henry3556108/coding365
/test/線性回歸.py
945
3.578125
4
import matplotlib.pyplot as plt import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression import numpy as np from io import StringIO from sklearn import preprocessing def foo(x): return 1.2 * x + 0.8 + 0.5 * np.random.randint(10) x = np.linspace(50,...
4f0b1dc410f30daf7a562f2e1a9cff4babd8de84
ousmanabakar/PhythonExercises
/func_args.py
466
4.03125
4
def main_func(operation_name): def addition(*args): result1 = 0 for i in args: result1 += i return result1 def mult(*args): result2 = 1 for i in args: result2 *= i return result2 if operation_name == "addition": r...
704912621fb8751bb9e6daa35239feb4d80c1481
ZJTJensen/Python-class-work
/findingchar.py
290
3.6875
4
word_list = ['hello','world','my','name','is','Anna'] new_list=[] char = 'o' num = 0 position = 0 for num in range(0, len(word_list)): for position in word_list[num]: if position == char: new_list.append(word_list[num]) break print new_list
deba08549ca3b707142eaca0b649669727adc645
nikhil-garg-rram/badcrossbar
/examples/plotting/3_different_variables.py
2,081
3.6875
4
import badcrossbar # The main purpose of the plotting module is for plotting currents and voltages # in the branches and on the nodes of the crossbar, respectively. However, # these functions can accept any numeric arrays and thus plot arbitrary # variables. This example shows how to plot the percentage change in curr...
ad0f62e11dea825a3e8fdcad58bb340efac07ea0
he-sends-regards/Brain-Games-Python
/brain_games/games/calc.py
469
3.9375
4
import random DESCRIPTION = 'What is the result of the expression?' def make_question(): num1, num2 = random.randint(0, 10), random.randint(0, 10) operations = { 'sum': ('{} + {}'.format(num1, num2), str(num1 + num2)), 'diff': ('{} - {}'.format(num1, num2), str(num1 - num2)), 'mult':...
618268841f41b0c2afe3214a528e895e2888c2f3
Matthew-Reynard/snake
/Graphs/graph.py
5,662
4.03125
4
""" Broken axis example, where the y-axis will have a portion cut out. """ import matplotlib.pyplot as plt import numpy as np import time ''' # 30 points between [0, 0.2) originally made using np.random.rand(30)*.2 pts = np.array([ 0.015, 0.166, 0.133, 0.159, 0.041, 0.024, 0.195, 0.039, 0.161, 0.018, 0.143, 0....
3cfc08f0d91f1d5dcef318f58b98a1fb5477cb82
multimentha/Advent-of-Code-2019
/5 - Sunny with a Chance of Asteroids/part_1.py
4,143
4.0625
4
"""Run the diagnostic test interactively, so that you can see every single instruction at work.""" from diagnostic_program import program as program VERBOSE = False # display details on how instructions are processed INTERACTIVE = False # set to true to step through the program instruction by instruction # keep trac...
0fe39111c3a7f19e750ea15f6a527a5347fb0217
DipalModi18/CrackingTheCodingInterviewPractice
/recursion/reverse_string.py
1,193
3.8125
4
def reverse(s): if len(s) == 1: return s return reverse(s[1:]) + s[0] class Solution(object): def reverseString(self, s): """ :type s: List[str] :rtype: None Do not return anything, modify s in-place instead. """ if len(s) == 2: return [s[1], s[0...
7e77a527e13d3ee52eb6d9fcc242f69d6b4d1442
kellysteele168/Introduction-to-Computer-Science
/HW5/hw5Part3.py
4,148
3.84375
4
''' The program moves the trainer for a given amount of simulations to determine various statistics. Additionally, it tracks a grid of caught and missed pokemon. Kelly Steele 3/8/2018 ''' import random def move_trainer(move): # function moves trainer directions=['N','E','S','W'] direction_choice= rand...
575d5e6c879ac2f05a1e342bfc5736cf96cdfcc6
ganasn/LPTHW
/ex47/LPTHW/ex20.py
642
3.515625
4
# Exercise 20 - Functions & Files from sys import argv script, src_file_name = argv # argument 'f' is a file object def print_all(f): print f.read() def rewind(f): f.seek(0) def print_one_line(line_number, f): print line_number, f.readline() src_file = open(src_file_name) print "Printing ...
36472762db8474a1c894b3a0275575ef511c08ac
KimMooHyeon/Algorithm-Studying
/백준/Gold/17609. 회문/회문.py
1,920
3.578125
4
num = int(input()) if num == 0: print(1) myFlag = 0 similarFlag = False def getAnswer(left, right, chance): global similarFlag notFlag = False while 0 <= left and right >= left: # print(f'{myString[left]} {myString[right]}') if myString[left] == myString[right]: ...
1e02a006c319cb7e379a94e11827369da403d5f7
Nipuncp/lyceaum
/ex/hang_man.py
777
3.890625
4
import random def secret_word(): wordfile = "/usr/share/dict/words" min_length = 6 good_words = [] f = open(wordfile) for i in f: word = i.strip() if word.isalpha() and len(word) >= min_length: good_words.append(word) f.close() return random.choice(good...
b0d8b5075696081c63da3d5d8d44517ad238ac57
rmassoth/pokedex-plus
/pokedex/editor.py
684
3.65625
4
import sqlite3 cnx = sqlite3.connect("./pokedex/pokemon.db") cursor = cnx.cursor() create_table = "CREATE TABLE IF NOT EXISTS pokemon(id INT PRIMARY KEY, name TEXT, type TEXT);" try: cnx.execute(create_table) except: print("Some error occured") def add_pokemon(pokemon): sql = "INSERT INTO pokemon(`name`, `type`) ...
99255b10d40551812c2ac3b3ab58f615086881e4
rakesh95136/python
/CLASS/file_ope1.py
2,173
4.15625
4
import os import shutil from os import walk ''' 1) Create a directory with name "newdir" and create a file "templo" in the new dirctory "newdir" 2) Rename a file in a particular directory Rename all the files in particular folder in a your computer; take backup before you re name the files. 3) List all the files from...
a0d6dec8fc702cf1e9d8fb564356e985dd5e81a4
Giorgiobientinesi/Twitter-elaboration
/Twitter_elaboration.py
3,641
3.5625
4
import pandas as pd import csv import tweepy # Twitter API credentials consumer_key = ## consumer_secret = ## access_key = ## access_secret = ## def get_all_tweets(screen_name): #this function return all the tweets # Twitter only allows access to a users most recent 3240 tweets with this method auth = tw...
ba46a4e914ded58a0551fd53e242607834ab646e
Ting-Shieh/Python_2020y
/io/struct_send.py
1,369
3.578125
4
""" udp 從客戶端輸入 學號 姓名 年紀 分數 將訊息發送給服務端 在服務端寫入到一個無見裡面 每一個學生訊息一行 ===> 客戶端 """ import struct from socket import * server_addr = ('127.0.0.1', 8888) class Student: def __init__(self,id=None, name=None, age=None, score=None): self.id = id self.name = name self.age = age self.score = s...
9887b642569c8a8c86c020361731d309f9df5b91
abbluiz/python-class
/python-quiz.py
3,311
3.671875
4
def checkEnteredPin(correctPin, enteredPin): return (correctPin == enteredPin) def withdrawl(currentBalance, withdrawlAmount): if (currentBalance - float(withdrawlAmount)) < 0.00: return currentBalance else: return (currentBalance - float(withdrawlAmount)) def didUserEnteredValidWithdrawl...
c8df2c16465f3dc40867b10fa204bfcd6460dfd4
Appleriot/Appleriot
/aliens.py
1,074
3.875
4
alien_0 = {'color':'green', 'points': 5} alien_1 = {'color': 'red', 'points': 10} alien_2 = {'color': 'yellow', 'points': 15} aliens = [alien_0, alien_1, alien_2] for alien in aliens: print(alein) # Makes a empty list of alien alien = [] # Make 30 alien for alien_number in range(30): new_alien = {'col...
939262fc1f0ddcab56cfda6c5e5a5d8a7308751b
tanpv/awesome-blockchain
/bitcoin_python/bitcoin_curve_and_field.py
1,803
3.65625
4
""" Define a finite field for bitcoin base on FiniteField class Define a elliptic curve for bitcoin base on Point class """ from finite_field import FieldElement from elliptic_curve import Point # prime field applied for bitcoin P = 2**256 - 2**32 -977 class S256Field(FieldElement): def __init__(self, num, pri...
ae5e8fbbf72da0a0e48bda0111a47b4be0f6340f
v0001/python_jw
/Basic/if test/if test_exam2.py
241
3.890625
4
# 정수를 입력받아 0 이면 "zero" 양수이면 "plus" 음수이면 "minus" 라고 출력하는 프로그램을 작성하시오. a1 = int(input()) if a1 == 0: print('zero') elif a1 > 0: print('plus') else: print('minus')
ca1507ecfc36acadb198f6fccd64c23385a9370a
TrulyPV/ZED-Tracking
/CNN.py
9,081
3.625
4
""" CNN.py Implement the CNN class. Uses Keras TensorFlow. Used in ZED Human Tracking algorithm. YOLO will produce bounding boxes, this CNN will distinguish target from others CNN Architecture Input Shape = 64x64x3 Conv2D 16 filters MaxPool Conv2D ...
d866dcc6225419557b1915ecd6783f5f1c56a5a0
caravan4eg/python_kata
/capitalize.py
302
3.71875
4
# capitalize #!/bin/python3 import math import os import random import re import sys # Complete the solve function below. def solve(s): for x in s.split(): s = s.replace(x, x.capitalize()) return s print(solve('alex piter 4ivanov')) print('132 456 Wq M E' == '132 456 Wq M E')
d21d0febfa5e6df998d26247aa9f572aa73720dd
ElvarThorS/Forritun
/9.3.2020/basic1.py
574
4.21875
4
#Algorithm: #1 make a loop and put input into a variable #2 loop around and compare the inputs and delete the lower input #3 repeat until negative number is input #4 print highest number and end program num_int = int(input("Input a number: ")) # Do not change this line # Fill in the missing code max_int = 0 while n...
eb98f9bb1536beaac46954ad46b62452b6d156c9
Hairidin-99/Korolevstvo-programmistov
/chislo.py
141
3.828125
4
a = int (input("vvedite pervoe chislo :")) b = int (input("vvedite vtoroe chislo :")) if a > b : print (a+b-1) else : print (a*b/1)
6dad6578bf9f77d699478bf4d9fd2ff8749c3c51
GourBera/ProjectPython3
/ProjectPython3/DataScientistFoundationsNanodegreeProgram/PyTricks/modelu2.py
3,458
4.3125
4
''' Created on May 21, 2018 @author: berag ''' if __name__ == '__main__': pass ''' Use a list comprehension to build a list called even_squares in the editor. Your even_squares list should include the squares of the even numbers between 1 to 11. Your list should start [4, 16, 36...] and go from there...
b94177d5134c59dea38cc6f740603d7f2cbab379
gbaghdasaryan94/Kapan
/HaykAmirjanyan/classroom/Lists/lhw3.py
189
3.96875
4
# Given an array of numbers. Find the maximum element in array.Whitout use max function. arr = [1,10,2,2,3,1,4,43,-112,0] n = arr[1] for i in arr[1:]: if i > n: n = i print(n)
4ae5640510cb67ca8871c102a55c838ee0557f57
Logan-Greenwood/cacs_projects
/censorship-project/censor-dispenser.py
1,409
3.65625
4
email_one = open("email_one.txt", "r").read() email_two = open("email_two.txt", "r").read() email_three = open("email_three.txt", "r").read() email_four = open("email_four.txt", "r").read() # remove single censored word from text def censor_a_word(text, word): return text.replace(word, "redacted") # print(censor_...
eb6abbe43ed8ffce9c3fa24fcf63c16a5db6fddb
rishabh-22/Problem-Solving
/island_problem.py
836
3.75
4
from typing import Tuple, List def mark_neighbours(matrix: List, pos: Tuple): r, c = pos if r < 0 or r >= len(matrix) or c < 0 or c >= len(matrix[0]) or matrix[r][c] != 1: return matrix[r][c] = 0 mark_neighbours(matrix, (r + 1, c)) mark_neighbours(matrix, (r - 1, c)) mark_neighbours...
0dc4808035f48dccd37d69d11c5ed0c3a5eb4b8e
akashvacher/AdventOfCode2019
/day2/day2.2.py
978
3.6875
4
#!/usr/bin/env python import sys def compute(a): """ Accept an intcode program as a list of integers and return the final output of running the program """ it = iter(a) while True: op = next(it) # Invalid opcode check if op not in (1, 2, 99): raise ValueErr...
f5ac8899d0b89ee7a03e23d51ddce2eab6d56b5c
Smitraj007/smitraj-hub
/Query bot for marine assessment/Tredence_practise_chatbot.py
4,687
3.953125
4
############# Using normal rule-based approach ################## import time # Dummy question-answer pairs knowledge_base = { "Q1": "What is the sea worthiness criteria for vessels?", "A1": "The sea worthiness criteria for vessels include factors such as structural integrity, equipment functionality, ...
1ba78b0607846888e87ff1dea9a8a8679b0f2000
Mohega/f-rF
/F,rF encryption.py
1,440
3.921875
4
import time def factorial(): n = input("Number (factorial: ") q = 0 r = 1 a = len(n) n = n.replace(" ", "") d = [a+b for a,b in zip(n[::2], n[1::2])] print (d) for i in d: i = int(i) for l in range (1,i): i = l * i ...
6f56945ef8106b681515426615e3a1afa33f4fe2
PollobAtGit/python-101
/Official Documentation/An Informal Introduction to Python/100/101.py
1,638
4.03125
4
value = 10 valueTwo = 20 print(value + valueTwo) needTrimming = " left trim : right trim " print(needTrimming.lstrip()) print(needTrimming.rstrip()) print(needTrimming.strip()) exponent = 3 ** 9 print(exponent)# 19683 # Fun with string print('python auto concat' ' magic') # This is useful print('python auto' ...
2c371f34d0d64a4f25db30a38f96fa9bd0496ba9
vijama1/word_count
/word_count.py
506
4.03125
4
#opening a file for word count file=open('test_data.txt','r') #creating a empty dictionary dict={} count=0 #processing data line by line for line in file: #processing data word by word for word in line.split(): #checks if word is in dictionary or not if word not in dict.keys(): dic...
e830aa64333c59a521df50b74620a67b866cbf11
zxpgo/Python
/071canvas画椭圆.py
355
3.53125
4
from tkinter import * root = Tk() w = Canvas(root, width=200, height=100, background='white') w.pack() w.create_rectangle(40, 20, 160,80, fill='green', dash=(4,4))#画矩形 #w.create_oval(70, 20, 130, 80, fill='pink')#画圆形 #w.create_oval(40, 20, 160, 80, fill='pink')#画椭圆 w.create_text(100, 50, text="FishC"...
05eabf5fc800fca936528dc9431440c163f62da2
hyeji-K/python_lab
/day2/function_return.py
608
3.671875
4
def add(a, b): print(f"더하기 {a} + {b}") return a + b def subtract(a, b): print(f"빼기 {a} - {b}") return a - b def multiply(a, b): print(f"곱하기 {a} * {b}") return a * b def divide(a, b): print(f"나누기 {a} / {b}") return a / b def even_or_add(n): if n % 2 == 0: print("짝수") ...
3e56fee28c5d8af89a3df26174022bde05bbdc22
scans/start_py
/function.py
1,378
3.734375
4
# encoding=utf-8 def my_abs(x): if not isinstance(x, (int, float)): raise TypeError('bad operand type') if x > 0: return x else: return -x print my_abs(-100) # print my_abs('A') def many_return(): lat = 1 lng = 2 return 1, 2 print '分别打印两个返回值' x, y = many_return() ...
d307f25080e03fc73937b6b7e5cec30a6c9ed6de
shanester85/Murach-Python-Programming
/ch02/test_scores.py
1,443
4.4375
4
#!/usr/bin/env python3 # display a welcome message print("The Test Scores program") print() print("Enter 3 test scores") print("======================") # get scores from the user total_score = 0 # initialize the variable for accumulating scores score1 = int(input("Enter test score: ")) # input for in...
802e8f4788d19d04c20767160ceabdd020340882
oneshan/Leetcode
/accepted/051.n-queens.py
1,432
3.65625
4
# # [51] N-Queens # # https://leetcode.com/problems/n-queens # # Hard (30.48%) # Total Accepted: # Total Submissions: # Testcase Example: '4' # # The n-queens puzzle is the problem of placing n queens on an nxn chessboard # such that no two queens attack each other. # # # # Given an integer n, retu...
517948ba40dcc6369a4532b88d5de19f40c800e1
miguel-dev/holbertonschool-higher_level_programming
/0x01-python-if_else_loops_functions/100-print_tebahpla.py
152
4.125
4
#!/usr/bin/python3 for c in reversed(range(97, 123)): if (c % 2): # Evaluates if it's even c -= 32 print("{}".format(chr(c)), end="")
f97f1363363f6532cce76283ba94908efd5ced5c
labesoft/top-projects
/hanggame/word.py
4,737
4.15625
4
"""The word handling logic of The Hangman Game ----------------------------------- About this module ----------------- This module handle the word behavior of The Hangman Game. It choose a word and then, masks and unmasks the letters of the word. It is also designed to reveal a word only once making it impossible to u...
1e743136939e7b2551415b82172e2a7bc31735c4
gabriellaec/desoft-analise-exercicios
/backup/user_016/ch55_2020_05_13_22_30_34_447979.py
462
3.65625
4
def positivo(lista10): lista0 = [] for i in lista10: if i<0: i = i*-1 lista0.append(i) else: lista0.append(i) pass return lista0 def encontra_maximo(lista): lista1 = positivo(lista[0]) lista2 = positivo(lista[1]) lista3 = positivo(l...
e97fc6e0c43e4466b17719da68e1927a8b0adbc4
YAtOff/python0
/archive/2017/tasks/games/hangman/game.py
954
3.796875
4
import functools import turtle import hangman import words def write_word(word): writer = turtle.Turtle() writer.penup() writer.goto(100, 200) writer.write(word, font=('Arial', 16, 'bold')) writer.hideturtle() # Иницилизация original_word = words.get_random_word() word = '_' * len(original_word...
a0fc185473a5b587c45a9595cedb1d8461049bad
ivan-yosifov88/python_fundamentals
/list_basic_exercise/easter_gifts.py
858
3.703125
4
names_of_the_gifts = input().split() command = input() while not command == "No Money": commands = command.split() if commands[0] == "OutOfStock": for index in range(len(names_of_the_gifts)): if commands[1] == names_of_the_gifts[index]: names_of_the_gifts[index] = None e...
0f6bdeb3cc63e25052e3fc89794727331a4ac0a8
lizhihui16/aaa
/pbase/day19/lianxi.py
2,368
3.953125
4
#  2.自己写一个MyList,实现重写len,str,让MyList类型的对象变为可迭代对象 class MyList: def __init__(self,iterable=()): self.data=[x for x in iterable] def __repr__(self): return "MyList(%s)"%self.data def __len__(self): '''要求必须返回迭代器''' return self.data.__len__()#返回迭代器 def __str__(self): ...
cca7aa753a50bae05cbc658e9d38829cc365d2bb
mspontes360/Programacao-Python-Geek-University
/section5/exercicio08.py
590
4.125
4
""" Faça um programa que leia 2 notas de um aluno, verifique se as notas são válidas e exiba na tela a média destas notas. Um nota válida deve ser obrigatoriamente, um valor entre 0.0 e 10.0, onde caso a nota não possua um valor válido, este fato deve ser informado e o programa termina. """ first_note = float(input("I...
d73e75fc9a5ec3878169b0453cc72ab7c1e34992
DeanHe/Practice
/LeetCodePython/ValidSudoku.py
2,505
3.859375
4
""" Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules: Each row must contain the digits 1-9 without repetition. Each column must contain the digits 1-9 without repetition. Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 with...
0b8cb2ca14e3e5a2f1a461fece73a1802d5857c6
julnarot/FundamProgram
/python/ejemplos/prac4.py
319
3.96875
4
#coding: utf-8 #se necesita obtener el promedio simple de un estudiante a partir de tres notas parciales #ENTRADA not1 = input("Ingrese Primera Nota: ") not2 = input("Ingrese Segunda Nota: ") not3 = input("Ingrese Tercera Nota: ") #PROCESO prom = (not1 + not2 + not3) / 3 #SALIDA print "El Promedio Es: %s" % prom
a52e4a33831ad9ac8c4775e9a3d8f0007754c3e8
pablomdd/Computational-Thinking-Python
/c23-funciones_como_objetos.py
712
4.125
4
# Funciones como argumentos de otras funciones def multiplicar_por_dos(n): return n * 2 def sumar_dos(n): return n + 2 def aplicar_operacion(f, numeros): resultados = [] for numero in numeros: resultado = f(numero) resultados.append(resultado) print(resultados) nums = [1, 2, 3] ap...
80e8deceb6b1cb9695661874a6e20f147ae4fd18
gokay/python-oop
/oop1_classes.py
563
3.890625
4
# Python OOP 1 Classes class Employee: def __init__(self,first, last,pay): self.first = first self.last = last self.pay = pay self.email = first + '.' + last + '@company.com' def fullname(self): return self.first + ' ' + self.last empl_1 = Employee('Gökay','Gürsoy...
a5d1af3e46387b4f805bf125a0c45d280e9592e5
BeefCakes/CS112-Spring2012
/hw03/prissybot.py
2,775
4.40625
4
#!/usr/bin/env python """ prissybot.py CS112 Homework 3: PrissyBot Prissy bot, the rude chat bot, is just mean! It does not listen, asks obnoxious questions, and says anything it likes. """ # Step 1: # ----------------------- # Program the following. # # $ python prissybot.py # Enter your name: Paul # ...
71577c8a3ac9cc3c6dc8dd485a6691a3a32536e9
DouglasAllen/Python-projects
/my_code/time_test.py
1,383
3.859375
4
#~ from datetime import datetime #~ from time import time #~ import datetime #~ 8.1.1. Available Types #~ print datetime #~ print datetime.date #~ from datetime import date #~ print date.today() #~ print datetime.time #~ print datetime.tzinfo #~ print datetime.today #~ print datetime.time() #~ print datetime.da...
cf0f04b7061aebfba0b299ccf441520655d2ea80
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/permutations-6.py
2,182
3.9375
4
'''Permutations of a list, string or tuple''' from functools import (reduce) from itertools import (chain) # permutations :: [a] -> [[a]] def permutations(xs): '''Type-preserving permutations of xs. ''' ps = reduce( lambda a, x: concatMap( lambda xs: ( xs[n:] + [x] + x...
b278dd333da450d14ee807caf580328ec3f8d308
bmg13/playing-with-python
/scripts/4_Crop_Resize_and_ChangeTransparency_of_Picture.py
818
3.8125
4
""" Change images - Crop, Resize and alter Transparency Important note: - There is a dependency of external library. To get it, the following command was used: a) pip install pillow The image used is the same created in the script "3_Webscrape_image_and_save_it_locally" of this repository """ from PIL import I...
98aacd29826b0e35ed1c2bb4748fec152c069114
angcbi/Data-Structures
/search/01_search.py
2,198
3.75
4
# -*- coding:utf-8 -*- def sequentialSearch(alist, item): pos = 0 found = False while pos < len(alist) and not found: if alist[pos] == item: found = True else: pos = pos + 1 return found, pos def orderedSequentialSearch(alias, item): """ 使用while 循环,可以在w...
f22a60ecbc786d86c3458c2fa6dff944328ac494
juandaisy/Python-study
/05.py
87
3.65625
4
a = [1, 2, 3, 4, 5] print range(len(a)) for i in range(len(a)): print a[-1 - i]
952769c601f3df6273d92d737e85ba926b139657
kkomarocker/learn_python
/tuple.py
1,236
4.59375
5
"""This is script for tuple. This file does nothing but showing how tuple is constructed. """ a = (1, 2, 3) b = ("a", "b", 4) # simple iteration for num in a: print(num) for val in b: print(val) # elements can be accessed by using [index] # a[1] = 2 # b[2] = 4 # length of tuple print(len...
b63edfc25bc7ccb1e2ea98023b744bbc4aba735d
KevinQL/LGajes
/PYTHON/Bucles V Continue, pass y else - V18.py
1,252
4.09375
4
## Ctrl + C .- Sale de un bucle infinito ## Continue .- Pasa al siguiente ciclo. no ejecuta las instrucciones después de esta instrucción ## pass .- Devuelve un null. es como si el bucle no se ejecutara. NO EXISTIECEN. bucles o clases nulas ## else .- Tienen misma caracteristica con los eleses condicionales. se...
f6c01c0f7ed285709c61d3f33901cfdb46277d3e
jinmi-yang/ai-bigdata-academy14
/파이썬/FILE/ex4.py
457
3.875
4
#!/usr/bin/env python # coding: utf-8 # In[1]: def my_len(l): total = 0 for i in l : total += 1 return total # In[2]: a = [5,5,6,7,8,3] b = 'Life is short.' print(len(a),len(b)) print(my_len(a), my_len(b)) # In[3]: def add(a,b): return a+b def sub(a,b): return a-b def mul(a,b): ...
25fb747f71516535836c416e9dfcad3cb624f3e8
Pravin-Ade-au16/Bank-Managment-System
/customer.py
1,455
4.03125
4
import sys class Customer: """customer class with bank application""" bank_name ="ADE Bank,(Ade Bank Bank) Vitthalwadi" def __init__(self, name, balance = 0.0): self.name = name self.balance = balance def deposit(self, amount): self.balance = self.balance + amount print(...
3788c4d9c006b1c84f0e91523b1fbf96f26a57f9
grivis/Python-Simple
/New_PRS.py
2,154
3.6875
4
class Gamepiece(object): types = ['Paper', 'Scissors','Rock'] def __init__(self, typeid): self.type = Gamepiece.types[typeid] def __str__(self): return self.type class Gamepot(object): def fill(self, pieces): self.content = pieces ...
6529e27da5fb05c5b24bea4fccf8f9484d087d26
Jonlukens/hangman
/rock_paper_scissors.py
3,158
3.984375
4
import random def f(): play_or_no = input ("Start a game of Rock-Papper-Scissors? Y/N:") play_or_no = str (play_or_no) if play_or_no == "Y": while True: name_1 = input ("Player 1:") name_2 = input ("Player 2:") first_p...
e27e2fb0e29db5a88138d71d911780e26216b0e9
victor-elceaninov/neural_network
/main.py
1,309
3.796875
4
import numpy def sigmoid(x, derivative=False): if derivative: return x * (1 - x) return 1 / (1 + numpy.exp(-x)) training_inputs = numpy.array([ [0, 0, 1], [0, 1, 1], [1, 0, 1], [1, 1, 1] ]) training_outputs = numpy.array([[0, 1, 1, 0]]).T # сделаем случайные числа более определённы...
a99794b16200fe60a23782169616f235ee35aecd
LeanderLXZ/leetcode-solutions
/problems/145.binary-tree-postorder-traversal/145.binary-tree-postorder-traversal.py
3,380
3.984375
4
# # @lc app=leetcode id=145 lang=python3 # # [145] Binary Tree Postorder Traversal # # https://leetcode.com/problems/binary-tree-postorder-traversal/description/ # # algorithms # Hard (53.90%) # Likes: 1920 # Dislikes: 96 # Total Accepted: 392.3K # Total Submissions: 713K # Testcase Example: '[1,null,2,3]' # # G...
865b90211d19c7257c3f54a9affdcf082b9041c4
hzhu212/ml-from-scratch
/kmeans.py
6,369
3.546875
4
import matplotlib.pyplot as plt import numpy as np from model import Model """Distance functions. these functions should be able to handle multiple times multiple distances. Assume the input is vec1(m1*n) and vec2(m2*n), the output should be like D(m1*m2), in which D[i,j] represents the distance between vec1[i] and ...
2866629f4944655eea3fd30de2511c106ca76650
kamranayub40/python
/theater4.py
226
4.03125
4
age=int(input("Enter your Age for Watch Movie :")) # while i in age: if age<=3: print("Ticket is Free :") elif age>3<=12: print("The Ticket is :$10") elif age<12>12: print("tHE Ticket is :$15") # i=i+1
dd7b2b2672e62bb998006e979e557783929abe8b
bido4500/learnpython2.7
/calendar_test.py
321
3.71875
4
#!/usr/bin/python import calendar #print calendar.TextCalendar(firstweekday=6).formatyear(2016) Mo, Da, Ye = map(int, raw_input().split()) WDnum = calendar.weekday(Ye, Mo, Da) DayDict = {0 : 'MONDAY', 1 : 'TUESDAY', 2 : 'WEDNESDAY', 3 : 'THURSDAY', 4 : 'FRIDAY', 5 : 'SATURDAY', 6 : 'SUNDAY'} print(DayDict[WDnum])...
8b620fa7fa31ee1070f6abf26983e46c55a4e442
zhoupengzu/PythonPractice
/Practice/practice20.py
357
4.03125
4
# 边界匹配符 # 在之前用^(表示从字符串开始的地方匹配)在结束的地方使用$(在字符串末尾进行匹配) import re qq = '100000001' print(re.findall('\d{4,9}', qq)) print(re.findall('^0{4}', qq)) # [] print(re.findall('^10{7}1$', qq)) # ['100000001'] print(re.findall('^10{7}$', qq)) # [] 因为此时不是以1结尾的
6d9d03b79a6ec5f22a87408182d37653fe68b1ec
acaciooneto/cursoemvideo
/ex_videos/ex-104.py
337
3.71875
4
def leiaInt(entrada): while True: dentro = input(entrada) if dentro.isnumeric(): n = int(dentro) break else: print(f'\033[0;31mERRO! Você não digitou um valor inteiro.\033[m') return n n = leiaInt('Digite um valor: ') print(f'Você acabou de informar o...
866c2c47b3bbdc628b3414b50e021508be832b55
daniyoko/Python-I--Meus-exercicios
/exercicio17.py
904
4.03125
4
def soma(n1,n2): print('Soma: {}' .format(n1+n2)) def subtracao(n1,n2): print('Subtração: {}' .format(n1-n2)) def divisao(n1,n2): print('Divisão: {}' .format(n1/n2)) def multiplicao(n1,n2): print('Multiplicação: {}' .format(n1*n2)) opcao = 1 while opcao: print('[0] Sair') print('[1] Calcular')...
929aea4d1014f4291c858b43514c67eaf608538a
mmchiro/testrepository
/s2_2_inspecting_data.py
673
3.71875
4
import pandas as pd df = pd.read_csv("intel.csv") #Print data to show that it work #print(df) #Print to check data type #print(type(df)) #Help to check dataframe shape #print(df.shape) #Print column name #print(df.columns) #Print first 5 rows of the data #print(df.head()) #Inspect bottom 5 rows of the data #print...
c5bf5520ab4472f85a369dac89d6e5bb89ba5b85
AlexGalhardo/Learning-Python
/Book Introdução Programação com Python/10 - Classes e objetos/10.06 - Classe Conta.py
1,022
4.375
4
############################################################################## # Parte do livro Introdução à Programação com Python # Autor: Nilo Ney Coutinho Menezes # Editora Novatec (c) 2010-2014 # Primeira edição - Novembro/2010 - ISBN 978-85-7522-250-8 # Primeira reimpressão - Outubro/2011 # Segunda reimpressão - ...
88f1b548c80fd2510ba78ba7dc234784aeb3172a
sirvenny/binary-to-dec
/binary_to_dec.py
1,954
3.5625
4
import tkinter from tkinter import * from tkinter import Tk from tkinter import filedialog import os import csv """ Converts binary file to two decimal arrays, p and q, where p = every even value and q every odd value (e.g. dec=12345678, p=[1,3,5,7] q=[2,4,6,8]). Also ouputs adjusted p -> padj = p / 25.6 -1 q...