blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
a31404839569a834ca98b6551ea8ef9e803df3e4
manhar336/manohar_learning_python_kesav
/Datatypes/sets/sets_methods.py
3,325
4.28125
4
#Union Method print("union method1:",set([1,2,3,4,5]).union(set((6,7,8,9)))) #it will combine 2 sets {1, 2, 3, 4, 5, 6, 7, 8, 9} a=(10,20,30,40) b=(40,50,60) print("union method2:",set(a).union(set(b))) #Intersection x=(10,20,30,40) y=(40,50,60) print("Intersection method",set(x).intersection(set(y))) #it will give...
ef93cf0f13e5acde0d39c4ad424f0ace6d02d9a7
wcu201/Leetcode
/Google/Longest Consecutive Sequence.py
856
3.796875
4
''' Given an unsorted array of integers, find the length of the longest consecutive elements sequence. Your algorithm should run in O(n) complexity. Example: Input: [100, 4, 200, 1, 3, 2] Output: 4 Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4. ''' class Solution:...
b607216b3145ce9e174b263209bb3f62a077f853
mfilipelino/python-notes
/sort/insertion.py
903
3.796875
4
from unittest import TestCase from sort.insertion import insertion_sort class TestInsertionSort(TestCase): def test_list_empty(self): self.assertEqual(insertion_sort([]), []) def test_list_one_item(self): self.assertEqual(insertion_sort([1]), [1]) self.assertEqual(insertion_sort(['a'...
ef6d1b80eeeba446f5322df4b171fecf0be72a1a
palindrome1311/Cracking-cracking-the-coding-interview
/8.2.py
1,155
3.8125
4
def getpath(mat): path=[] visited=set() rows = len(mat)-1 cols= len(mat[0])-1 if(isValid(mat,rows,cols,path,visited)): return path return None def isValid(mat,rows,cols,path,visited): #out of bounds check or obstacle check if(cols < 0 or rows < 0 or not mat[rows][cols...
23f42b9f1825a55b58eeec6a85a13fdca1f00875
veeteeran/holbertonschool-higher_level_programming
/0x0C-python-almost_a_circle/models/rectangle.py
4,550
3.59375
4
#!/usr/bin/python3 """Docstring for Rectangle class""" from models.base import Base class Rectangle(Base): """Rectangle class inherits from Base""" def __init__(self, width, height, x=0, y=0, id=None): """ Init method for Rectangle class Parameters: width: width ...
fbb5837c706aaab28022b81ce89628c86fa7b6d2
srikanthpragada/PYTHON_27_AUG_2020
/demo/libdemo/thread_demo.py
328
3.8125
4
from threading import Thread class PrintThread(Thread): def run(self): for i in range(1, 11): print("Child", i) def print_numbers(): for i in range(1, 20): print(i) t1 = PrintThread() t1.start() t2 = Thread(target=print_numbers) t2.start() for n in range(1, 20): print("Mai...
8c190675df895f5d9a2885694f3930f2c4b4eac6
aroraakshit/coding_prep
/pacific_atlantic_water_flow.py
3,744
4.03125
4
class Solution(object): # 196ms, Credits - https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/90739/Python-DFS-bests-85.-Tips-for-all-DFS-in-matrix-question. def pacificAtlantic(self, matrix): """ :type matrix: List[List[int]] :rtype: List[List[int]] """ if no...
c1175e91542c3a0d9351d30096253073c43f0c10
alex-stefa/thor
/thor/enum.py
2,266
3.75
4
#!/usr/bin/env python """ Simple enumeration type implementation in Python """ __author__ = "Alex Stefanescu <alex.stefa@gmail.com>" __copyright__ = """\ Copyright (c) 2013 Alex Stefanescu Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files...
643d48b116918c8b7096936e0830723a3775fb33
alui07/Technical-Interview
/LeetCode/Python/NumSquares.py
891
3.6875
4
""" 279. Perfect Squares Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n. Example 1: Input: n = 12 Output: 3 Explanation: 12 = 4 + 4 + 4. Example 2: Input: n = 13 Output: 2 Explanation: 13 = 4 + 9. """ class Solution(object): def numSqua...
be03b227f58829ab907a993e0f655e25e77f03c6
kamojiro/atcoderall
/beginner/079/B.py
121
3.71875
4
N = int(input()) a = 2 b = 1 if N == 1: print(1) else: for _ in range(N-1): a, b = b, a + b print(b)
1259bffe8240c1b0523bb816565829db10d6caaa
Godsmith/adventofcode
/aoc/year2020/day15/day15.py
484
3.609375
4
def last_number2(numbers, count): locations = {} for i, number in enumerate(numbers): locations[number] = i while len(numbers) < count: numbers.append(len(numbers) - 1 - locations[numbers[-1]] if numbers[-1] in locations else 0) locations...
516c66837f0cc8948eb6e5350ecfb16b8b0e9530
DaVinci42/LeetCode
/19.RemoveNthNodeFromEndofList.py
771
3.796875
4
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: if not head or n < 1: return None right = head for _ i...
a1425d169f8a5819814a64b7d53a3b005186bd6c
WangGewu/LeetCode
/python/007.py
346
3.546875
4
class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ x = str(x) x=x[::-1] if x[-1]=='-': x='-'+x res=int(x[0:-1]) else: res=int(x) if -2**31<res<2**31-1: re...
6c021f5e56a5e078a0bf896e74492bc5f77bd231
zhiyunl/lcSolution
/0020validParentheses.py
1,951
3.90625
4
""" Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Note that an empty string is also considered valid. Ex...
ad904dadfd53c96771768a93980804b15297a816
akashghanate/OpenCV
/imageManipulation/thresholding.py
1,393
3.875
4
#thresholding is converting an image into it's binary form #cv2.threshold(image, Threshold value, Max value, Threshold type) #NOTE: image is first converted to grayscale before thresholding import cv2 import numpy as np # threshold types # cv2.THRESH_BINARY # cv2.THRESH_BINARY_INV # cv2.THRESH_TRUNC # cv2.THRESH_...
5bfd5cec22633300b2704fef578b15e8d5ffc551
Nyapy/TIL
/04_algorithm/Programmers/거듭제곱.py
294
3.75
4
three = [0] n = 9 num = 0 length = 0 while num < n: tem = 3**num tem_list = [] for i in three: tem_list.append(tem+i) length += 1 if length == n : break three = three + tem_list if length == n: break num+= 1 print(three[n])
71a652032cedf5dd889990cd89bad96b82f0be93
valmsmith39a/u-data-structures-algorithms
/p1-text-calls/Task3.py
5,111
4.1875
4
""" Read file into texts and calls. It's ok if you don't understand how to read files. """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ TASK 3: (080) is the area code for fixe...
6b1d067686afd07990f44a105ba34999f0dd2206
ZhangShuang666/course_system
/src/service/admin_service.py
1,483
3.84375
4
from src.models import School, Teacher def create_school(): school_name = input("请输入学校名称:") obj = School(school_name) obj.save() def show_school(): print("=========学校========") school_list = School.get_all_school_list() for item in school_list: print(item.schoolName) def create_tea...
c201fea752866167819c4cbe68fa483ff591f4db
Kyrk/Automate-the-Boring-Stuff-Code
/Chapter 7 - Pattern Matching with Regular Expressions/pwStrength.py
1,672
4.53125
5
#!/usr/bin/env python3 '''Program with function that uses regular expressions to make sure the password string passed as a parameter is strong. A 'strong' password contains the following: - At least 8 characters long - Contains both uppercase and lowercase characters - Contains at least one digit ''' import...
ef3354d49c9e4fe1024ec3357b5018b4e9333189
FunWithPythonProgramming/coding-bat-exercises
/week_1_Jan_28/lucky_sum/miguel_lucky_sum_solution.py
315
3.859375
4
def lucky_sum(int_one, int_two, int_three): if int_one == 13: return 0 elif int_two == 13: return int_one elif int_three == 13: return int_one + int_two else: return int_one + int_two + int_three lucky_sum(1, 2, 3) # 6 lucky_sum(1, 2, 13) # 3 lucky_sum(1, 13, 3) # 1
1f7ae9a68384675289ffdff7a60cd721370cda61
AndresNunezG/ejercicios_python_udemy
/ejercicio_17.py
647
4.03125
4
""" Ejercicio 17. - Escribir una lista que encuentre el menor número de una lista """ #Lista a determinar el menor elemento lista = [12, 20, 17, 21, -16, 21, 2.0, -2.3, 0] #Determinar menor elemento def lista_menor(lista): min_elem = 10e6 indice = 0 for ind, num in enumerate(lista): if num < m...
ae9175050cd84fc23102e5f4d3f0f523991ac686
connorourke/lammps_potenial_fitting
/bond_types.py
1,011
3.65625
4
class BondType(): """ Class for each bond type. """ def __init__(self, bond_type_index, label, spring_coeff_1, spring_coeff_2): """ Initialise an instance for each bond type in the structure. Args: bond_type_index (int): Integer value given for the bond type. ...
73d48b983bf412caac2783a231d403ea0bd3983f
KarinaMapa/Exercicios-Python-Decisao
/ex.11.py
737
3.828125
4
salario = float(input('Digite seu salário: ')) if salario <= 280: novo_salario = (salario*1.2) aumento = 20 diferenca = novo_salario-salario elif 280 < salario < 700: novo_salario = (salario*1.15) aumento = 15 diferenca = novo_salario-salario elif 700 < salario < 1500: novo_salario = (salari...
1108ca9aa8bd18026389658239903670218c2d8e
leson238/python
/Student projects/Restaurant/backend.py
3,019
3.96875
4
class Restaurant: def __init__(self, name, address, average_price, distance, nationality): self.name = name self.address = address self.average_price = average_price self.distance = distance self.nationality = nationality def __str__(self): return f"{self.name} :...
bcd9ff9e967c67c0b0ac2c5306b7b141ffa86912
JerryChii/PycharmProjects
/QuickStart/FunctionTest.py
1,381
4.09375
4
#!/usr/bin/python # -*- coding: UTF-8 -*- print '======================================' # 给变量赋初值 def printinfo(name, age = 10): "打印任何传入的字符串" print "Name: ", name print "Age ", age return # 指定变量名赋值 printinfo(age=50, name="miki") # 不定长参数 def printinfo(arg1, *vartuple): "打印任何传入的参数" print "输出...
8b28cd817abc775a86d102aefc63d649bb8c1ff7
daniel-reich/ubiquitous-fiesta
/t2WH2HdrQhCcJrezL_11.py
235
3.546875
4
def eda_bit(start, end): s = [] for i in range(start,end+1): if i%3==0 and i%5==0: s.append('EdaBit') elif i%3==0: s.append('Eda') elif i%5==0: s.append('Bit') else: s.append(i) return s
25ea922f2490c1aa7964472c7ba340ab04f3549a
Fettes/PythonLearning
/Yield/try_yield_01.py
191
3.765625
4
def fab(max_num): n1, a, b = 0, 0, 1 while n1 < max_num: yield b # 使用 yield # print b a, b = b, a + b n1 = n1 + 1 for n in fab(5): print(n)
8cbf4dc8dbeaed221143a80522ac885ced51697c
apatel3112/SC_FinalProject
/Movie_GUI.py
24,425
3.59375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Dec 6 15:48:09 2019 @author: Anusha """ """ Created on Mon Dec 2 16:38:47 2019 This file creates a GUI application that allows for user input of movie paramteres on mupltiple pages @author: bento """ import tkinter as tk from tkinter import font as ...
56f68f69740de55331a8485e08f0e7ee5e977611
coloriordanCIT/PycharmProjects_Mac_Desktop
/PDA_A02/venv/Main.py
9,344
3.921875
4
''' Project B Programming for Data Analytics Haithem Alfi @author: colinoriordan @StudentID: R00133939 @Email: colin.r.oriordan@mycit.ie @class: SD3B Project objective is to produce an application and report that allows the user to explore some of the most interesting aspects of the IMDB dataset, using Pandas where p...
b9d2b0498293c978e79f30d5500e6ae0bcf39037
PdxCodeGuild/class_emu
/Code/Kevin/Misc Practice/Linked Lists/Push.py
694
4.15625
4
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def push(self, new_data): # Pushing the data to the top of the stack. Today?->You->Are->How->World!->Hello new_node = Node(new_data) ...
ded0465eb4046dff3fa4ecfca6e3df18088166be
shirleyxx/Leetcode
/P133.py
706
3.734375
4
""" # Definition for a Node. class Node: def __init__(self, val, neighbors): self.val = val self.neighbors = neighbors class Solution: def __init__(self): # Dictionary to save the visited node and it's respective clone # as key and value respectively. This helps to avoid cycles. ...
c1fe6beca5205441d0cd0e6f46d03d49503a436c
javiermms/cs1.3
/word_jumble.py
3,638
3.796875
4
import time start = time.process_time() def get_file_lines(filename='/usr/share/dict/words'): """Return a list of strings on separate lines in the given text file with any leading and trailing whitespace characters removed from each line.""" # Open file and remove whitespace from each line with open(fi...
14d85a9438091d02535a7b1b84cef2b4a29716eb
Abhayghoghari/internship
/q1-avg of 5 num.py
307
4.28125
4
print('enter value and find average number') n1= int(input('enter 1st number: ')) n2= int(input("enter 2nd number: ")) n3= int(input("enter 3rd number: ")) n4= int(input("enter 4th number: ")) n5= int(input("enter 5th number: ")) s=n1+n2+n3+n4+n5 avg=s/5 print("your average number is",avg) input()
30850cf5649e2369e56dc5f355211685df805f01
ratedr360/pdsnd_github
/Bikeshare_analysis.py
7,991
4.125
4
import time import pandas as pd import numpy as np import calendar CITY_DATA = { 'Chicago': 'chicago.csv', 'New York City': 'new_york_city.csv', 'Washington': 'washington.csv' } def get_filters(): """ Asks user to specify a city, month, and day to analyze. Returns: ...
4f9564eca5f03faa2141319eed0dc88d0e23c7f5
CNieves121/lps_compsci
/class_samples/3-7_forloops/PartnerPractice.py
398
4.40625
4
""" colors = ["red", "blue", "green", "purple"] ages = [14, 15, 15, 16, 16, 13, 18, 14, 15, 15, 14] # 5 - how do we remove an item from the list? print(colors) del colors[2] print(colors) """ colors = ["red", "blue", "green", "purple"] ages = [14, 15, 15, 16, 16, 13, 18, 14, 15, 15, 14] # 6 - what happens when we u...
c46b3e12f80dcdc94892ee2990ecf3c4bcf0f5c4
juanchixd/Curso-python
/Listas.py
264
4.0625
4
lista = [12, "World", True, "oración", [21, "Hello"]] valor = lista [1] print(valor) valor2 = lista[4][1] print(valor2) lista[1] = 1 print(lista) var2 = lista[-1] print(var2) var3 = lista[0:2] #no incluye el elemento 2 print(var3) var4 = lista[0:5:2] print(var4)
251d529268ed35832a12c1e556ff62ac7607158b
Joombey/project
/function.py
2,388
3.6875
4
import sqlite3 as sql import calendar import datetime #user = input() class SQL: def __init__(self, user): self.User = 'name'+str(user) def open_conn(self): self.conn = sql.connect("base_db.sqlite") self.cur = self.conn.cursor() return self.conn, self.cur def close_co...
ff7825225222d401ddf19233b9b3a79e10831504
shahmk/Algorithms
/Longest Pal.py
697
3.875
4
def longest_pal(str): n=len(str) #initialize Opt Table Opt=[[0 for i in range(n)] for j in range(n) ] for i in range(n): Opt[i][i] = 1 # define sil as length of substring interval [i,j] sil=(j-i +1) # compute Opt table entry for each starting index i and each sil for sil in range(2, n...
7f695c13678e2de0d7669a5123a28b170583e2f7
superyang713/pcookbook
/07_functions/02_write_functions_that_only_accept_keyword_arguments.py
496
3.65625
4
""" Problem: You want a function to only accept certain arguments by keyword. Solution: It is easy to implement if you place the keyword arguments after a * argument or a single unnamed *. """ # Example 1: Note that * argument can only appear as the last positional # argument in a function definition. A ** argument ...
22d61d76e4b73e30afde7874d99971b0d786726f
1GBattle/gab_locator
/.idea/gag_functions/get_gag.py
1,001
3.578125
4
def get_gag(line_in_file, operators, operators_in_string, operands): split_line = line_in_file.split() data_types = [] for character in split_line: if character in operators: operators_in_string.append(character) elif isinstance(character, str) or isinstance(character, int) or i...
5b1c4ff05a833b1358e9249037090b8afc70d57b
ShayLn/py-fighter
/screens/scores.py
2,737
4.125
4
''' High Score Screen This screen is shown at end of game after pressing on scoreboard button. Takes data from other_data/highscores.txt and creates a score board of top 10 players. Used Roberts Text, Menu and Button functions @author: Rokas ''' import pygame from classes.generalfunctions import quitGame from class...
8b9b217ab70bb9667998b6dc15f6089f015c3fa7
pavelbrnv/Coursera
/PythonBasis/week07/task09.py
685
3.59375
4
inFile = open('input.txt', 'r', encoding='utf8') n = int(inFile.readline().strip()) common_languages = set() all_languages = set() for pupil_index in range(n): m = int(inFile.readline().strip()) pupil_languages = set() for language_index in range(m): language = inFile.readline().strip() p...
5f6b3eb50500a11ed3a2a93a514ef31c2f8c4250
BrunoCerberus/Algoritmo
/Ex78.py
738
3.5625
4
""" Programa que recebe um vetor de 20 posicoes e um valor x qualquer O programa devera fazer uma busca de x no vetor, caso encontre, exibir a posicao do vetor juntamente com o valor, caso nao, mostrar uma mensa- gem de erro. """ from random import randint vetor = [] for i in range(0,20): vetor.append(randint(-...
84363766857f0d258ea001be59087308f0d50091
phoenix9373/Algorithm
/2020/백준문제/수학3/5086_배수와 약수.py
250
3.796875
4
while True: a, b = map(int, input().split()) if a == b == 0: break ans = '' if (a // b) * b == a: ans = 'multiple' elif (b // a) * a == b: ans = 'factor' else: ans = 'neither' print(ans)
ae0f3eeba843f7eaa2b216f82d35fd0ad6e48e92
RaptorPatrolContinuum/An
/OldStuff/MiraExternalsold.py
16,118
3.59375
4
from math import * from inspect import * import ast file = open('INP.txt', 'r') basis = open('Basis.txt', 'r+') memory = open('Memory.txt', 'r+') def ARB(function, replacelist): ''' ANSWER: need to map everything to concept space then ARB is just a basis remapping god fucking damn it I hate writ...
1af790332e8b6e0f9205ebde9fcdca3d649ebc42
darshankrishna7/NTU_reference
/NTU/CZ1003 Intro To Computational Thinking/Tutorial/max_min_recur.py
1,423
4.0625
4
# Write two functions maxInList(aList) and minInList(aList) that return # the maximum and minimum value in a list of integers, aList, respectively. # You have to implement the two functions by using recursion. # Notice that max() and min() functions for lists are not allowed. import os import random def ...
a5e99641706643931304846fb8e1295e8451391f
CloudChaoszero/Data-Analyst-Track-Dataquest.io-Projects
/Probability-Statistics-Beginner/Introduction to probability-48.py
2,251
3.9375
4
## 1. Probability basics ## # Print the first two rows of the data. print(flags[:2]) most_bars = flags["bars"].idxmax most_bars_country = flags["name"][most_bars] print(most_bars_country) highest_population = flags["population"].idxmax highest_population_country = flags["name"][highest_population] print(highest_popul...
e6da34831a48a98c7ab7bfb73575cccba22e88c4
amyjberg/algorithms
/python/merge-sort.py
1,596
4.25
4
# merge sort algorithm: # divide into subarrays of one element # merge every two subarrays together so they stay sorted # continue merging every two subarrays until we just have one sorted array def mergeSorted(listA, listB): pointerA = 0 pointerB = 0 merged = [] while pointerA < len(listA) and pointerB < len(...
5bf9e79ddf0b7ad1ec9ed9c7f37de1e1858e9ec9
SophieEchoSolo/PythonHomework
/Lesson12/teamD112_prog2.py
4,446
4.28125
4
""" Author: Sophie Solo and Kyle Howell Course: CSC 121 Assignment: Lesson 12 - Program 2 Description: teamD112_prog2.py - This program will generate a test and answer key, administer the test, and grade the test """ def grade_test(student_response_list, answer_list): """ Function used to grade the test t...
a7f294083b725c86ff98ac4921c41eba036832a9
ttvang22/totalbillcostandbillsplit
/billsplitter.py
1,439
4.1875
4
print "Hello, this system is to help split bills among roommate" #Define roommate roommatename1 = raw_input("What is the first roommate name? ") roommatename2 = raw_input("What is the second roommate name? ") roommatename3 = raw_input("What is the third roommate name? ") roommatename4 = raw_input("What is the fo...
746b4b9ac02cd307a5e6432d4fc99751fdfa780d
121910313014/LAB-PROGRAMS
/L7-NUMBER OF NODES.py
1,159
4.15625
4
#NUMBER OF NODES #class for nodes class Node: #constructor for creating nodes def __init__(self,data): self.data=data self.next=None #class for LinkedList class LinkedList: #constructor for initialising LinkedList def __init__(self): ...
0ca2e60dc6c0f9e8646a938551c64e0a9cb24005
Djam290580/lesson_6
/lesson_8/practic_8.6.except.py
1,373
3.890625
4
# Exception обязательно указывать, т.е. OwnError является помком от Exception class OwnError(Exception): def __init__(self, txt): self.txt = txt inp_data = input('Only positive numbers - ') # Задача отсечь все отрицательные значения и получать только положительные # Блок try содержит инструкции, которые ...
f718e572c0d7faeda3d69958410402418638aabd
Tadele01/Competitive-Programming
/Week-03/construct_bst_from_preorder.py
643
3.546875
4
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def bstFromPreorder(self, preorder: list[int]) -> TreeNode: if len(preorder) == 0: return None left, right = [], [] roo...
82b1f6abcd4adf6781cf4a75659a15d222fe7361
michaelwro/linalg-python
/examples/genSPDSystemExample.py
1,763
4.40625
4
""" EXAMPLE GENSPDSYSTEM: linalg-python Generate a dense, symmetric positive-definite system of linerar equations. SPD systems are commonly solved using iterative solvers. By: Michael Wrona Student, B.S. Aerospace Engineering Iowa State University (Ames, IA) """ import numpy as np def genSPDSystem(n): """ ...
53524b3199aa1cf0063f1d61d359df054ad8db1d
whiteydoublee/Python
/Ch06/sub1/StockAccount.py
852
3.625
4
from Ch06.sub1.Account import Account #Inheritance : class 이름(상속할 부모 클래스이름) class StockAccount(Account): def __init__(self,bank,id,name,balance,stock,amount,price): super().__init__(bank,id,name,balance) self.stock = stock self.amount = amount self.price = price def sell(self...
318f87e73389aeeb7aea98d25e3c1ab174ca42b6
zzandland/Algo-DS
/Python/Amazon_2020_03/optimal_utilization.py
5,566
3.875
4
# Given 2 lists a and b. Each element is a pair of integers where the first integer represents the unique id and the second integer represents a value. Your task is to find an element from a and an element form b such that the sum of their values is less or equal to target and as close to target as possible. Return a ...
ab3d768830aa63824722b59464c52ee4be0b53fa
FGolOV/rot
/main.py
1,647
3.59375
4
num=int(input('Введите число, состоящее только из цифр 6 и 9 ')) #Функция принмимает на вход целое число def rot(num): #Объявляем ф-цию num_list=[] #Создаем пустой список while num>0: #Цикл, который преобразует целое число в список путем внесения в список остатка от деления числа на 10 num_list.appe...
a1c54d0c0bad8b68d39c2f9f3af4d86a2587f9a6
adhitizki/List_Spinner
/soal_2.py
929
4
4
def counter_clockwise(masukan): list_baru = [] #untuk list yang nanti digunakan untuk mengisi list yang sudah diputar for i in range(len(masukan[0])-1,-1,-1): #untuk memberikan index pada baris dimana ketika diputar akan menjadi kolom list_baris = [] #membuat list untuk baris baru yang sudah diputar ...
22e4b80cec5d87cd7fba527a129ff4e0030c7665
frankwwu/machine-learning-exercise
/coursera-machine-learning-python/ex5/linear_reg_cost_function.py
1,045
4.1875
4
import numpy as np def linear_reg_cost_function(theta, X, y, l): """ Compute cost and gradient for regularized linear regression with multiple variables. Parameters ---------- theta : ndarray, shape (n_features,) Linear regression parameter. X : ndarray, shape (n_samples, n_features) ...
07e3b9829b4df69813d316f8d7a7539493a37bbf
juliachristensen/PS239T_Fall2019
/04_python-basics/15_Errors.py
11,683
3.671875
4
# coding: utf-8 # # Errors and Exceptions # # **Time** # - teaching: 10 min # - exercises: 10 min # # **Questions**: # - "How do a read an error message?" # - "What do the error messages mean?" # - "How do a fix an error?" # - "What if I still can't figure it out?" # # **Learning Objectives**: # # * To be able ...
1455321388ca58a8a23eeefbf286638bdd41de33
n18013/programming-term2
/src/algo-p2/task20180807_q04.py
542
4.09375
4
#変数fruitsに辞書を代入してください # ('apple'というキーに対し'りんご'という値、'banana'というキーに対し'バナナ'という値のふたつ) fruits = {'apple': 'りんご', 'banana':'バナナ'} #辞書fruitsのキー「banana」に対応する値を出力してください print('バナナ') #辞書fruitsを用いて、「appleは◯◯という意味です」となるように出力してください for name in fruits.items(): print('appleは' + 'アップル' + 'という意味です。')
45887d1553d33ec93227b561618c66356b78153c
JulianMW/python-resources
/data-structures/heapify_max.py
895
4.09375
4
def heapify_helper(arr, n, i): largest = i # Initialize largest as root l = 2 * i + 1 # left = 2*i + 1 r = 2 * i + 2 # right = 2*i + 2 # See if left child of root exists and is # greater than root if l < n and arr[i] < arr[l]: largest = l # See if right child of root exi...
29a2d5e47ea97b04bb1162604eb016673c7fff60
flame4ost/Python-projects
/§7(178-250)/z180.py
268
3.640625
4
import math n = (int(input("Введите число n "))) i = 3 for i in range(n): x = i*i*i-3*i*n*n+n print(i,'. ',x) if (frac(x/3)==0) and (odd(round(x//3))): s = s+x print(x, ' - утроенное нечетное') print("s = ", s)
700065aec87bf2f9514e2d1c7f1e75377c6d8463
bayramcicek/language-repo
/p014_dictionary.py
2,949
4.0625
4
#!/usr/bin/python3.6 # created by cicek on 07.08.2018 22:06 ages = {"dave":34, "ahmet":65} print(ages["dave"]) # 34 list = {5:90, 1:34, 2:[11,99,65], 3:777} print(list[5]) # 90 print(list[2][1]) # 99 ages = {"Dave": 24, "Dave": 42, "John": 58} print(ages["Dave"]) # 42 duplicate key, used the last value myDic = {"he...
70b353b2b4b7a018a9d814c593545ad2909e353d
vivianmaxine/hello-flask
/main_form_values.py
1,731
3.671875
4
from flask import Flask, request #request object allows us to access data in request user sent to server #via python #POST refers to a methods parameter via request.form['param_name'] app = Flask(__name__) app.config['DEBUG'] = True """GOAL 1: Change Index Handler so it returns HTML that consists of form that user ...
9b7bee441f4d306e9cabbd8d31368c8201d72be4
pankaj307/Data_Structures_and_Algorithms
/LinkedList/reverseLinkedList.py
578
4.125
4
import my_LinkedList def reverse(l1): cur = l1.head prev = None while cur: nxt = cur.next cur.next = prev prev = cur cur = nxt l1.head = prev def reverseRecursive(cur,prev): if cur is None: return prev nxt = cur.next cur.next = prev ...
6e02ca47369b3f7205d8dd119dfe8f3944051b80
itspratham/Python-tutorial
/Python_Contents/Sample_Programs/ll.py
2,330
4.03125
4
# class Node: # def __init__(self, data): # self.data = data # self.next = None # # # class LL: # def __init__(self): # self.head = None # # def append(self, data): # headd = self.head # if self.head is None: # self.head = Node(data) # return #...
45f298202f0e1384d387d8e9886b89fc4022803d
lacekim/Nueral_Networks
/ch6.py
2,501
3.546875
4
import matplotlib.pyplot as plt import nnfs import numpy as np from nnfs.datasets import vertical_data, spiral_data from ch4 import Activation_ReLU from ch5 import Layer_Dense, Activation_Softmax, Loss_CategoricalCrossentropy nnfs.init() X, y = spiral_data(samples=100, classes=3) # Create dataset X, y = vertical...
efee66f212089430f30441c932c6406ff94410a9
gjwlsdnr0115/algorithm-study
/data-structure/Queue.py
544
3.75
4
# 1. use deque # add, del: O(1) from collections import deque # deque init dq = deque([]) # add data dq.append(1) dq.append(2) dq.append(3) dq.append(4) print(dq) # deque([1, 2, 3, 4]) print(dq.popleft()) # 1 print(dq.popleft()) # 2 print(dq.popleft()) # 3 print(dq.popleft()) # 4 print(dq) # deque([]) # 2. ...
5abd1b96411db367eb2aabe511b62942deef4e14
DmitriyA13/Chess-knight
/knight.py
874
4
4
""" knight""" def Enter(x): while True: try: int(x) if int(x) > 0: break else: print('cannot be less than zero or equals zero') return Enter(input('try again >')) except ValueError: print('entered not numbers') return Enter(input('try again...
34a34f0bc4b721674f7c41c26f3bf02a8b192046
Timur597/First6team
/6/Tema2(if,elife,else)/12.if_0.py
57
3.71875
4
aa=10 bb=5 if aa>bb: print("aa+2") else: print("bb+2")
ad7a8704fdc738c00868f9dd50607f1d9bd0d9a5
GAURAV-GAMBHIR/pythoncode
/5.8.py
243
3.625
4
print("\n\n") list4 = [input("Enter element : ") for x in range(10)] x = input("\nEnter element to be deleted : ") for y in range(len(list4)): if x==list4[y] : del list4[y] break; print("After deletion : ",list4)
bdcd03389298becf48e714c054677171f959c10d
lizzzcai/leetcode
/python/greedy/0402_Remove_K_Digits.py
1,913
3.703125
4
''' 13/05/2020 402. Remove K Digits - Medium Tag: Stack, Greedy Given a non-negative integer num represented as a string, remove k digits from the number so that the new number is the smallest possible. Note: The length of num is less than 10002 and will be ≥ k. The given num does not contain any leading zero. Exam...
126497ab4bccf3aac6d5f1152a0c86459271cc34
suhang319/exercise
/作业/作业.py
1,935
3.5625
4
#_*_ coding:utf-8 _*_ #@Time :2020-12-1920:21 #@Author :lemon_suhang #@Email :1147967632@qq.com #@File :作业.py #@Software:PyCharm # 1.5层打印,外层循环 m=5 m=1 # 内层循环控制个数你n<=m m=1 while m<=5: n=1 while n<=m: print("*",end='') n +=1 print() m +=1 # 字符串去重 # str1 ="aabbbcddef" str2='...
62f8d684cadaaacc2318897ae4adb67c742f8f6f
alexandraback/datacollection
/solutions_5738606668808192_1/Python/ppsreejith/c.py
1,208
3.625
4
from collections import defaultdict primes = [3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 2...
52a1dc0793292a96915c0928606fd75af1117253
poppindouble/AlgoFun
/length_last_word.py
520
4.03125
4
""" In python, str.split() if we specifiy the seperator for example, "1,2,3,,,4".split(',') we will get ['1', '2', '3', '', '', '4'] if we don't specific the seperator for example " 1 2 3 4".split(' ') you will get ['1', '2', '3', '4'] https://docs.python.org/3/library/stdtypes.html#str.split """ class Solutio...
bc198d2b00d521e91e4bc6d860d5d0d3254c507b
Yuandi888/algorithm014-algorithm014
/Week_04/122_Best_Time_to_Buy_and_Sell_Stock_II.py
982
3.71875
4
# 122. Best Time to Buy and Sell Stock II # 122. 买卖股票的最佳时机 II # 采用贪心算法 class Solution: def maxProfit(self, prices: List[int]) -> int: all = 0 for i in range(len(prices)-1): if prices[i] < prices[i+1]: all += prices[i+1] - prices[i] return all # https://leetco...
d0d6a49b6bf947dfa9c96f9d594d1c5abd25d664
thenavdeeprathore/LearnPython3
/06_2_data_structure_tuple/Tuple_Functions.py
1,850
4.59375
5
""" Important Functions of Tuple: --------------------------- I. To get Information about Tuple: 1) len : Returns the number of elements present in the tuple 2) count : Returns the number of occurrences of specified item in the tuple 3) index : Returns the index of first occurrence o...
75858326d14f1cb4c5347ff3e6edbe02529dc10e
RaymondHealy/Karahl_Codespace
/CS 1/Labs/Lab8/dna.py
3,685
3.5625
4
from linked_code import * """----------------------------<Required Functions>----------------------------""" def convert_to_nodes(dna_string): dna_string = dna_string.strip() if dna_string == '': return None else: return Node(dna_string[0].upper(), convert_to_nodes(dna_string[1:])) def con...
f3a82a9881f9618e4ccb88e315a9f7e75cee8af9
burcekrbrk/GlobalAIHubPythonCourse_Burce-Karabork
/HW2.py
262
3.90625
4
dict = {"KullanıcıAdı": "Burçe", "Şifre":1234} a= str(input("Kullanıcı adı giriniz: ")) b= int(input("Şifre giriniz: ")) if dict["KullanıcıAdı"]==a and dict["Şifre"]==b: print("Tebrikler") else: print("Şifre veya kullanıcı adı hatalı")
af071de08043b70c2217492a0c62c79a12c5a6b5
k2mv/AdventOfCode2020
/18/18_2.py
4,000
3.5625
4
file_input = open("input1218.txt", "r") #file_input = open("test_input.txt", "r") lines = file_input.readlines() # LIST METHODS # append(this), count(of_this) # extend(iterable_to_append) # index(of_first_this), insert(at_pos) # pop() default: idx -1 # remove(first_of_this), reverse(), sort() # DICT METHODS # assignm...
c3d779ce587514b746220eb317ee03b81928b41f
supatel/bin2image
/bin2image.py
1,885
3.703125
4
import cv2 # Not actuallfile_array necessarfile_array if file_arrayou just want to create an image. import argparse import numpy as np def parse_args(): parser = argparse.ArgumentParser( add_help=True, ) # file_arrayour arguments here if len(sfile_arrays.argv) == 1: parser.print_help...
162cb05c63de85d431ab3efcdba8d96ce41d62c4
prd81/bomberman
/run.py
2,327
3.703125
4
""" Main module """ from random import choice from time import sleep from os import system as do from board import Board from person import Person from game import game def welcome(): """ Welcome screens """ do('clear') time = 3 for i in range(time, 0, -1): for j in (i, ' '): do('cl...
fb8b8bbbb90d4638c0d11ffc8b01f3bdf961c4bb
hwang033/job_algorithm
/py/cci_4.3_binary_tree_minimal_order.py
673
3.921875
4
class Node: def __init__(self, val): self.val = val self.left = None self.right = None def create_binary_tree_from_list(l): if not l: return None mid = len(l)/2 root = Node(l[mid]) root.left = create_binary_tree_from_list(l[:mid]) root.right = create_binary_tre...
f1440aa672848e4a45b814aaf98788ce7d2cb8a4
paalso/mipt_python_course
/4_arithmetics_and_lists/9.py
284
3.5
4
# http://judge.mipt.ru/mipt_cs_on_python3_2016/labs/lab5.html#o9 # Упражнение № 9 # =============== hours = int(input()) data = list(map(int, input().split())) k = int(input()) maximum = max([sum(data[i:i + k]) for i in range(hours - k + 1)]) print(maximum)
3cfb075958f24ab01e90794e6261e34e35ee78a4
Yohenba18/Advance-Programing-Practices
/week-2/zero.py
331
3.671875
4
def shift_zero(arr, n): count = 0 for i in range(n): if arr[i] != 0: arr[count] = arr[i] count+=1 while count<n: arr[count] = 0 count+=1 arr = [3, 4, 0, 0, 0, 6, 2, 0, 6, 7, 6, 0, 0, 0, 9, 10, 7, 4, 4, 5, 3, 0, 0, 2, 9, 7, 1] n = len(arr) shift_zero(arr,n)...
1b64e7adb54c25f6a798bd14171089b0b7453992
tggithub619/Codewars_Python
/8 kyu Is this my tail.py
272
3.53125
4
#https://www.codewars.com/kata/56f695399400f5d9ef000af5/train/python def correct_tail(body, tail): return body.endswith(tail) # return body[-1] == tail # #sub = body[len(body)-len(tail)] # if sub == tail: # return True # else: # return False
f86a80b921cdf49c58b308b142e558edb8f99310
yurinmk/python
/Faculdade/exercicioSequencia.py
391
3.890625
4
def sequecia(inicio, fim): #Cria uma lista vazia lista = [] #lista.append incrementa o item a lista for i in range(inicio,fim+1): lista.append(i * i) print(lista) def main(): inicioDaSequencia = int(input("nº de início da sequência = ")) fimDaSequencia = int(input("nº de fim da sequ...
0307e65004a5db61af506448757ff39433ee0182
AG-Systems/MicroProjects
/Essay-Auriga/EssayTyper2.py
630
3.65625
4
import wikipedia import re import random testVar = raw_input("Please input the topic you want the computer write for you: ") print("If you want to best results, please choose the number 2 down below. ") LengthX = raw_input("Please input the length of your essay. Pick 1-10: ") print wikipedia.summary(testVar, sentences...
2fd7755579fcbb6f572c05b6ed9063df2ef091af
chenjiunhan/JAQQRobotKingdom
/world/ptt/test.py
335
3.65625
4
import re s = "第 01~22 行" print(re.search(r"第 ([0-9]+)~([0-9]+) 行", s).group(1)) def findnth(string, substring, n): parts = string.split(substring, n) if len(parts) <= n or n <= 0: return -1 return len(string) - len(parts[-1]) - len(substring) s2 = "aaabbbbbbbaaabbbbbbbaaa" print(findnth(s2, "aaa...
4406bd314cc72273053a7b4cf58f3ff6a373f78a
sekar5in/experiments
/LearnPython/tkintermodule.py
302
3.765625
4
#!/usr/local/bin/python3 # This is basic GUI window creation using tkinter module. from tkinter import * class Window(Frame): def __init__(self, master = None): Frame.__init__(self, master) self.master = master root = Tk() app = Window(root) root.mainloop()
9f8efe04c89d644b9b7365b4b5ae5394f302d55e
ZhiCheng0326/SJTU-Python
/Reverse list.py
472
3.90625
4
def main(): old_list = [] while True: x = raw_input("Please input a number:") if x == "c": break else: print "Enter 'c' to exit!" a = old_list.append(x) reverse_list(old_list) def reverse_list(l): t...
73cb1171bd992ecc890e51f3d5e627240e247f69
atomextranova/leetcode-python
/Template/segment_tree.py
2,139
3.515625
4
class SegmentTree(object): # 总结 # 区间操作,修改值或者一段的值 # 询问区间性质:最大,最小,和。。 def __init__(self, start, end, cur_sum=0): self.start = start self.end = end self.cur_sum = cur_sum self.left = self.right = None @classmethod def build(cls, start, end, array): if start ...
d5335bc09cb9720c99ab3a13880eb238ad76a7c3
SARWAR007/PYTHON
/Python Projects/list_extend.py
489
3.71875
4
list1 = [10,20,30,40] #list1.extend([50,60,70]) list1.count(10) print(list1.count(10)) x = list1.index(40,1,len(list1)) print("List index",x) print(list1) tuple1 =(10,20,30,40) #print(tuple1) print(max(list1)) print(max(tuple1)) list1.pop(2) print(list1) list1.remove(10) print(list1) list1[1]=50 print(list1)...
32546e86c13be2425cc72e4147585ca8260a85c5
hjqjk/python_learn
/test/main/wrapper/wrapper2.py
1,228
3.78125
4
#!/usr/bin/env python #_*_ coding:utf-8 _*_ #装饰器 #当调用装饰器对函数进行装饰,想对原函数调用前后进行修改,为方便自定义修改,传入两个函数参数 def Filter(before_func,after_func): def outer(main_func): def wrapper(arg1,arg2): before_result = before_func(arg1) #调用原函数前的操作 if before_result != None: retur...
a24c0c0ece273c93d43935e3108f5955dc5fe0f2
elgaspar/tkinter-tutorial
/examples/dialogs/hello-world.py
330
3.5625
4
import tkinter from tkinter import ttk, messagebox def do_hello_world(): messagebox.showinfo("Important Message", "Hello World!") root = tkinter.Tk() big_frame = ttk.Frame(root) big_frame.pack(fill='both', expand=True) button = ttk.Button(big_frame, text="Click me", command=do_hello_world) button.pack() root.m...
49e390a8901bf1139ba74cd61efc69f751f633c2
testcg/python
/code_all/day12/exercise02.py
656
4.4375
4
""" 父类:车(品牌,速度) 创建子类:电动车(电池容量,充电功率) """ class Car: def __init__(self, brand, speed): self.brand = brand self.speed = speed class ElectricCars(Car): # 1. 子类构造函数参数:父类参数+子类参数 def __init__(self, brand, speed, battery_capacity, charging_power): # 2. 通过super调用父类构造函数 sup...
d92ca2eba5017a0bcebcb25d659c7aab8402bb7a
qmnguyenw/python_py4e
/geeksforgeeks/python/basic/21_15.py
2,015
4.59375
5
Python Set | update() **update()** function in set adds elements from a set (passed as an argument) to the set. > **Syntax :** > set1.update(set2) > Here set1 is the set in which set2 will be added. > > **Parameters :** > Update() method takes only a single argument. The single argument can b...
5e14273bb3b0e42022010274e89b75760489713a
atulasati/scripts_lab_test
/calc_weekly_pay/hr.py
1,027
3.796875
4
from employee import HR print ("Devoir 4 Anthony Ilunga") print ("Utilisation de classe et module. Script pour manipuler des employé(e)s).\n") hr_direcotory = HR(name='directory') while(True): command = "\n-------------------------------------------\n" command += "1 - Add employees to the directory\n" command +=...
7a8668ea497bb53f1c4ebaf8e27d247f04ca86d4
VitaliStanilevich/Md-PT1-40-21
/Tasks/ProkopovichKL/Самостоятельная 1.py
2,732
3.984375
4
text = 'five thirteen two eleven seventeen two one thirteen ten four eight five nineteen' # Преобразуем в список. text = text.split(' ') print(text) # Словарь для сравнения элементов - перемешан для того, чтобы последующий список # с цифрами был не по порядку. numbers = {'eighteen':18, 'nineteen':19, 'twenty':20, 'fiv...