blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
40da267aa5a58daf6edc9d5f6e2077b987d6b38c
mmilett14/cracking-the-coding-interview
/chapter-1-arrays-and-strings/1.4-palindrome-permutation.py
546
3.890625
4
def palindrome_permutation(string): string = string.lower().replace(" " , "") letter_counter = {} odd_counter = 0 for char in string: if char not in letter_counter: letter_counter[char] = 1 else: letter_counter[char] += 1 ...
33918da738639817797a8e653d7947bcd8bdb5b3
natiawhitehead/-MasterInterview_Udemy
/Section_12/insertion_sort.py
838
3.703125
4
def shiftArray(nums,indStart,indEnd): while indStart < indEnd: nums[indEnd] = nums[indEnd-1] indEnd -= 1 def insertionSort(nums): for i in range(1,len(nums)): predIndex = i-1 while predIndex >= 0 and nums[i] < nums[predIndex]: predIndex -= 1 temp = nums[i] ...
d35cd5034e3693fdf80854cdbd0d2aceba5176db
msadhimb/Praktikum-Semester-2
/latihan.py
198
3.5625
4
jam = int(input("Jam berapa sekarang : ")) if 7 <= jam < 12: print("Pagi") elif 12 <= jam < 15: print("Siang") elif 15 <= jam < 18: print("Sore") elif 18 <= jam < 24: print("Malam")
0a807fb3c13185ceeea276eca5e902e55fbbbf69
sikm31/yuri
/test/class2
533
3.78125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- class Critter(object): def __init__(self, name): print("A new critter has been born!") self.name = name def __str__(self): rep = "Critter object\n" rep += "name: " + self.name + "\n" return rep def talk(self): print("Hi.I'm", self.name, "\n") # main crit1...
4144f50c03022e4cc9aec97ca6380a51b5ee586f
SamuelEsd/Algorithmic_Toolbox
/week2_algorithmic_warmup/7_last_digit_of_the_sum_of_fibonacci_numbers_again/fibonacci_partial_sum.py
935
3.8125
4
# Uses python3 import sys def calc_fib(n): a = 1 b = 1 if (n == 0): return 0 elif (n < 3): return b else: n -= 2 while(n > 0): temp = b b = a + b a = temp n -= 1 return b def get_period_len(n,m): a = 1 ...
aebd1bb31d4a7333ac6b47bb93e3a455827d7399
CarloZoc7/Bioinformatics_labs
/lab02/lab02es02/lab02es02.py
2,959
4.03125
4
""" Assignment 2: Local alignment A local alignment approach tries to identify the most similar subsequences that maximize the scoring of their matching parts and the changes needed to transfer one subsequence into the other. The dynamic programming approach tabularizes optimal subsolutions in matrix S, where an entry ...
97ad8f7d87ea5998f504768012c6b4468a3c54e0
kiiiswa/kiiiswa.github.io
/oop/starter.py
622
3.890625
4
class vehicle: def __init__(self, name): self.name = name self.wheels = 0 self.ingnition = False self.passengers = [] self.windows = 0 def add_passenger(self,passenger): self.passengers.append(passenger) def set_color(self,color): self.color = color ...
4a6e83d32aea808f2f164d62a1365dc3c44e26db
liorkesten/Data-Structures-and-Algorithms
/Data_Structures/MinHeap.py
4,439
3.921875
4
from collections import deque from Data_Structures.MyHeap import * class MinHeap(MyHeap): """ Min heap object: Extract Min - O(1) Build Heap - O(n) Insert - O(log(n)) Delete - O(log(n)) """ def __init__(self, array=[]): MyHeap.__init__(self, array) # self.build_heap(ar...
23d85ac14a5c8fc509d33deb46555664f3422997
suryanshsoni27/pythoncodes
/kirnanger.py
766
3.71875
4
import matplotlib.pyplot as plt import numpy as np def angry(b): if b == 1: print("i am sorry") t = np.arange(0, 2 * np.pi, 0.1) x = 16 * np.sin(t) ** 3 y = 13 * np.cos(t) - 5 * np.cos(2 * t) - 2 * np.cos(3 * t) - np.cos(4 * t) plt.plot(x, y) plt.show() else: print("puchi puchi") print("...
030b3cac2a0285cb35d244ef3fcaa35c81573ccb
anumike/dragon
/star.py
582
3.578125
4
import turtle import tkinter tkinter.Tk() t = turtle.Pen() for x in range(1, 6): t.forward(10) if x % 2 == 0: t.left(9) else: t.left(99) def my_star(beam, fill): if fill == True: t.begin_fill() for x in range(1, 19): t.forward(beam) if x % 2 == 0: t.left(...
60120898d9bf9008e1e28b87b69dfd91eb31a8bb
UchihaSean/LeetCode
/0085/MaxRect.py
1,672
3.578125
4
class Solution(object): def maximalRectangle(self, matrix): """ :type matrix: List[List[str]] :rtype: int """ if matrix==[]: return 0 for i in range(len(matrix)): for j in range(len(matrix[0])): matrix[i][j] = int(matrix[i][j]) ...
5ea979e20218eb5fb395abe3568eaaa9dd407cee
takecian/ProgrammingStudyLog
/LeetCode/0/54.py
966
3.515625
4
class Solution(object): def spiralOrder(self, matrix): """ :type matrix: List[List[int]] :rtype: List[int] """ return matrix and list(matrix.pop(0)) + self.spiralOrder(zip(*matrix)[::-1]) class Solution: def spiralOrder(self, matrix: List[List[int]]) -> List[int]: ...
c84372c774048f05cbd3f5230ba49a011e631e29
HernanFranco96/Python
/Curso de Python/Intro-python/Python/14_Herencia.py
494
3.65625
4
class Usuario: # El primer argumento, hace referencia a la instancia. def __init__(self, nombre, apellido): self.nombre = nombre self.apellido = apellido def saludo(self): print('Hola, mi nombre es ',self.nombre, self.apellido) #Indicamos entre parentesis que hereda de Usuario class Admin(U...
5cdf0c515201e0c67eb104cdec8c7cd8de528c73
dhita-irma/miniprojects
/datastructure/stack.py
1,054
4.25
4
class Stack: def __init__(self): self.stack = list() def push(self, item): """Append an item to the end of the stack""" self.stack.append(item) def pop(self): """Remove the last item of the stack and return the value""" if len(self.stack) > 0: return s...
0c2af57bb9ba5f4b093d95fd4418a761963d9458
sugky7302/Code-for-Learning-Python
/20181117_deep_learning_practice.py
3,292
3.59375
4
import numpy as np class NeuralNetwork: def __init__(self, X, Y, layerDim, studyingIteration = 2000, learningRate): """ Implements a L-layer neural network: [LINEAR->RELU]*(L-1)->LINEAR->SIGMOID. Arguments: X -- data, numpy array of shape (number of examples, num_px * num_px * 3) Y -- true...
1b96828a787dcbf1f3ebdb201563a3f623db7887
Phil-U-U/leetcode-practice
/max-points-on-line/max-points-on-line.py
2,570
3.65625
4
''' Given n points on a 2D plane, find the maximum number of points that lie on the same straight line. Solution: To find the maximum number of points lying on the same line, First, form all possible lines: n choose 2 lines in total. So at most an embeded for loops is needed for an enumeration of n(n-1)/2. During the ...
c0e3672d4ee6a882b2d123c19931d912c481d354
gaanasc/python
/Técnicas de Programação/exemplo_while3.py
446
4.25
4
print ("::: MENU :::") print ("1 - Logar no sistema") print ("2 - Sair do sistema") print ("3 - Recuperar senha") opcao = int(input("Digite uma das opções do menu: ")) while (opcao < 1 or opcao > 3): print ("Opção inválida, digite uma das opções do menu!") print ("1 - Logar no sistema") print ("...
8fec396164d5ad079fec4e23cd38cb1c60075622
diamondstone/project-euler
/python/pe125.py
1,737
3.53125
4
from time import time # Method 1: iterate through palindromes, check whether palindrome is a sum of squares. def palindrome(n,b): if b: return int(str(n)+reverse(str(n))) else: return int(str(n)+reverse(str(n)[0:-1])) def palindromes(n): for d in xrange(1,n+1): for k in xrange(10**((d-1)/2),10**(...
3d03754f5e9bf55b93bf2fb7a65310f3ba34fbff
ABHI2598/python-for-armstrong-number-and-prime-number
/armstrong&primeno.py
498
3.625
4
s= int(input("Enter start: ")) e = int(input("Enter end: ")) a =0; p = 0; for num in range(s, e + 1): order = len(str(num)) sum = 0 temp = num while temp > 0: digit = temp % 10 sum += digit ** order temp //= 10 if sum == num: a += 1 if num > 1: for y in ra...
d1924514862097169d99dedc0b933e72e448ca66
OvernightGruel/leetcode-for-python3
/111、二叉树最小深度.py
486
3.734375
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def minDepth(self, root): if not root: return 0 depth_left = self.minDepth(root.left) depth_right = s...
eb1da2a4d6d9afdef681607b88a2ff5fea07d88e
KeetonMartin/HomemadeProgrammingIntro
/Lesson7.py
1,890
4.3125
4
#Lesson 7 topics #Problem 1 """ Write a function taking in a string like "WOW this is REALLY amazing" and returning "Wow this is really amazing". String should be capitalized and properly spaced. Hint: Try using functions like "APPLE".lower() or ourList = "Multiple words in a string".split() ["Multiple", "words", "i...
01020a338f0bb37bde18544baaddeda181fe45a8
codershenghai/PyLeetcode
/hard/0004.median-of-two-sorted-arrays.py
653
3.5
4
class Solution(object): def findMedianSortedArrays(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ # 暴力法(先排序,然后找中位数) unite = nums1 + nums2 sorted_unite = sorted(unite) n = len(sorted_unite) if n ...
013d81b06dbdfe0fbe42033336bd9f78b082a656
luluchicken/this-again-
/Luna_DatingApp.py
758
4.03125
4
#Luna Cuervo #Program2 print("Hi there, let's see if you like the same things as this " "person and we will determine if you are match, just answer" " the questions and we will do the rest") name=input("What is your name ") animal=input("\n \n What is your favorite animal? ") if ( "Cat" in ...
fd6b3b8f3db6e039d303fbc3fd485178bc2b843f
jslim7812/jslim7812
/st01.Python기초/py08반복문/py08_13_3단구구단.py
67
3.71875
4
i=1 while i<10: str="3*%s=%s" %(i,3*i) print(str) i=i+1
cfc4bf0e8f02bc920b47fe14081e4481c9ed24be
rosa-yuri/Python
/day 0904_2.py
1,646
3.5
4
import numpy as np #행렬연산을 빠르게 실행해주는 패키지 a=np.array([1,3,5]) # print(a) #[1 3 5] print(type(a)) #<class 'numpy.ndarray'> b=np.arange(7) print(b) #[0 1 2 3 4 5 6] b+=1 #[1 1 1 1 1 1 1] print(b) #broad casting ..[1 2 3 4 5 6 7] print(b<4) #[ True True True False False False False] print(b[b<4...
d2937b35f037139e460065928524c43844c38610
jee-van/code-backup
/rangoli.py
372
3.78125
4
from string import ascii_lowercase def print_rangoli(size): latters = ascii_lowercase result = [] for n in range(size): strings = '-'.join(latters[n: size]) result.append((strings[::-1] + strings[1:]).center((4 * size) - 3, '-')) print('\n'.join(result[::-1]+result)) if __name__ == '...
9f75213e84415a14aa081b023bcca07c7d4a74f3
yutaka-watanobe/problem-solving
/AOJ/0130/0130.py
283
3.8125
4
n = int(input()) for _ in range(n): s = input() # 巡回記録 form = s[0] # 列車の編成 for i in range(3, len(s), 3): if s[i] in form: continue if s[i - 1] == '>': form += s[i] else: form = s[i] + form print(form)
98deffcaf5f8f4a5160c817d1287ae689e353684
DaharGon/gb_python
/lesson03/hw03_normal.py
1,875
4.03125
4
# Задание-1: # Напишите функцию возвращающую ряд Фибоначчи с n-элемента до m-элемент # Первыми элементами ряда считать цифры 1 1 def fibonacci(n, m): farray = [1,1] for i in range(m-2): farray.append(farray[-1]+farray[-2]) return farray[n-1:m] print(fibonacci(5, 9)) # Задача-2: # Напишите фу...
ad474c2c4e1f37fb48a03950bd7af645572aea25
sijapu17/Advent-of-Code
/2020/2020-24.py
3,567
3.578125
4
#Advent of Code 2020 Day 24 f = open('C:/Users/Simon/OneDrive/Home Stuff/Python/Advent of Code/2020/2020-24.txt') state = f.read() input=state.splitlines() class Hex(): #Hex coordinate pair with e and ne coords def __init__(self,c): self.str2tup={'ne':(0,1),'e':(1,0),'se':(1,-1),'sw':(0,-1),'w':(-1,0),'n...
5f2f4f1261b0352c2111fb77b45db3b1d6ab64b1
denkho/CourseraPython
/week5/21_biggest_element_position.py
232
3.65625
4
numbers = list(map(int, input().split())) max_number = numbers[0] position = 0 for pos in range(len(numbers)): if numbers[pos] > max_number: max_number = numbers[pos] position = pos print(max_number, position)
3ecff4871c7b138ae5c149242223a58fad9f429f
uozuAho/pylox
/pylox/parser/expressions.py
1,892
3.90625
4
from ..token import Token class Expression: """ abstract expression """ def accept(self, visitor): """ Uses visitor pattern to extend expression functionality """ pass class Binary(Expression): def __init__(self, left: Expression, operator: Token, right: Expression): self.left = l...
9d5c3084bbb583fa60fd161c29929a10c868dd11
SalihTpc/Python
/Password_Reminder.py
230
4.25
4
name = "Joseph" password = "W@12" input_name = input("Whats your name?:") if input_name == name: print(f"Hello, {input_name}! The password is : {password}") else: print(f"Hello, {input_name}! See you later.")
9fbfb960a58491ca661edf3600b4e7ac4ee6c54f
carello/wpe_2018
/meeting-rooms/sol47v1.py
2,026
3.671875
4
#!/usr/bin/env python3 import arrow from pprint import pprint class MeetingRoomTakenException(Exception): pass class Meeting(object): def __init__(self, starts_at_str, meeting_length): self.starts_at = arrow.get(starts_at_str) self.ends_at = self.starts_at.shift(hours=meeting_length) d...
b23adc181941725f74b84554a8dd011c78bf62a2
muthuku/polyname
/polyname/monomer.py
4,715
3.734375
4
#!/usr/bin/env python # coding: utf-8 # In[32]: import pandas as pd import numpy as np import itertools import pubchempy as pcp import cirpy def lowercase(anylist): '''a function that takes the list of polymers and makes it lowercase input: anylist: description: a list of uppercase polym...
68ea40738d6a396af2165679b4590426feaa5826
jamesshapiro/cs41-python
/cs41/lab4/filter.py
676
4.28125
4
#!/usr/bin/env python3 -tt """ Filter Recall from class that filter(pred, iterable) keeps only those elements from an iterable that satisfy a predicate function. Write statements using filter that convert the following sequences from the left column to the right column: """ #['12', '-2', '0'] => ['12', '0'] list...
c548403522c6f33d95d81b4b3bf9f99c97ea2a24
lborke/Keras
/artefakte/01_basic_classification_comments.py
8,896
4.34375
4
# Train your first neural network: basic classification # # This guide trains a neural network model to classify images of clothing, # like sneakers and shirts. It's okay if you don't understand all the details, # this is a fast-paced overview of a complete TensorFlow program with the details # explained as we go. #...
a2ecd9aa4c92e7c689dcae84327b78d7bdee87aa
dalalsunil1986/Algoexpert-4
/Easy/12-PalindromeCheck.py
1,315
3.765625
4
# Solution 1 - Iterative # def PalindromeCheck(string): # ''' # Time: O(n^2) # Space: O(n) # ''' # new = '' # for i in reversed(range(len(string))): # new += string[i] # return new == string # Solution 2 - Iterative # def PalindromeCheck(string): # ''' # Time: O(n) # Sp...
b037d2e203a4ff4210f58f51fbc4673b0c32c7fc
anujpanchal57/Udemy-Challenges
/Lect-30-challenge.py
417
4.3125
4
# Stores Name and Age of the person name = input("Please enter your name : ") age = int(input("What is your age : ")) # Checks whether he/she is below 18 or above 31 if 18 <= age < 31: print("Welcome to the Holiday Mr. {} !!!".format(name)) # If he/she is below 18 years of age or above 31 years of age # Then he/s...
75b4800b8ab88c68704a1b821fe9eb6cd3a35c3d
AlwaysOnline233/cookbook
/leetcode/21.py
691
4.09375
4
# 合并两个有序链表 ''' 将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。  示例: 输入:1->2->4, 1->3->4 输出:1->1->2->3->4->4 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/merge-two-sorted-lists ''' class Solution: # 递归 def mergeTwoLists(self, l1, l2): if l1 is None: return l2 elif l2 is None:...
413255905c208abb2786583a21184a72dd50ec60
acganesh/euler
/41_PandigitalPrime.py
729
4.0625
4
from math import sqrt def is_pandigital(n): my_str = sorted(str(n)) my_str = ''.join(my_str) length = len(my_str) ctr = 1 pandigital_str = '' while ctr <= length: pandigital_str += str(ctr) ctr += 1 if my_str == pandigital_str: return True else: return False def isPrime(n): bound = sqrt(n) ...
c8aeff7934e890c026cbf3357e4d9f3c4d98a989
rotsix/algo
/ProjectEuler/Problem017.py
1,977
3.921875
4
#!/usr/bin/env python # If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. # If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? # NOTE: Do not count spaces or hyphen...
34c777fd8d13efff8be522a0636a1a8ccdc92d9c
hugotallys/NumericalAnalysis
/Polynomial_Interpolation/linsys.py
602
3.546875
4
import numpy from matplotlib import pyplot def main(): x = numpy.array([ [1., -1., 1, -1.], [1, .5, .5**2, .5**3], [1., 1., 1., 1.], [1, 1.25, 1.25**2, 1.25**3] ]) y = numpy.array([1.25, 0.5, 1.25, 1.8125]) inv_x = numpy.linalg.inv(x) a = inv_x.dot(y) print...
57ce4de926a42c71fb03ed332e556d7482f35e54
shrutisaxena0617/Data_Structures_and_Algorithms
/Arrays/leader_array.py
735
4.125
4
# Find leaders in an array # An element is leader if it is greater than all the elements to its right side def find_leader(arr): leader = [] for i in range(len(arr)): for j in range(i+1,len(arr)): if(arr[i]<=arr[j]): flag = 0 break else: ...
076afd0fdbb2bd07e3e5ff49971450285ba63a4c
aliakseik1993/skillbox_python_basic
/module1_13/module3_hw/task_1.py
1,058
4.375
4
print('Задача 1. Язык математики') # Маше для защиты курсовой работы нужно написать программу для расчёта экономической модели по формуле. # Как записать саму формулу в программу, она не знает, у неё есть только начальные значения. # Поэтому Маша решила просто заплатить Егору, чтобы тот написал её быстрее. # # Дана пр...
fe5303be2d7821136dd97a8db7be1c79bfea2859
M0673N/Programming-Fundamentals-with-Python
/exam_preparation/final_exam/02_mock_exam/03_problem_solution.py
1,257
3.65625
4
n = int(input()) plants = {} for i in range(n): info = input().split("<->") plant = info[0] rarity = int(info[1]) plants[plant] = [rarity, []] command = input() while not command == "Exhibition": command = command.split() if command[0] == "Rate:": plant = command[1] if plant not...
f57c87c984423e8108894ed8381d9c2c16dec953
mihailter/PythonPY200_desktop
/Атрибуты и методы/Повторение/task6_Glass__dict__/main.py
482
3.8125
4
class Glass: def __init__(self, capacity_volume: [int, float], occupied_volume: [int, float]): self.capacity_volume = capacity_volume # объем стакана self.occupied_volume = occupied_volume # объем жидкости в стакане def add_water(self, water): self.occupied_volume += water ret...
b5182ce8cf575b4306c68fb20fd1b1f485058098
Naawww/ffmpeg_gnu
/pipe_practice.py
903
4
4
import os r, w = os.pipe() # use os.fork() to create a child process - this actually makes a whole new process # running this program, in the child process it has pid = 0, and in the parent # process it has pid > 0 (equal to the child process id). pid = os.fork() if pid > 0: # so, if pid > 0 , we are in the PARE...
5836152efb63325081d9722bc3d3973ce9b58e25
sashakrasnov/datacamp
/24-data-types-for-data-science/4-handling-dates-and-times/04-creating-datetime-objects...now.py
1,093
4.625
5
''' Creating DateTime Objects... Now Often when working with datetime objects, you'll want to work on windows or ranges that start from the current date and time. You can do this using the datetime now functions. There is a .now() method on the datetime object in the datetime module and a .utcnow() method. The .now() ...
7a4a06956184baab5572dfef8cb25c72ee3248aa
YufeiHu/Online-Accessment
/Amazon/virtual-interview/distance_between_nodes_in_BST.py
1,611
3.765625
4
class Node(object): def __init__(self, x): self.val = x self.left = None self.right = None def distance_between_nodes_in_BST(root, val1, val2): # find LCA level_LCA = 0 val_min = min(val1, val2) val_max = max(val1, val2) p_LCA = root while p_LCA: ...
f7a4e290429a76ad87c0fcfc70da8867d9819b1b
kviiim/AdventOfCode2020
/day2/day2-2.py
569
3.65625
4
totalValidPasswords = 0 with open('advent2020/day2/day2input.txt', 'r') as file: for testPassword in file.readlines(): rangeAndLetter = testPassword.split(':')[0] letter = rangeAndLetter[-1] num1 = int(rangeAndLetter.split('-')[0]) num2 = int(rangeAndLetter.split('-')[1].strip(letter...
dd998ffd93747cf94c8cb773bdcb4d2e3fbab3f8
asheeshcric/leetcode
/subtree-of-another-tree/subtree-of-another-tree.py
755
3.828125
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def path_string(self, node, string_path): if node is None: return string_path + '*' ...
1559d5704f14feaab7b232412cefa1fbc4567eb8
xingyunsishen/pixiu_runoob
/42-数组翻转指定个数的元素.py
1,442
3.6875
4
#-*- coding:utf-8 -*- #实例1 def leftRotate(arr, d, n): for i in range(d): leftRotatebyOne(arr, n) def leftRotatebyOne(arr, n): temp = arr[0] for i in range(n - 1): arr[i] = arr[i + 1] arr[n - 1] = temp def printArray(arr, size): for i in range(size): print("%d" % arr[i], end...
e5ee3d0a8c7f2a8281819561c80a607ff216b6c8
MuhammadEhtisham60/dev-code2
/operator.py
903
4.34375
4
#arithmatic """ x=2 y=4 #a=x+y #a=x*y #a=y-x #a=x/y #a=x%y a=x**y print(a) """ """ x=144 y=3 print(x//y) """ #Assignment operator """ x=5 y=x print(y) """ #x=5 #x +=3 #x=5 #x -=3 #x=5 #x *=3 #x=5 #x /=3 #x=5 #x %=3 #x=5 #x //=3 #x=5 #x **=3 #x=5 #x &=3 #x=6 #x=x|2 #x=3 #x=x^2 #print(x) #Python Comparison O...
2d2fdd19bd84fa823f0c368750565d2e22584a44
Ankita909/fullstackDevelopment
/Python/reversed-linked-list.py
827
4.09375
4
# TO reverse a linked list class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: newhead= ListNode() def linkofthelink(orig,rev): stack=[] ...
95a752bbe827c780accdbeff4b42faa2d51ec94c
clarkjoypesco/pythonpracticestringfind
/teststringfind.py
2,038
4.8125
5
# This segment is just a chance for you to play around with # finding strings within strings. Read through the code and # press Test Run to see what it does. Is there anything # interesting or unexpected? print "Example 1: Finding substrings in a string" print "test".find("te") print "test".find("st") print "test"[...
3fa36f604ed7adfb265a2a9be0ac01680d5d1524
cavmp/200DaysofCode
/Day13-PostIt.py
854
3.65625
4
import tkinter as tk HEIGHT = 500 WIDTH = 700 def format_response(): final_str = entry.get() return final_str def print_text(text): label['text'] = format_response() root = tk.Tk() canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH, bg='#0066ff') root.title('Post It') canvas.pack() frame = tk.Frame(r...
4a2411f01cb3a59bc54dfe02252b7dc054131fae
gabbycampos/pythonSyntax
/words.py
804
4.4375
4
def print_upper_words(string): """ Will print words in uppercase """ for char in string: print(char.upper()) print(print_upper_words(['I', 'am', 'a', 'list'])) def only_letter_e(words): """ Will only print words that start with 'e' """ for word in words: if word.startswith('e') or word.startswith('E')...
27ceb0bac63351193a90c1ede823de2210c2b6a1
murali-kotakonda/pyDjango
/myProject/login/DB/ex8.py
497
3.84375
4
import sqlite3 # connecting to the database connection = sqlite3.connect("myTable.db") crsr = connection.cursor() print("conn success") # SQL command to insert the data in the table sql_command = """UPDATE PERSON SET NAME = ? WHERE Id=?""" crsr.execute(sql_command,("suchi",26)) # To save the changes in the files....
fb41ffbb17b1ad75a0ac2b62e9d2db0153945174
nascarsayan/lintcode
/1105.py
913
3.875
4
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param root: the given tree @return: the binary tree in an m*n 2D string array """ def printTree(self, root): # Write your code here def getMaxdep...
afe9da183e68805c919a0a3de8dc0925acb04384
EricQXu/MultiPark
/game.py
12,204
4
4
""" https://www.youtube.com/watch?v=-8n91btt5d8 https://www.youtube.com/watch?v=NjvIooRpuH4 https://www.pygame.org/docs/ """ import pygame #imports pygame module into project (1) import random Alpha = 1 Beta = 1 Gamma = 10 class Car: def __init__(self, x, y, sprite_path): self.x = x self.y = y ...
38aabed0bb71683569e7eb9a4b0b5a53255226f4
waxmittmann/workflowManagers
/luigi/tasks/step0.py
376
3.59375
4
from sys import argv def main(): if len(argv) != 3: raise Exception("Must have 3 args") else: out_file = open(argv[1], "w") out_file.write("data1") out_file.close() out_file = open(argv[2], "w") out_file.write("data2") out_file.c...
29a373a47fd22af18d33e7334eba859c3f59fa42
thonny/thonny
/thonny/plugins/circuitpython/api_stubs/sdcardio/__init__.pyi
2,859
3.5625
4
"""Interface to an SD card via the SPI bus""" from __future__ import annotations import busio import microcontroller from circuitpython_typing import ReadableBuffer, WriteableBuffer class SDCard: """SD Card Block Interface Controls an SD card over SPI. This built-in module has higher read performance t...
87b5a97b5d0cf21dc28c53ca14544f6d3250178b
WillianVieira89/Python_Geek_University
/Script_Python/Estudos/Exercicios de fixação/Exercicios_Secao4/imprime_soma.py
215
3.875
4
n1 = int(input('digite um numero inteiro: ')) n2 = int(input('digite um numero inteiro: ')) n3 = int(input('digite um numero inteiro: ')) soma = n1 + n2 + n3 print(f'A soma de {n1} + {n2} + {n3} é igual a {soma}')
33f7ac69a361e0a4ed7044953be0e0aa5b127751
Asobu77/python_basic
/Section_5/52.py
293
3.5625
4
# 引数にタプルに入れる def say_something(*args): for arg in args: print(arg) # 引数に単語を指定すると*argsに含まれる say_something('Mike', 'Bob', 'Cathy') # 引数に参照渡しすることもできる tpl = ('elly', 'poal') say_something('Edy', *tpl)
3f5ea85e7d53885288707aa3d89001d13ff67f9f
mgbo/My_Exercise
/2017/Turtule/lesson_7_Циклы___for/zadache_9.py
632
3.515625
4
# -*- coding: utf-8 -*- import turtle import time def write(data): t.write(data, font = ("Aria",14,"normal")) def sqr(col2): t.color('black',col2) t.begin_fill() for _ in range(4): t.fd(50) t.lt(90) t.end_fill() def polosa(n,col1,col2): x=50 for _ in range(n): #p =t.pos()...
dac09610a5c3ade652f183451db823916580d86b
bclark2/Ordered-Linear-Search
/orderedLinearSearch.py
517
3.765625
4
# Ordered linear search my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21] def search(ordered_list, term): for index, item in enumerate(ordered_list): if term == item: return ( f'Index of my number = {index}\n' f'Nu...
0c67881140b5cdf1d77d2877440341c950061385
mirmisbahali/python_course
/3.py
120
3.65625
4
num1 = "5" num2 = '2' num3 = 5 num4 = 5.0 # print(type(num1)) # print(type(num3)) # print(num1 + num2) print(type(num4))
5b54277c1747bcd1689df6ebee460ce2dd8de253
Spotex/Tasks
/exc_5.py
190
4
4
a=input('Enter 1st number') b=input('Enter 2nd number') if a>b: print(str(a)+' is bigger than '+str(b)) elif b>a: print(str(b)+' is bigger than '+str(a)) else: print('ERROR')
adff51915ecba0866f7d6f9eb38208dc7bdd7f9b
SMHari/Python-problems
/Module 4/6_filter.py
213
3.703125
4
import numpy as np if __name__ == '__main__': arr = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]] arr_np = np.array(arr) print(arr_np) print("elements greater than 5 are : ", arr_np[arr_np > 5])
ff739638df91cb7c5c78c50b528a31a0ff951367
pauljxtan/souffle
/souffle/math/stochastic.py
7,398
3.515625
4
""" Stochastic processes. """ # TODO: # Generalize lattice_dims to have non-zero minimum # Example script with real-time plotting import random class RandomWalk(object): """ The base random walk class. """ def __init__(self, dims, pos0, lattice_dims, kwargs): self.pos = [] if...
4f5a10b94fb9c320043734374d4786471da629e3
everaldobass/introducao-python
/digital-innovation/brigadeiro.py
799
3.578125
4
""" Você está em uma festa de aniversário e está tendo confusão para distribuir de modo justo a quantidade de brigadeiro entre os participantes. Todos, por alguma coincidência, entendem de Python, então você planeja o seguinte código: brigadeiros = 150 pessoas = 16 Por você ter feito a conta e evitado aumento da c...
f1e6482a1025a7f92e070e3b4fd426b8246063dd
mmesas3699/LQN
/ejercicio_a.py
516
3.6875
4
def es_par(numero): if numero % 2 == 0: return 'buzz' else: return False def es_multiplo(numero): if numero % 5 == 0: return 'bazz' else: return False if __name__ == '__main__': for n in range(0, 101): par = es_par(n) multiplo = es_multiplo(n) ...
8b2956d0b0b9e15b445258e270332d98c163708b
brewswain/PCC
/Part I - Basics/Chapter 06 - User Input and While Loops/Notes/09_list_specific_values_removal.py
605
4.5
4
""" Previously, we used the remove() function to remove a specific value from a list. The remove() function worked because the value we were interested in only appeared once in the list. But what if you want to remove all instances of a value from a list? In the below example, we have a list of pets with the value 'ca...
43e358a174771ac2aa643dd9bb427ae89f3e6d9e
tnakaicode/jburkardt-python
/line/line_distance.py
6,655
3.515625
4
#! /usr/bin/env python3 # def line_distance_compare ( n ): #*****************************************************************************80 # ## line_distance_compare compares the observed and theoretical PDF's. # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 18 May 20...
50755ba88adcbf39a58dbcd659233c4a6a5d75e6
sahilg50/ML_ALGORITHMS
/reluLossFunction.py
534
4.28125
4
# Relu stands for rectified linear unit import matplotlib.pyplot as plt # Defining the relu loss function def relu(x): if x > 0: return x else: return 0 # Plotting the relu function on the graph plt.style.use('ggplot') plt.figure(figsize=(10, 5)) # define a series of inputs input_series =...
2230b2b75cf6e76cea24fc62b53ef5b021f0ae4b
ifpi-corrente/Algoritmos-2019.2
/03-14.py
446
3.9375
4
# 3. 14. Escreva um programa que pergunte a quantidade de km percorridos por um carro alugado pelo usuário, assim como a quantidade de dias pelos quais o carro foi alugado. Calcule o preço a pagar, sabendo que o caro custa R$ 60 por dia e R$ 0,15 por km rodado km = float(input("informe a quilometragem percorrida: ")) d...
b8f358e1e05dbfc26897ad914f06205582aace8e
jinwooklim/coding-test
/algorithm/graph_search/dfs_matrix.py
1,352
4.03125
4
# Created by Jinwook Lim (Aiden Lim) at 7:01 PM 2021/06/22 __author__ = "Jinwook Lim (Aiden Lim)" def recursive_dfs(i, discoverd=[]): discoverd.append(i) for j, value in enumerate(graph[i]): if value == 1: if not j in discoverd: print(i + 1, '->', j + 1) re...
c2b012839d89b42832d9e89b843d2ee9b095bc57
rajeshsvv/Lenovo_Back
/1 PYTHON/7 PROGRAMMING KNOWLEDGE/26_Multi_Constructor.py
825
4.34375
4
class Hello: def __init__(self): print("The __init__") hello=Hello() # Multiple Constructor Concept ''' class Bye: def __init__(self): # this init method is overwritten pass def __init__(self,name): # this init method t...
35dd70e6d74981c638e90183de96dce863b91934
IPVL/Ahsan-PythonWorks
/chapter2/listSorting.py
290
4.40625
4
#!/usr/bin/env python lst = [3,4,1,2] #using sort method the list itself becomes sorted lst.sort() print lst # using sorted function it returns a sorted list other than the original y = sorted([2,1,4,3]) print y #to sort decendingly lst = [3,4,1,2] lst.sort(reverse= True) print lst
fc6ea4a0c82eeeab4d9c3b17633dbe904d728108
Gustavokmp/URI
/1015.py
257
3.546875
4
lista1 = input() lista2 = input() parte1 = lista1.split() parte2 = lista2.split() x1 = (float(parte1[0])) y1 = (float(parte1[1])) x2 = (float(parte2[0])) y2 = (float(parte2[1])) distancia = ((((x2 - x1)**2) + ((y2 - y1)**2))**0.5) print("%.4f" % distancia)
b4761d8cd2ec0041c2de9c104e9cd448bf2c0201
BJV-git/amazon_6
/amazon_6/game_of_life.py
1,235
4.03125
4
# logic: so while changing the state of the current element we should do in such a way that it can be traced while changing for upcoming def gameOfLife( board): rows, cols = len(board), len(board[0]) for i in range(rows): for j in range(cols): # print("row and column", i, j) n...
346d2e0380883f4497d47b85a2895923f9d81db2
Galarzaa90/AdventOfCode2020
/04-passport-processing/main.py
2,375
3.609375
4
import re def process_input(): with open("input.txt") as f: input = f.read() return input def part_one(): values = process_input() entries = values.split("\n\n") required_fields = {"byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"} valid_count = 0 for entry in entries: data...
3820aa8a1c91c7caf600830e57a9cdafe90a128a
unsortedtosorted/elgoog
/hard/mergeKLists.py
795
3.796875
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def mergeKLists(self, lists): """ :type lists: List[ListNode] :rtype: ListNode """ l= [] ...
b44d9127613b81c9dd263f1aa437ffa39b2bc070
janus-magnus/PP_S1_B1
/Les2/FA2.py
1,338
3.96875
4
stations = ['Schagen', 'Heerhugowaard', 'Alkmaar', 'Castricum', 'Zaandam', 'Amsterdam Sloterdijk', 'Amsterdam Centraal', 'Amsterdam Amstel', 'Utrecht Centraal', "s-Hertogenbosch", 'Eindhoven', 'Weert', 'Roermond', 'Sittard', 'Maastricht'] while True: beginStation = input('Wat is je beginst...
e6181056de7b8034a2598f03a0e72f18f0743add
izabela9525/BIM-BOOM
/tuple_advanced.py
363
4.0625
4
tuple1 = (45,'Testing', "www.thetestingworld.com", 23.4, "Yes", "No") tuple2 = (100, 200) # Count number of times a value displayed in Tuple # 1print(tuple1.count(45)) # Find index of any value in tuple # print(tuple1.index(23.4)) tuple3 = tuple1 + tuple2 print(tuple3) for i in tuple1: print(i) i = len(tuple1...
24b6822cbc82f65e175bd79fd93bf778d0bc249c
mpigelati/Python_adb
/56.py
572
3.984375
4
#56. WAP to do all stack operations using lists l=[] def push(d): l.append(d) def pop(): if len(l): r=l[len(l)-1] l.pop() return r print("stack is empty") def display(): for i in l: print(i) while(True): print("1.push 2.pop 3.display 4.peak 5.quit") ch=input("ent...
3b9f4dd738bc0e689487733f71e2b2713e65ff73
Yamigichi/Data_Visualization_Practice-
/pieChart.py
4,751
3.65625
4
#Downloading and Prepping Data import numpy as np # useful for many scientific computing in Python import pandas as pd # primary data structure library df_can = pd.read_excel('https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-DV0101EN-SkillsNetwork/Data%20Files/Canada.xlsx',...
77bb6e8f2ecadd4747c04ccf8bb5ddcfd680b6c7
nneuro/lesson2_new
/task3_for.py
952
3.828125
4
''' # Создать список из словарей с оценками учеников разных классов школы вида [{'school_class': '4a', 'scores': [3,4,4,5,2]}, ...] # Посчитать и вывести средний балл по всей школе. # Посчитать и вывести средний балл по каждому классу. ''' score_list = [ {'school_class': '4a', 'scores': [3,4,4,5,2]}, {'school...
a661b2fd5ac4ae065dfd6b2f6617abb941fc4f49
rinoguchi/python_sandbox
/src/generator/generator_return.py
627
3.8125
4
import time from typing import Generator def main(): gen: Generator[int, None, str] = generate() i: int = 0 while True: try: print(f'before next. i: {i}') i: int = next(gen) print(f'after next. i: {i}') time.sleep(1) except StopIteration as e...
0bc85e52dd7039b44ed806764920ca8d62083f77
Minitour/BigDataHW4
/modules/twitter/users_ids.py
2,144
3.609375
4
import json import requests import requests_oauthlib import csv CONSUMER_KEY = 'owJ9m2q48GGYrMubsOSEyZbap' CONSUMER_SECRET = 'LQNlKSk7azipU1lIA2znEkQSwsGkTswhRheP0S2RbHLioW8HJt' ACCESS_TOKEN = '1053037342867554304-4QmY7LgUp0N5f9Jof1suuKf3LmE09h' ACCESS_SECRET = '14YaQqTDjwmzUfALLhtuzJw1ibLehe6NbtlbdtAJiXOea' my_auth ...
b5eeb2d9a5ab7a7848950b85421f0c8e17f156e6
LucianErick/p1-2018.2
/Questões/encontra_menores/encontra_menores.py
570
4.03125
4
# coding: utf-8 # Universidade Federal de Campina Grande # Ciência da Computação # Programação I | 2018.2 # Aluno: Luciano Erick Sousa Figueiredo Filho # Matrícula: 118110400 # Problema: Encontra Menores def encontra_menores(numero, lista): lista_menores = [] for valor in lista: if valor < numero: ...
38d403123e1293414b54b26bdbf60d750790dd26
letspython3x/code_examples
/code_snippets/runcommand.py
1,878
3.671875
4
# runcommand.py Runs an external command in Python and returns exit code, stdout and stderr contents. # Handy function that executes an external command in the shell # and returns 3 values: exit code of the command, its standard output # and its error output. # If you run the script directly, an example is provided: #...
c8028c9c218900347774e05e118d3f64c4b50e32
aniagut/ASD-2020
/7a.Stos i kolejka/queue.py
875
3.640625
4
#kolejka FIFO first in first out #dokladamy na koniec kolejki #sciagamy z poczatku #enqueue=wstaw, dequeue-pobierz i wyjmij, is_empty #IMPLEMENTACJA TABLICOWA class Queue: def __init__(self,n): self.S=[None]*n self.n=n self.elements=0 self.head=0 def enqueue(self,x...
5fd47cdfaca61fdd67e38b18abced38b37023b5e
JoshVarty/AlgorithmDesignManual
/CrackingTheCode/Chapter16/Ch16_Moderate_25.py
1,445
3.765625
4
# LRU Cache: Design and build a "least recently used" cache, which evicts the least recetnyl used item. The cache should map from keys to # values (allowing you to insert and retrieve a value associated with a particular key) and be initialized with a max size. When it is full # it should evict the least recently used...
a96507a1b801cf0eeecff553deff60ed73fbe4e3
jfbo/myHomework-Project_Python_pirple
/homework4.py
1,620
4.25
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: ''' Homework # 4 : Lists ''' #Details: #Create a global variable called myUniqueList. It should be an empty list to start. #Next, create a function that allows you to add things to that list. Anything that's passed to this function should get added to myUniqueList, #un...
6638ce89efcd00a5d893d8170b7220b064ebaec1
YeonggilGo/python_practice
/leetcode/Spiral-Matrix2.py
1,639
3.65625
4
# https://leetcode.com/problems/spiral-matrix-ii/ from typing import List class Spiral: n: int x_dir: int y_dir: int x_pos: int y_pos: int result: List[List[int]] def __init__(self, n=0): self.x_pos, self.y_pos = 0, 0 self.x_dir, self.y_dir = 1, 0 self.n = n ...
49a2fb6d1bc6dd0b82376bef93564f5b26cff708
user-0123456789/DodgeGameGeneticAlgorithim
/game.py
5,280
3.5
4
import sys import pygame from pygame.locals import * import random #if __name__ == "__main__": if True == True: pygame.init() fps = 60 fpsClock = pygame.time.Clock() width, height = 600, 700 gameDisplay = pygame.display.set_mode((width, height)) class Game: ...
28b417e17a6abe611ebe5596ddf206f9099a2574
ryuo07/C4TB
/session10/exercises/init_many_quiz.py
1,035
3.875
4
count = 0 question = "ranking of the vn team in PUBG Nations Cup Seoul 2019:" print(question) answers = { "a)" : "first place", "b)" : "second place", "c)" : "third place", "d)" : "fouth place", } for k,v in answers.items(): print(k,v) a = input("enter your answer:") if a == "a" or...
773645730cd5bb9f37e808f37b9d7eca5a736eec
vshen009/my-python
/c2f.py
179
3.96875
4
#摄氏温度转发成华氏温度程序 #让使用者输入 C 然后打印出 F c = input('请输入摄氏温度:') c = float(c) f = c * 9 / 5 + 32 print(f, '这是华氏温度')
e1017d9c6cbab30425de1998944e9fcbe14995a7
danielwangai/ds-algorithms
/ds/linked_lists/more_operations.py
3,515
4.1875
4
from basic_operations import Node, LinkedList class LinkedList2(LinkedList): def __init__(self): self.head = None self.tail = None def remove_duplicates_sorted_iterative(self): """ removes all duplicates from a sorted linked list complexity: O(n) """ t...