blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
c892b0004d36908c0fca32091c2261d700f1251a
Eashan123/Laposte_
/packages/le_poste/le_poste/config/logging_config.py
940
4.03125
4
# refer: https://docs.python.org/3/howto/logging.html#logging-advanced-tutorial import logging import sys # Multiple calls to logging.getLogger('someLogger') return a # reference to the same logger object. This is true not only # within the same module, but also across modules as long as # it is in the same Python ...
3c7b2e44ad8bf4f0160f4b8da1a7792a3dbdc597
lees9/ftp-with-socket-programming
/server/ftserver.py
11,556
4.375
4
#!/usr/bin/env python # # Programming assignment 1 for cs372 online by Kamal Chaya # # simple implementation of FTP server in python # USAGE: # 1. In order to run the script w/o typing "python" give yourself # execute permissions. Run the following command in the shell: # chmod +x f...
c0f82a228074325413677ec4ea24c65fe63a73d9
alpaka99/algorithm
/algorithm_class/완전검색_그리디/p_연습3/s1.py
453
4.125
4
""" 연습 문제3. 2의 거듭제곱 2의 거듭 제곱을 반복과 재귀버전으로 구현하시오. """ my_list = [5, 2, 7, 1, 3, 8, 9, 3, 5, 2] # 반복 def power_of_two_iteration(k): answer = 1 for _ in range(4): answer *= 2 return answer print(power_of_two_iteration(4)) # 재귀 def power_of_two_recursion(k): if k == 0: return 1 ret...
bc4d675149f418e5ac29813c6da17335aa30a0de
Dami-o72/mini-project
/incomplete-week-4.py
2,588
4.3125
4
# user input 1 - print """def print_list_or_dict(op): #change name '''Print courier list, products list or orders dictionary''' print(op) print_list_or_dict()""" # user input 2 - create -- rename to new_product/courier """def create(num:str): '''Create new product or new courier''' # product ...
c361b9aeb879c9e2652d1e1b78b3daf825dd8de2
justAnotherMathmo/CrypticConstructor
/assembler.py
6,275
3.90625
4
import numpy as np import re # flag that indicates when we should backtrack class BacktrackException(Exception): pass def backtrack_search(answers, size, symmetric): BLANK = ' ' VOID = '#' # all letters in the completed grid board = np.array([[BLANK for j in range(size + 2)] for i in range(size...
fd18fed3f2b6c8adfa54ce9e5c3d705ad0d6e063
skumartd/PythonIntro
/Day2/Dictionaries.py
1,814
4.5
4
# Example: jobs = {"David": "Professor", "Sahan": "Postdoc", "Shawn": "Grad student"} print(jobs["Sahan"]) # output : Postdoc # Can change in place jobs["Shawn"] = "Postdoc" print(jobs["Shawn"]) # Oupup : Postdoc # Lists of keys and values print(jobs.keys()) # Output : ['Sahan', 'Shawn', 'David'] # note order is diff p...
e808ed4773414a5f8f068fa8a4ae7da5cb4eb225
monaj07/ml
/rl/sumtree.py
4,154
3.75
4
""" This code implements a sumTree data structure, to be used in Prioritized Experience Replay (PER) sampling algorithm. It has O(log(n)) complexity for samplings, insertions, and updates. Great explanation in: https://adventuresinmachinelearning.com/sumtree-introduction-python/ This method is an alternative for straig...
5b52c3470834a83fff234c73b2fdc017b2d15493
EvanJamesMG/Leetcode
/python/Binary Search/033.Search in Rotated Sorted Array.py
2,295
3.640625
4
# coding=utf-8 import collections ''' Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). You are given a target value to search. If found in the array return its index, otherwise return -1. You may assume no duplicate exists in the array. ''' ...
2e7210a960e852010a07e22221ea2c8351e715d2
seocobe/Python_oefeningen_sbm
/donderdag/oefening_collecties.py
1,216
4.03125
4
# lees 3 waarden in van stdin # maak er een tuple van # maak ook de tuple in omgekeerde volgorde # toon beide tuples # geef weer of de omgekeerde tuple groter is dan de oorspronkelijke a = input('geef eerste element in: ') b = input('geef tweede element in: ') c = input('geef derde element in: ') tup = a,b,c print(...
c5c9501e6c18fe2d00019fe4c3c024f83ead8ca1
Hector-hedb12/HackTheNorth2018Challenge
/main.py
256
4.0625
4
import itertools def rotate(m): while m: yield m[0] m = list(reversed(zip(*m[1:]))) def main(): m = [[1,2,3], [8,9,4], [7,6,5]] print list(itertools.chain(*rotate(m))) if __name__ == "__main__": main()
96b000cfffb76131818b45ac62ec301115713dab
yingliufengpeng/algorithm
/zhengwei/extra_python/cmpobject.py
847
3.859375
4
# -*- coding: utf-8 -*- import functools class Student(object): def __init__(self, name, score): self.name = name self.score = score def __str__(self): return '(%s: %s)' % (self.name, self.score) __repr__ = __str__ def __gt__(self, other): # > ...
6dafb78d3fea822988dc95f8fff1b18061145c70
loristissino/oopython
/lessons/21/custom_widget.pyw
4,072
3.53125
4
#!/usr/bin/env python3.1 from tkinter import * from tkinter import messagebox import fractions class FractionWidget(object): def __init__(self, parent, height=10, width=10, background=None): self.parent=parent self.height=height self.width=width self.NumeratorValue=IntVar() ...
22c14efc86b486131f8245160634370641a71609
SergeiLSL/PYTHON-cribe
/Глава 3. Списки, кортежи и словари/Раздел 1. Списки/7.1 Знакомство со списками (массивами)/Задача 3.py
916
3.890625
4
""" Задача №3 Напишите программу, которая считает среднее арифметическое первых трёх элементов массива. Найденное значение округляется, то есть печатается только целая часть, дробная часть отбрасывается. Массив уже задан в программе. Надо обратиться по индексам к указанным элементам и организовать вычисления в формул...
43b0c6aeab42d8937cb26de89c86b5d53afdb469
alexsieusahai/dim
/src/dataStructures/lineLinkedList.py
2,098
4.09375
4
from dataStructures.lineNode import LineNode class LineLinkedList: """ doubly linked list created with lineNode objects each value contains a string (could contain other objects) constructor takes in a list of values, usually strings, to creat the linked list """ def __init__(self,lineLis...
98953b09c12beaafd98a34a0cb76c1d44e8f52ba
chefmohima/DS_Algo
/quick_sort.py
778
3.8125
4
import random def quicksort(A,start,end): # pick random pivot index if start < 0 or end >= len(A) or start>=end: return pivot_index = random.randint(start,end) (p1,p2) = dnf(A,start,end,pivot_index) quicksort(A,start,p1) quicksort(A,p2,end) def dnf(A,start,end,pivot_index): pivo...
368fdcb904663352b71f3d7af00e9684c88a84d0
Tele-Pet/informaticsPython
/Homework/Week 5/bookExercise5.2_viaList_v1.py
540
4.3125
4
# Exercise 5.2 Write another program that prompts for a list of numbers as above and at the end prints out both the maximum and minimum of the numbers instead of the average. import numpy as np usrInput = None usrList = [] while usrInput != 'done': usrInput = raw_input('Enter a number: ') try: usrInput = float(...
64c375227ea2d1b6759b868cffee983aebabd482
inyong37/Study
/V. Algorithm/i. Book/모두의 알고리즘 with 파이썬/Chapter 11.py
944
3.765625
4
# -*- coding: utf-8 -*- # Modified Author: Inyong Hwang (inyong1020@gmail.com) # Date: *-*-*-* # 모두의 알고리즘 with 파이썬 # Chapter 11. 퀵 정렬 def quick_sort_1(a): n = len(a) if n <= 1: return a pivot = a[-1] g1 = [] g2 = [] for i in range(0, n - 1): if a[i] < pivot: g1.appe...
ac374c68621cd0d30ebde38dadcd1e85841dbf1b
Kartavya-verma/Python-Programming
/16.py
173
4.34375
4
#16.Write a python program to display table of a number taken from user input. num=int(input("Enter the number ")) for i in range(1,11,1): print(num ,"*", i,"=",num*i )
7de1d60ead2b8ef15c8d7977f1f3a8cd7da4abaf
sheng1993/datastructures_algorithms
/_4_algorithms_on_strings/Week1/Programming-Assignment-1/trie/trie.py
1,815
3.75
4
#Uses python3 import sys from typing import List, Dict # Return the trie built from patterns # in the form of a dictionary of dictionaries, # e.g. {0:{'A':1,'T':2},1:{'C':3}} # where the key of the external dictionary is # the node ID (integer), and the internal dictionary # contains all the trie edges outgoing from t...
80a46493f9d50ae5c04ba512d3bc9432a691c65d
Saccha/Exercicios_Python
/secao05/ex05.py
287
4.0625
4
""" 5. Faça um programa que receba um número inteiro e verifique se este número é par ou ímpar. """ x = int(input("Digite o valor de x: ")) if (x % 2 == 0): # Resto da divisão print(f'O valor que foi digitado ele é PAR') else: print(f'O valor que foi digitado ele é IMPAR')
84c74294624bd0625c8f63e73c4fa40e40e83f72
LeTurtleBoy/General-Algorithms
/Python_general_purpose/Generators.py
1,008
3.625
4
#generators from time import sleep #top level syntax or function -> underscore method def add(x,y): return x+y class adder: def __init__(self): self.z = 0 def __call__(self,x,y): self.z +=1 return x+y+self.z def compute(): rv = [] for i in range(10): sleep(0.5) rv.append(i) return rv class compu...
b56a0a4d3bd12f19c4954af109e6c7533da86f4c
bloy/adventofcode
/2016/day13.py
2,158
3.859375
4
#!/usr/bin/env python3 import collections def is_space(input_number, x, y): if x < 0 or y < 0: return False num = x*x + 3*x + 2*x*y + y + y*y + input_number num_ones = len([c for c in "{0:b}".format(num) if c == "1"]) return ((num_ones % 2) == 0) def print_map(input_number, size): map_ch...
267082575179466d13ce7d3a3f4fd051f7f256a9
cho-stat/coding-exercises
/intersection.py
515
3.796875
4
class Solution: def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: if len(nums1) < len(nums2): num_set = {num for num in nums1} compare_list = nums2 else: num_set = {num for num in nums2} compare_list = nums1 ...
bddc63619cdf56c8c702c93ff94cc44599a19db4
akimi-yano/algorithm-practice
/lc/978.LongestTurbulentSubarray.py
2,816
3.515625
4
# 978. Longest Turbulent Subarray # Medium # 964 # 154 # Add to List # Share # Given an integer array arr, return the length of a maximum size turbulent subarray of arr. # A subarray is turbulent if the comparison sign flips between each adjacent pair of elements in the subarray. # More formally, a subarray [arr[...
8c1365f56e26fe97f5f383b6836683dd8c579c08
Jyllove/Python
/DataStructures&Algorithms/Sort/heapsort.py
821
4.21875
4
def heap(array,start,end): root = start child = root*2+1 while child<=end: if child+1<=end and array[child]<array[child+1]: child += 1 if array[root]<array[child]: array[root],array[child] = array[child],array[root] root = child child ...
366393da267bfdc9e3558dd8276c6738e92e34d1
jr09/DojoAssignments
/Python/Multiples,Sum,Average/allin1.py
367
3.703125
4
# Multiple Par 1 for idx in range(1,100,2): print idx # Multiples Part 2 for idx in range(5,1000000,1): if(idx%5==0): print idx # Sum List a = [1, 2, 5, 10, 255, 3] sum = 0 for item in a: sum += item print sum # Average a = [1, 2, 5, 10, 255, 3] sum_a = 0 for item in a: sum_a += item print "...
8f5d302380ad4e16c44bf769b750018b506b344d
polonkaipal/Szkriptnyelvek
/hazi feladatok/09.15/20120815e.py
1,724
4.03125
4
#!/usr/bin/env python3 """ Palindróm Írjunk függvényt, mely egy sztringről eldönti, hogy palindróm-e. Egy karaktersorozatot akkor nevezünk palindrómnak, ha visszafelé olvasva megegyezik az eredeti karaktersorozattal, pl.: görög. A feladatot többféleképpen is oldjuk meg: (1) Triviális módszer (Pythonban egy szekvenc...
5a2248958f79e79b325df87dea72cae262cd0a02
jamsidedown/euler_py
/problems/0XX/00X/002/solution.py
294
3.5625
4
def run() -> int: total, first, second = 0, 1, 2 while second < 4_000_000: if second % 2 == 0: total += second first, second = second, first + second return total if __name__ == '__main__': print(f'Sum of even fibonacci numbers under 4M: {run()}')
df6fa5bf6a8ccac896eb39298dc350143e5949a9
taekyunlee/SNU_FIRA_Business-Analytics
/1st semester/파이썬을 이용한 빅데이터 분석 개론/hw5-1 score100.py
1,689
4.09375
4
# Assignment Number... : 5 # Student Name........ : 이택윤 # File Name........... : hw5_이택윤 # Program Description. : 이것은 if_else 문과 while, for 문을 활용하여 원하는 결과를 출력하는 과제입니다. a = int(input('Enter a: ')) # int() 와 input()을 활용하여 각각의 변수 a,b,c에 정수를 선언합니다. b = int(input('Enter b: ')) c = int(input('Enter c: ')) if a>b a...
ff4bf1df1d5e76f43c53579358ddf35438896488
xiaohaier66/python_study
/map.py
153
3.53125
4
alien_0 = {'color':'green'} print("The alien is "+alien_0['color'] + ".") alien_0['color'] = 'yellow' print("The alien is now "+alien_0['color'] + ".")
c5ad6d92040373117ea4a33465aa26f0f53975ee
manojnaidu15498/manset8
/p1.py
70
3.609375
4
s=input() ns=s[::-1] if s==ns: print('yes') else: print('no')
39b770c6cd5d262efc4c887a4a388765a969167b
oscarDelgadillo/AT05_API_Test_Python_Behave
/GermanQuinonez/sessions/session1_examples.py
887
3.703125
4
# Values and types print(type(1)) print(type("Somthing")) print(type(0.2)) # Variables Message = "hi" n = 1000 pi = 3.04e500 print(type(Message)) print(type(n)) print(type(pi)) # Membership operators a = 1 b = 2 list = [1, 2, 3, 4, 5]; if (a in list): print("a exists list") else: print("a does not exist li...
c090ccd81e1c69ef0cf819397821efb710385eb9
hilariusperdana/praxis-academy
/novice/01-01/latihan/shellsort.py
547
3.828125
4
def shellsort (arr): n = len(arr)//2 while n > 0: for mulai in range(n): gapInsertionSort(arr,mulai,n) print("setelah",n,"listnya",arr) n = n // 2 def gapInsertionSort(arr,start,gapP: for i in range(start+gap,len(arr),gap): value = arr[i] position = i ...
08c2942c26d0c382b7ce410f434f638f1fad0704
yukiko1929/python_scripts
/function_basic.py
978
4.125
4
# 関数に関する基本的な知識 # def sentence(name, department, years): # print('%s is at %s for %s years' % (name, department, years)) # print(sentence()) #TypeError: sentence() missing 3 required positional arguments: 'name', 'department', and 'years' # print(sentence('yuki')) # print(sentence('yuki', 'MP', '5')) # print(sent...
10ee7a231767d1583053ee7970753cce97a0fda5
MoritzSchwerer/Maze
/src/algorithms/generators/backtracker.py
935
3.796875
4
from src.algorithms.generators.generator import Generator class Backtracker(Generator): def __init__(self, board): self.board = board self.current = self.choose_start(board) self.initial = self.current self.stack = [] def choose_start(self, board): tiles = self.board...
2ee75810b80ede9ca2d099190baf2a5157f3a1c4
wangminli/codes
/python/defaultdict.py
225
3.609375
4
#! /usr/bin/env python # -*-coding:utf-8 -*- 'defaultdict,对dict添加一个默认值' from collections import defaultdict dd = defaultdict(lambda: '==> :no this value') dd['key1'] = 'abc' print dd['key1'] print dd['key2']
9266397b9bdd7e11e1047ff431a060fe789a5694
adqz/interview_practice
/algo_expert/p26_reverse_linked_list.py
608
3.875
4
# O(n) time | O(1) space def reverse(head): node = head if node.next == None: return head prev_node = None # 1. Reverse links until last element while node.next != None and node.next.next != None: next_node = node.next next_next_node = node.next.next # Reverse ...
9191dc53a92190dc08fdd2c79a6e5b22dce8d750
lotabout/leetcode-solutions
/617-merge-two-binary-tree.py
824
3.921875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # https://leetcode.com/problems/merge-two-binary-trees/description/ from util import TreeNode class Solution(object): def mergeTrees(self, t1, t2): """ :type t1: TreeNode :type t2: TreeNode :rtype: TreeNode """ if t1 ...
44bcadcde07d95f6d112b5a939b7f4305db0da91
lorodin/py-lesson8
/task7.py
1,387
4.0625
4
# 7. Реализовать проект «Операции с комплексными числами». # Создайте класс «Комплексное число», реализуйте перегрузку методов сложения и умножения комплексных чисел. # Проверьте работу проекта, создав экземпляры класса (комплексные числа) и выполнив сложение и # умножение созданных экземпляров. Проверьте корректность ...
a4fa1006b6923c940032476160f26b4a2e4ef50d
tranxuanduc1501/Homework-23-7-2019
/Bài 2 ngày 23-7-2019 ( Cách ngu).py
425
3.859375
4
listnumber= [129,2,182,41,439] a= int(input('Enter a number: ')) if a!=129 and a!=2 and a!=182 and a!=41 and a!=439: print('Number not found in the list') elif a==129: print('Number found. Position 1') elif a==2: print('Number found. Position 2') elif a==182: print('Number found. Position 3') ...
058350f37a2143994fef846169735b8826fea047
DK333D/AGH_Algorithms
/SEM_1/python/Ex 2018/can_create_0_sum/main.py
777
3.734375
4
def find(array, curr_line=0, curr_sum=0) -> (bool, []): result = [] if curr_sum == 0 and curr_line >= len(array): return True, result if curr_line >= len(array): return False, result for i in range(len(array[curr_line]) + 1): if i == len(array[curr_line]): return F...
9da3bd19daaa7a02153c4373cd1844f01d6ad250
hasnatosman/sum_cube
/cube_sum.py
225
4.25
4
def cube_sum(num): sum = 0 for n in range(num + 1): sum = sum + n ** 3 return sum user_num = int(input('Enter a number: ')) result = cube_sum(user_num) print('Your sum of cubes are: ', result)
948453d9e75087f16c4785803892a1d1ffa9df13
afaubion/Python-Tutorials
/Code_Introspection.py
1,245
3.578125
4
# Code introspection is the ability to examine classes, functions and keywords # to know what they are, what they do and what they know. # Python provides several functions and utilities for code introspection. """ help() dir() hasattr() id() type() repr() callable() issubclass() isinstance() __doc__ __name__ """ # O...
6bfd0499452e9064f200fe1d382f366c2ef2cc91
ThomArm/snips-skill-sonos
/snipssonos/provider/provider_player_template.py
4,276
3.515625
4
import abc from abc import ABCMeta, abstractmethod import sys if sys.version_info >= (3, 4): ABC = abc.ABC else: ABC = abc.ABCMeta('ABC', (), {}) class A_ProviderPlayerTemplate(ABC): """ Abstract Class to create a music provider as Spotify, Soundclound you have to create at least one of t...
76bc06baf83941444925155cc2fd668f4ba1c6d5
sagarnikam123/learnNPractice
/hackerEarth/practice/dataStructures/arrays/1D/theAmazingRace.py
1,588
3.703125
4
# The Amazing Race ####################################################################################################################### # # As the Formula One Grand Prix was approaching, the officials decided to make the races a little more interesting # with a new set of rules. According to the new set of rule...
c464a63272bf7a280e5baca41cc0f5386f205bfc
zaid-sayyed602/Python-Basics
/if else_2.py
116
3.703125
4
number1=input("enter no 1") number2=input("enter no 2") print("number1 is",number1) print("number2 is",number2)
4575352727f3905c627aa642b11231da4f55ad55
othLah/Email_Sender
/emailSender.pyw
10,246
3.5625
4
''' This code present a simple application to send text mails from a gmail,live,yahoo and gmx accounts to any other email address, gmail and yahoo ask for the "Less Secure App" option to be actived but don't worry, the app will guide you to the right place. Enjoy and Leave your comments ;) ''' impo...
dc5b5ccd096855e87a3ae3777d5e9677126fb3b4
elveera0491/SimpleSockets
/server.py
2,202
3.546875
4
import socket import threading PORT = 5000 HEADER = 64 SERVER = socket.gethostbyname(socket.gethostname()) FORMAT = 'utf-8' ADDR = (SERVER, PORT) DISCONNECT_MESSAGE = "Client Disconnected" server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(ADDR) def handle_client(conn, addr): ''' Hand...
637a4afd8df595740820901f6f92175bcf0b6d61
mbassale/computer-science
/book2-algorithms-sedgewick/ch2/03_shell_sort.py
1,597
3.671875
4
from math import floor import sys import random import time class ShellSort: def sort(self, items) -> None: h = 1 while h < len(items) // 3: h = 3 * h + 1 # 1, 4, 13, 40, 121, 364, 1093, ... while h >= 1: for i in range(h, len(items)): j = i ...
c7726ea73793143b840221ffe03d8762b3442f51
marsied107/CS0008-f2016
/Ch3-Ex/Ch3-Ex8.py
289
4.15625
4
#Prompts the user to enter the number of people attending the party and how many hot dogs they will be given people = int(input('Enter the number of people attending the party: ')) hotdogs = int(input('Enter the number of hot dogs each person will be served: ')) total = people * hotdogs
6e3660f6ea66e0baf14dbe45b7a4c59062cbf656
dante092/Password
/password.py
1,426
3.796875
4
import re def digitRegex(testpassword, digit_list): 'Returns a list of Digits in password.' digitRegex = re.compile(r'\d') digit_list = digitRegex.findall(testpassword) return digit_list def characterRegex(testpassword, character_list): 'Returns a list of characters in password.' characterRege...
5279912fcad3e1a8e145784ae46cfd3743e541b7
SeffuCodeIT/pythoncrashcourse
/functions.py
552
3.890625
4
# name = input() # print("Nice to meet you" + name) # def greeting(): # print('Hello there my friend') # print('what is your name') # name = input() # print("my name is" + name) # greeting() # greeting() def greeting(name): print('Hello there' + name) # greeting('Seffu') def multiply_by_10(number...
475b6ca8dc219c3259c81efae79e07886921bee9
sidhumeher/PyPractice
/LeetCode/Arrays/twoSum.py
1,275
3.5625
4
''' Created on Apr 20, 2020 @author: sidteegela ''' def twoSum(nums,target): result = [] ''' for i in range(len(nums)-1): for j in range(1,len(nums)-1): if nums[i] + nums[j] == target: result.append(i) result.append(j) ''' ''' for i in range...
836bb4d2fc506e0e9a6916ffd5c186229532ed50
carolana/learning-area
/projects/scripts/nome-completo.py
318
3.9375
4
nome = str(input('Digite seu nome completo: ')).split print('Seu nome com todas as letras maiusculas é {}'.format(nome.upper())) print('Seu nome em minusculo é {}'.format(nome.lower())) print('Seu nome tem {} letras'.format(len(nome)- nome.count(' '))) print('Seu primeiro nome tem {} letras'.format(nome.find(' ')))
7579c07e26aa0645a96eb7d0118096f58573e607
Amithmg6/ipl_data_analysis_python
/test folder/spark.py
4,519
4.15625
4
# Verify SparkContext # print(sc) # Print Spark version # print(sc.version) # Import SparkSession from pyspark.sql from pyspark.sql import SparkSession # Create my_spark my_spark = SparkSession.builder.getOrCreate() # Print my_spark print(my_spark) # Print the tables in the catalog print(spark.catalog.listTables()...
e23d5e81dbea99a3c548a0f344faeed4670680d4
kuritan/codility-practice
/Lesson6-Triangle.py
1,158
3.75
4
# An array A consisting of N integers is given. # A triplet (P, Q, R) is triangular if 0 ≤ P < Q < R < N and: # # A[P] + A[Q] > A[R], # A[Q] + A[R] > A[P], # A[R] + A[P] > A[Q]. # For example, consider array A such that: # # A[0] = 10 A[1] = 2 A[2] = 5 # A[3] = 1 A[4] = 8 A[5] = 20 # Triplet (0, 2, ...
64c5b1e80e20e2824b5592f3d78f3a91e3227dd1
Harnet69/HomeWork1
/fibonacciNumbersRecc.py
579
4.15625
4
# calculate a number of Fibonacci def fib_num(n): if n == 1: return 0 if n == 2: return 1 return fib_num(n-1) + fib_num(n-2) # create and fill sequance with number of Fibonacci def fib_seq(n): seq = [] for i in range(1, n+1): seq.append(fib_num(i)) return seq #...
8ee4983f9ed9c28d47dcefa261662985ffb5a6b1
liujunsheng0/notes
/lintcode/permutation-index.py
1,018
3.625
4
#!/usr/bin/python3.6 # -*- coding: utf-8 -*- """ https://www.lintcode.com/problem/permutation-index/description 给出一个不含重复数字的排列, 求这些数字的所有排列按字典序排序后该排列的编号. 编号从1开始. 输入:[1,2,4] 输出:1 样例 2: 输入:[3,2,1] 输出:6 """ class Solution: """ @param A: An array of integers @return: A long integer """ def permutat...
f5e688029674df61e56808b19089510184e3f681
paulocaram/PENTEST
/MODULO04/portscan.py
1,116
3.53125
4
#!/usr/bin/python # Informa que irei utilizar as rotinas de socket import socket import sys def sai(): sys.exit() def resolva(): try: dominio = raw_input("Digite o dominio: ") print dominio,"=====>",socket.gethostbyname(dominio) print "\n" except Exception as e: print "E...
8228947acfb5a2bf16f229b72d76d2fe2fe226d3
ed-cetera/project-euler-python
/053_solution.py
583
3.578125
4
#!/usr/bin/env python3 import math import time def binomial_coefficient(n, r): return math.factorial(n)//(math.factorial(r) * math.factorial(n - r)) def main(): n_limit = 100 lower_noninclusive_limit = 1000000 counter = 0 for n in range(1, n_limit + 1): for r in range(1, n + 1): ...
544b1ef122cd72095c4336b5a377e16c11522a46
StevenSoares14/ASTR_119
/annual_savings.py
1,471
4.0625
4
# -*- coding: utf-8 -*- # anaconda2/python 2.7 """ Compute annual dollar amount on savings invested at float_Interest over int_Years years Variables: int_Years = durations of investment flt_Interest = interest rates flt_iniInvest = initial investment """ #import numpy #========...
49521eeead27ec5c05aa3b9ecd06aa9d2e9f3660
elim168/study
/python/basic/pillow/10.ImageDraw_画图_test.py
1,295
3.515625
4
from PIL import Image, ImageDraw, ImageFont # 创建一个图片 image = Image.new('RGBA', (500, 300), 'green') # 获取该图片的画笔,之后都通过该画笔进行绘画 draw = ImageDraw.Draw(image) # 画一个矩形,起点是(20, 20),终点是(480, 280)。 draw.rectangle((20, 20, 480, 280), fill='red', outline='blue') draw.text((50, 50), 'Hello World!', fill='blue') # 写的字如果是中文需要指定字体 d...
997f758e9a49a373c0a88fecccb81f06e00653c6
PanMaster13/Python-Programming
/Week 8/Week 8, Functions/Tutorial Files/Week 8, Exercise 2.py
325
3.875
4
def function_2(): print("User input") ipt = input("What's your message?") list1 = [] counter = 1 for i in range(0, len(ipt)): list1.append(ipt[len(ipt)-counter]) counter +=1 list1 = "".join(list1) print("\n~Output") print("Message in reverse order:", list1) function...
9ca77f753e4299febecff8e9e956de70373410ff
JagritiG/interview-questions-answers-python
/code/set_1_array/34_find_range_sorted_array.py
1,456
4.03125
4
# Find first and last position of element in sorted array # Given an array of integers nums sorted in ascending order, # find the starting and ending position of a given target value. # Your algorithm's runtime complexity must be in the order of O(log n). # If the target is not found in the array, return [-1, -1]. # E...
3195155e7854a870d1212bff880762aeeb7b9cf6
ubco-mds-2018-labs/Data533_Lab4_Sang_Wiese
/health/conversion/find_age.py
498
4.09375
4
from datetime import date from datetime import datetime def year_to_age(name,bdate): #enter a string in form yyyy-mm-dd today = datetime.now() # Calculate age try: dt = datetime.date(datetime.strptime(bdate, "%Y-%m-%d")) age = today.year - dt.year if today.month < dt.month or (today...
6096a537d591e25362b1f093421899f37262f566
Yousef497/Professional-Data-Analyst-Track
/Exercises/Factorial with While.py
455
4.46875
4
# number to find the factorial of number = 6 # start with our product equal to one product = 1 # track the current number being multiplied current = 1 # write your while loop here while current <= number: product *= current current += 1 # multiply the product so far by the current number ...
9579a0f65b4a5268924979366b837525ae34d0f7
hoogland/AdventOfCode2018
/day2.py
982
3.875
4
filename = "resources/day2.txt" boxes = [str(x).rstrip() for x in open(filename).readlines()] def check_freq(str): freq = {} for c in str: freq[c] = str.count(c) return freq #star 1 solution twoOccurance = 0 threeOccurance = 0 for box in boxes: frequencies = check_freq(box) if 2 in frequen...
83b205af7cea7e738f0e0e010fc73d1ff344ab2a
yungjoong/leetcode
/58.length-of-last-word.py
1,113
3.640625
4
# # @lc app=leetcode id=58 lang=python3 # # [58] Length of Last Word # # https://leetcode.com/problems/length-of-last-word/description/ # # algorithms # Easy (32.47%) # Likes: 582 # Dislikes: 2252 # Total Accepted: 356.3K # Total Submissions: 1.1M # Testcase Example: '"Hello World"' # # Given a string s consists...
f0fb4b6bcd0cbcc6f6b99eab87a70040b4d6ed07
JvRahul/DataStructures
/strings_lists_dicts_exercises.py
9,202
3.90625
4
#python :average length of words. l = 'Geeks', 'for', '', 'Rahul' v = l.split(',') def avg(L): if L == "": return None c= 0 for i in L: i = i.strip() print(i) c = c + len(i) print(c) n = len(L) print(n) avg = c/n return avg def AverageLenWords(sentence): words = sentence.split()...
102882f2ce1b0a2f155c417e7a015bb1ef49b599
Super0415/Python
/mycollect/lesson/lesson02/lesson02/homework.py
1,571
3.9375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # author:fei time:2018/11/27 # 数字类型:整数、浮点数、复数 # 初始数字类型 a = 5 b = 5.66 c = "6" # d = 1 + 2j print("a:", a) print("a的类型为:", type(a)) # a的类型为: <class 'int'> print("b:", b) print("b的类型为:", type(b)) # b的类型为: <class 'float'> print("c:", c) print("c的类型为:", type(c)) # c的...
292ec6ccbbf456f227d32ef18c01e460d761c035
chaoswork/leetcode
/056.MergeIntervals.py
1,133
3.96875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Author: Chao Huang (huangchao.cpp@gmail.com) Date: Mon Feb 26 19:57:12 2018 Brief: https://leetcode.com/problems/merge-intervals/description/ Given a collection of intervals, merge all overlapping intervals. For example, Given [1,3],[2,6],[8,10],[15,18], return [1,6]...
b49e8ed37014f1032faef58a2cc1bfad2b778b5d
shawnco/pyverse
/classes/objects/station.py
324
3.65625
4
''' General implementation for a Station object. These are constructed and float stationary in space. ''' import pygame class Station(pygame.sprite.Sprite): ''' Constructor doesn't do much. ''' def __init__(self): pass ''' Updates the display ''' def update(self): ...
a732b38d1d44c8de9eb7161abeef512a2001097c
misrashashank/Competitive-Problems
/construct_binary_tree_from_in-pre.py
1,366
4.09375
4
''' Given preorder and inorder traversal of a tree, construct the binary tree. Note: You may assume that duplicates do not exist in the tree. Example: preorder = [3,9,20,15,7] inorder = [9,3,15,20,7] Return the following binary tree: 3 / \ 9 20 / \ 15 7 ''' # Definition for a binary tree node. ...
a85f4ffc36f89ba36a72f629501a8f933377332b
sodewumi/dictionary_word_count
/wordcount.py
976
3.5625
4
from sys import argv from collections import Counter script, filename = argv def count_words(filename): open_file = open(filename) rm_punctuation = [] word_count = {} for line in open_file: words = line.rstrip().split(" ") for word in words: alpha_wrd = "" ...
5108298808215f1151f28e700184bb05ae9b9ecd
AkshayGyara/Linked-List-2
/reorderList.py
1,192
3.828125
4
#143. Reorder List #Time Complexity : O(n) #Space Complexity : O(n) #Did this code successfully run on Leetcode : Yes class Solution: def reorderList(self, head: ListNode) -> None: """ Do not return anything, modify head in-place instead.slow """ if not head: r...
71c98f1dd557c921a809ea37eec3594902639503
zly7674/ThirdProject
/py实验一/bll.py
2,015
3.96875
4
# 1)添加学生信息 def add_student_info(): L = [] while True: n = input("(按回车直接退出)\n请输入名字:") if not n: # 名字为空 跳出循环 break try: a = int(input("请输入年龄:")) s = int(input("请输入成绩:")) except: print("输入无效,重新录入信息") continue info ...
e9fb91a55503f0e9482f8fdb4a54bb1550813e45
rorymer1989/testproject-python-sdk-example
/tests/traditional/test_duckduckgo.py
1,058
3.625
4
""" This module contains traditional pytest test cases. They test searches on the DuckDuckGo website. """ # ------------------------------------------------------------ # Imports # ------------------------------------------------------------ import pytest # ----------------------------------------------------------...
4a03a7990cc748c73585c9db9f97787fdd1728e0
srishtishukla-20/List
/Q10(Tables).py
801
3.671875
4
l=[1,2,3,4,5,6,7,8,9,10] i=int(input("enter number")) j=0 while j<len(l): print(i,"*",j,"=",i*l[j]) j=j+1 #table List=[1,2,3,4,5,6,7,8,9,10] i=int(input("enter number")) j=0 while j<len(List): print(i*List[j]) j=j+1 #any table l=[0,1,2,3,4,5,6,7,8,9,10] i=int(input("enter number")) j=1 while j<len(l): print(i,"×",...
c60bacc93f9dcb4bc528892c3ee9578d1a60ddb1
lonnie-nguyen/TripIt
/main.py
3,566
3.84375
4
''' main.py: Project MapQuest_API Created on Aug 24, 2021 @author: lon ''' import out import maps import gui ''' CLI Gets user input of location number. User inputs the locations. Locations are appended to a list. ''' def inputlocations(): #CLI code while True: try: locnum = int(i...
efe2fc06868853c1589325b59ef7dfcf6fc89977
komap2017/soc
/edtext.py
1,840
3.59375
4
# -*- coding: utf8 -*- import re import string def clean(string): # From Vinko's solution, with fix. return re.sub('\W+',' ', string.lower()) #return regex.sub('', string.lower()) def lighter_clean(string_to_clear): symbols = set(string.punctuation) symbols.remove('.') symbols.remove...
94ab0df69caec7bee1e7b5dd1f7e20b815d20bc7
jiajia15401/pywidget
/pywidget/AI/__init__.py
830
3.5
4
__all__ = ['ai'] v = '1.0.0' class ai(): def make(self,path): n = path + '.py' self.name = n s = open(n ,'w') run = '''class ai(): name = "%s" def __init__(self): self.list = [] self.add = [] def why(self): pass def think(self): self.wh...
9b7964bbedf26fe7e633067754f4ad1aa4b7bc11
cainellicamila/FRRo-Soporte-2018-Grupo4
/Tp3-11.py
590
3.9375
4
''' Ejercicio 11 Programar un función Divide que ingresa dos valores x, y y devuelve el cociente x/y. La función tiene que tener control de error, que imprima el nombre y el tipo de error. Ejemplos: Divide(6,0) Divide(60,”hola”) Divide(True,5) ''' def Divide (x, y): try: res = x/y except Zer...
2eabb4ed1a8c30bba46e341725b1b3cfb0609f0f
PatrickHuembeli/Adversarial-Domain-Adaptation-for-Identifying-Phase-Transitions
/Code/Gradient_Reverse_Layer.py
1,546
3.578125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Gradient Reversal Layer implementation for Keras Credits: https://github.com/michetonu/gradient_reversal_keras_tf/blob/master/flipGradientTF.py """ import tensorflow as tf from keras.engine import Layer import keras.backend as K def reverse_gradient(X, hp...
d75e266a89aceb34445a35e2fcf5a387e1fb5597
pooja-subramaniam/2018_day2
/pass.py
566
3.65625
4
def get_credentials(): username = input('Please type your user name: ') password = input('Please type your password') return username, password def authenticate(username, password, pwdb): if username in pwdb: if pwdb[username] == password: return True return False def add_user(...
f14aafa44ed0f040b2638de7ca7ca0a47ebd1e50
valthalion/ohhi
/cp_solver.py
4,287
4.25
4
""" Solve a constraint programming problem """ def propagate_constraints(problem, constraints): """ Apply the constraint propagation functions in constraints to problem. Each constraint in constraints should update the values in the problem and return True if changes were made, False otherwise. ...
a6d806085cb9e990a86bb15ce0d40294ada9e8fd
yamatakudesu/enshu
/gittest/RI/main.py
559
3.578125
4
#! /usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt from network import Net def main(): net = Net([784,100,50,10]) print("neurons: {}".format(net.neurons)) B, W, acc, count = net.update(noise=0) x = np.array([i for i in range(count)]) y = np.array([ac...
313002c94f71331f28457a740cdb35974802fac8
CSmel/pythonProjects
/item_program/item_program.py
1,762
4.34375
4
import retailitem def main(): # Get a list for the retail objects. info = make_list() # Display the data in the list. display_list(info) # The _list function will ask the user how many retail items need # to be entered. The function will then return a list of item objects #...
9503c8b88e4d91654b223be96d31c94901a0d6fe
cowerman/python
/fir_11_19/input.py
195
3.96875
4
print("------------------Please input---------------") tmp=input("waiting for input: ") tmp=int(tmp) if tmp == 8: print("entered 8\n") else: print("enter not 8\n"); liu="100" print(int(liu))
196b2e73adf91b2e5b4df165ac4531ce3c6302fa
kpatel010/CS116
/Assignment 3/unicode_encoding.py
1,061
3.875
4
def unicode_encoding(s): ''' Return the correct UTF-8 binary encoded string dependant on s unicode_encoding: Str -> Str Requires: 0 < len(s) < 21 S inputted into unicode_encoding will either be '0' or have a leftmost digit of '1' S can have either digits '1' or '0' Examples: unicode_...
c8df6e18279a635e033538a8374f302fc7e7a09c
thomas-kw/birthday_wisher
/main.py
3,162
4.28125
4
##################### Normal Starting Project ###################### MY_EMAIL = "my_email@gmail.com" MY_PASSWORD = "abcd1234" # 1. Update the birthdays.csv with your friends & family's details. # HINT: Make sure one of the entries matches today's date for testing purposes. e.g. #name,email,year,month,day #YourName,...
802948f0da443583188ce1a30044cd8a51bb0532
DaliahAljutayli/PythonCode
/Convert Decimal to Binary, Octal and Hexadecimal/Python Program to Convert Decimal to Binary, Octal and Hexadecimal.py
810
4.28125
4
#By Daliah Aljutayli #Python Program to Convert Decimal to Binary, Octal and Hexadecimal #Help: geeksforgeeks.org #---------------------- def desTbin(Decimal): if Decimal>1: desTbin(Decimal//2) print(Decimal%2,end='') def desToct(Decimal): if Decimal>1: desToct(Decimal//8...
f4950a82185c0aea01d72623a8a1aa4afe6bc2ce
stromatolith/py_schule
/ex04_amoeba_economy/ae_00a_random_walk.py
3,880
4.21875
4
#! /usr/bin/env python """ Once we can create moving circles with pygame, we can use that to start working on simulations of populations of moving and interacting little things. Preliminaries, step A: Let's create one moving dot doing a random walk and make sure it doesn't leave the box. """ import numpy as np from nu...
fd881fb8b83ebc085d34b128a1b4857123e2c83e
Yashmistry11/InnovationPython_Yash
/NUMBERS AND VARIABLES.py
123
3.734375
4
X = 20 ; Y = 40.5; Z = "Yash Mistry" # print( X, Y, Z ) print("Hello, this is my first python file") x=10 y=20 print("x")
a1ed9725064fd91660022b1534097ea59450e67d
Mostofa-Najmus-Sakib/Applied-Algorithm
/Leetcode/Python Solutions/Strings/ReverseVowelsofAString.py
2,056
3.765625
4
""" LeetCode Problem: 345. Reverse Vowels of a String Link: https://leetcode.com/problems/reverse-vowels-of-a-string/ Language: Python Written by: Mostofa Adib Shakib Time complexity: O(n) Space Complexity: O(n) """ class Solution: def reverseVowels(self, s: str) -> str: length = len(s) # Calculate...
61eb06fa13186485450fbf851cc67827be7d634c
ictcubeMENA/Training_one
/codewars/8kyu/doha22/kata8/posotive_negative/positive_negative.py
410
3.75
4
def count_positives_sum_negatives(arr): res_num = [0,0] if (arr == [] ): return [] for n in arr: if(n> 0 ): res_num[0] += 1 elif(n < 0): res_num[1] += n return res_num def count_positives_sum_negatives2(arr): pos = sum(1 for x in arr ...
5cd1af8789fd03566ea1896673eab1c9f8374518
WonyJeong/algorithm-study
/koalakid1/Math/bj-3009.py
415
3.5625
4
import sys input = sys.stdin.readline x = {} y = {} other_x = [] other_y = [] for i in range(3): _x, _y = map(int, input().strip().split()) if _x not in x: x[_x] = [i] other_x.append(_x) else: other_x.remove(_x) if _y not in y: y[_y] = [i] other_y.append(_y) ...
8566b6be101a8839b2bd0a127ddf61e1e791f3bc
ottomattas/py
/user-input.py
962
4.25
4
#!/usr/bin/env python """This is a simple user input function.""" __author__ = "Otto Mättas" __copyright__ = "Copyright 2021, The Python Problems" __license__ = "MIT" __version__ = "0.1" __maintainer__ = "Otto Mättas" __email__ = "otto.mattas@eesti.ee" __status__ = "Development" # DEFINE THE USER CHOICE INPUT FUNCTIO...
c70942bb49117831530bc3ae8ddf3e6a45a69c56
anu-coder/Basics-of-Python
/scripts/L3Q48.py
195
3.875
4
''' Write a program which can filter() to make a list whose elements are even number between 1 and 20 (both included). ''' even = filter(lambda x: x%2==0, range(1,21)) print([i for i in even])
ca41df81c90979ec1bda8e1bd31daecc2ac7a19b
gcvalderrama/python_foundations
/atest/IntegertoEnglishWords.py
1,048
3.546875
4
def getHundred(y): sb = "" units = ["", "One ", "Two ", "Three ", "Four ", "Five ", "Six ", "Seven ", "Eight ", "Nine ", "Ten ", "Eleven " , "Twelve ", "Thirteen ", "Fourteen ", "Fifteen ", "Sixteen ", "Seventeen ", "Eighteen ", "Nineteen "] tens = ["", "", "Twenty ", "Thirty ", "Forty ", "Fifty ",...
c2626775f87d1ad7cde152a8748528fcb1f6605c
katger4/uwmediaspace
/add_bionote.py
3,006
3.515625
4
#!/usr/bin/env python import pickle # this python script takes in a list of resources from an ASpace repo, filters that list by a specified creator, then adds a biographical note or a historical note (from a text file) to each resource ############################################################ def load_pickled(f...