blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
06061280a8333db9d6b3aa747fd98ac8456c02e7 | poojithayadavalli/codekata | /word after article.py | 257 | 3.5625 | 4 | h=['the','a','an','A','An','The']
x=input().split()
y=[]
for i in range(len(x)):
if x[i] in h:
if (i+1)<len(x) and x[i]=='The':
y.append(x[i+1].capitalize())
elif (i+1)<len(x):
y.append(x[i+1])
print(' '.join(y))
|
3bc448474640ea1ea33ec5fc2c66ae813786389f | AmosFilho/-estcmp060- | /Árvore Fractal.py | 742 | 3.796875 | 4 | from turtle import *
speed('fastest')
rt(-90)
angle = 30
def fractal_tree(size, level):
if level > 0:
colormode(255)
# Splitting the rgb range for green into equal intervals for
# each level setting the colour according to the current level
pencolor(0, 255 // level, ... |
f1c0c46efba1ac1eeab2b8a6243a085ff5bb49e7 | giovannirosa/HackerRank | /TrocoSimples/entryTime.py | 1,861 | 3.921875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'entryTime' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. STRING s
# 2. STRING keypad
#
def findIndexes(val, matrix):
return [(index, row.index(val))
... |
f3e601f60dd73770aa60c91a4758f08f5fa0f9c8 | Vijay-161/pythonProject1 | /vijay.py | 1,074 | 3.5 | 4 | from tkinter import *
root = Tk()
root.title("System")
root.iconbitmap("vj.ico")
root.maxsize(width=500, height=300)
root.minsize(width=300,height=200)
# root.geometry("500x300")
redbutton = Button(root, text="LEFT",fg="green",bg="yellow").pack(side=LEFT)
# redbutton.pack(side=LEFT)
greenbutton = Button(root,text = "R... |
0514fccd19f194a6169bc28e21771da55aaeab48 | Macmilonsaled/Primo | /Lesson1.py | 265 | 3.859375 | 4 | def even_or_odd(num):
if num % 4 == 0:
print("Dyelyatso na 4")
elif num % 2 == 0:
print("Chetnoe")
else:
print("Nechotnoye")
def main():
even_or_odd(int(input("Vvedite chislo ")))
if __name__ == "__main__":
main()
|
61668fd99d33e7a30792f327b06742b0758b112e | danielpza/codeforces-solutions | /71A - Way Too Long Words.py | 214 | 3.625 | 4 | #!/usr/bin/env python3
def abbr(word):
if len(word) <= 10:
return word
return word[0] + str(len(word) - 2) + word[-1]
amount = int(input())
for i in range(0, amount):
print(abbr(input()))
|
0bb704da0099869834b7e4f7dcec2faa8ace0a82 | ErsanSam/Data-Analyst-Career-Track | /4. Mengolah Dataset Dalam Jumlah Kecil sampai dengan Besar/Part 2/1. Penggabungan Series/4, join.py | 399 | 4 | 4 | import pandas as pd
df1 = pd.DataFrame({
'key':['k1','k2','k3','k4','k5'],
'val1':[200,500,0,500,100],
'val2':[30,50,100,20,10]
})
df2 = pd.DataFrame({
'key':['k1','k3','k5','k7','k10'],
'val3':[1,2,3,4,5],
'val4':[6,7,8,8,10]
})
#penerapan join dengan menggunakan set_index dan keyword how
join_... |
0cd9402ee4abc5d52422acf69d78f07f888c9c8f | enrico-secco/Python-Studies | /Sintaxe/1.3. Tuplas.py | 569 | 3.578125 | 4 |
# um_array = [] # Lista
# print(type(um_array))
#
# dicionarios = {} # Lista do tipo Dict
# print(type(dicionarios))
# Entendendo sobre tuplas
#Declaração de Listas do tipo Tuplas -> são dados fixos.
dias_da_semana=('Domingo','Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sábado') # -> convencional
dias_da_sema... |
13e94726844683a6138de6191e2e351d6635923e | mayur1101/Mangesh | /Python_Day4/Q6.py | 203 | 4.03125 | 4 | def Sum(number):
Last=number%10
first=0
while(number>=10):
number=number//10
first=number
return first + Last
number=int(input("Enter the number:"))
print(Sum(number)) |
c8e2fa85899e7bf965449305ca7a323da34b7480 | jfly/dotfiles | /homies/bin/dual_blueoot/util.py | 425 | 3.765625 | 4 |
def group_by(arr, *, unique=True, key):
grouped = {}
for el in arr:
k = key(el)
if unique:
assert k not in grouped, "The given key is not unique for the array"
grouped[k] = el
else:
if k not in grouped:
grouped[k] = []
gro... |
a0aeb81d7001765e1b26758e709c9b597b6471f7 | Marikyuun/AS91906 | /6. User Name Entry.py | 3,705 | 3.578125 | 4 | from tkinter import *
from functools import partial # To prevent unwanted windows
class Quiz:
def __init__(self):
# Formatting variables
background_color = "coral"
# Quiz Frame
self.quiz_frame = Frame(bg = background_color,
... |
f1e7c0429d6913856342195b067e94614fe24476 | LukaszSztuka/Jezyki-Skryptowe | /lab2/3-4.py | 168 | 3.625 | 4 | min = int(input("Podaj dolny zakres: "))
max = int(input("Podaj górny zakres: "))
for i in range(min, max+1):
if (i % 2) == 1 and (i % 17) == 0:
print(i)
|
9f2c8859ffea77df250724fb78baf04ea723f947 | manavkulshrestha/Computational_Physics | /1.24/euler.py | 257 | 3.5 | 4 | from numpy import exp, sin, cos, pi
def print_euler(alpha):
print(f'LHS = {exp((0+1j)*alpha)}\nRHS = {complex(cos(alpha),sin(alpha))}')
for i in range(0, 11):
print(f'{print_euler(i)}\n')
alpha = complex(input('Input alpha: '))
print_euler(alpha) |
2df09bd59db9e6e57567683ad76c8f978ab2344b | Aasthaengg/IBMdataset | /Python_codes/p03568/s588296033.py | 154 | 3.546875 | 4 | n = int(input())
A = list(map(int,input().split()))
even = odd = 0
for a in A:
if a%2:
odd += 1
else:
even += 1
print(3**n - 2**even)
|
fda5ddf205ad6f79ce3129be311bae0608fe7184 | Runsheng/bioinformatics_scripts | /wormbase/orthoget.py | 2,278 | 3.578125 | 4 | #!/usr/bin/env python
# Runsheng, 2016/01/25
# get a function to wrap all the para into one function to run in shell
import argparse
def ortho_to_list(orthfile):
gene_l=[]
with open(orthfile, "r") as f:
full_gene=f.read()
gene_l=full_gene.split("=")
return gene_l
def sp2_extract(gene_l, name)... |
2bf1c685885112fbcc584900f917fdd4cbe30064 | dbconfession78/interview_prep | /leetcode/65_valid_number.py | 1,553 | 4.09375 | 4 | # Instructions
"""
Validate if a given string is numeric.
Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true
Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.
"""
import string
class Solution:
d... |
955381411cb7d7d39309c9d1706525cc26f6c861 | wattaihei/ProgrammingContest | /AtCoder/ABC-A/175probA.py | 137 | 3.9375 | 4 | S = input()
if S == "RRR":
ans = 3
elif S == "RRS" or S == "SRR":
ans = 2
elif "R" in S:
ans = 1
else:
ans = 0
print(ans) |
935c2e97f8fcadd8c0d60f930c552bfa32ea331f | Ujwal-Ramachandran/ITT-Lab | /Lab5/Q1a.py | 290 | 3.953125 | 4 | def cal(a,b,op):
if op=='+':
return a+b
elif op=='-':
return a-b
elif(op=='*'):
return a*b
elif(op=='/'):
return a//b
a,b= input("Enter 2 numbers : ").split()
op = input("Operation : ")
print(a,op,b,' = ',cal(int(a),int(b),op)) |
150c0bc58eb1d45c884859b265912012b1436dc4 | zdravkob98/Fundamentals-with-Python-May-2020 | /Programming Fundamentals Mid Exam - 29 February 2020 Group 1/02. MuOnline.py | 965 | 3.578125 | 4 | health = 100
bitcoin = 0
rooms = input().split('|')
for i in range( len(rooms)):
tolken = rooms[i].split(' ')
command = tolken[0]
number = int(tolken[1])
if command == 'potion':
if health == 100 :
print("You healed for 0 hp.")
elif health + number > 100:
print(f... |
4db813fc239442715c0b979041139723ddfa98e9 | CatmanIta/x-PlantForm-IGA | /turtles/turtle.py | 21,047 | 4.25 | 4 | """
Classes for drawing L-system structures.
The Turtle defines the points corresponding to the turtle representation of an L-system structure.
@author: Michele Pirovano
@copyright: 2013-2015
"""
import turtles.my_mathutils
import imp
imp.reload(turtles.my_mathutils)
from turtles.my_mathutils import... |
0c4d48c2f27ee22e7da1cb4cba70591503caf4de | jperilla/Machine-Learning | /Reinforcement Learning/car.py | 1,970 | 3.578125 | 4 | class Car:
def __init__(self, x, y, vx, vy, max_x, max_y):
self.position = CarPosition(x, y)
self.last_position = CarPosition(x, y)
self.velocity = CarVelocity(vx, vy)
self.last_velocity = CarVelocity(vx, vy)
self.max_x = max_x
self.max_y = max_y
def accelerate(... |
dfe51d9008383ee0808d9c0042c7e1f35f37d36a | shivansamattya09/Pincode | /pincode.py | 653 | 3.71875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
import csv
import numpy as np
import random
import math
state = input("Enter State : ")
df = pd.read_csv("/Users/shivanshamattya/Desktop/pincode/state1/" + state +".csv",)
# In[2]:
df.dropna(axis=0, how='any',inplace=True)
# In[3]:
district... |
c3f8a8de9149a49334627af33bc201cd7c66aa44 | HEroKuma/leetcode | /1604-least-number-of-unique-integers-after-k-removals/least-number-of-unique-integers-after-k-removals.py | 921 | 3.65625 | 4 | # Given an array of integers arr and an integer k. Find the least number of unique integers after removing exactly k elements.
#
#
#
#
#
# Example 1:
#
#
# Input: arr = [5,5,4], k = 1
# Output: 1
# Explanation: Remove the single 4, only 5 is left.
#
# Example 2:
#
#
# Input: arr = [4,3,1,1,3,3,2], k = 3
# Output: 2
#... |
66183b40c01c329f8bd0c8e986874a3ef374d523 | DenisRudakov0/Algorithm | /19 Угадайка слов.py | 4,785 | 3.65625 | 4 | from random import *
word_list = ['корабль', 'карандаш', 'медуза', 'грабитель', 'моряк', 'абонемент', 'авиасалон', 'бессонница',
'вакуум', 'велосипед', 'викторина', 'дрессировщик', 'жужелица', 'иероглиф', 'коктейль', 'крокодил']
def get_word(word_list):
return choice(word_list)
def display_hangman(t... |
fe2a5f6db97bfdb5509f3112a7ec50d1ce7d3a07 | Eazjay/Chaining_Methods | /chaining_methods.py | 965 | 3.84375 | 4 |
class User:
def __init__(self, first_name, last_name, age, account_balance):
self.first_name = first_name
self.last_name = last_name
self.age = age
self.balance = account_balance
def make_deposit(self, amount):
self.balance += amount
return self
def make_wit... |
c318a7baa3e8f3caa138ce383ba51652d8d934a0 | FaisalAlnahhas/Machine-Learning-Fall-18 | /K-means clustering.py | 4,339 | 4.15625 | 4 | ############################################
#Faisal Alnahhas
#k-means clustering
#UTA - Fall'18
#CSE 6363 - Machine Learning
#Assignment 3
############################################
# coding: utf-8
# In[23]:
import numpy as np
from sklearn import datasets
import pandas as pd
import random
# In[2]:
data = datas... |
94de03141f724094e52e2f8dcbb246d26916383d | 2099454967/wbx | /04day/2-保护对象属性优化版.py | 437 | 3.515625 | 4 | class Dog():
def __init__(self):
self.__age = 1 #私有属性
pass
def wark(self):
print("汪汪叫")
def setAge(self,age):
if age <= 0:
print("传入年龄有误")
else:
self.__age = age
def getAge(self):
return self.__age
def __str__(self):
return "狗的年龄是%d"%self.__age
xiaohuang = Dog()
xiaohuang.setAge(-10)
#... |
80983b7f7375608f7b6982287a0d8e8687402838 | julianaprado/forcaEuProfessor | /forcaEuProfessor.py | 4,694 | 3.671875 | 4 | import random
def forca(numRodadas):
lista = [ '''
+---+
| |
O |
/|\ |
/ \ |
|
=========''',
'''
+---+
| |
O |
/|\ |
/ |
|
=========''',
... |
dbbf77a46a7f0cc7f43a7413ce0757b76a8ce251 | jbhennes/CSCI-220-Programming-1 | /Chapter 1/circleArea.py | 725 | 4.21875 | 4 | #Stalvey and class
#Purpose: This code calculates the area of a circle
# given the radius provided by the user
from math import *
def main():
print("Calculates the area of a circle.")
print()
#ask for input of radius
radius = input("Enter radius: ")
radius = eval(radius)
#calculate ... |
ace2857015f86348df519416f5d144ecf03a2f80 | leegangho/20190701 | /Python/other_다리를지나는트럭.py | 1,850 | 3.8125 | 4 | import collections
DUMMY_TRUCK=0
class Bridge(object):
def __init__(self,length,weight):
self._max_length=length
self._max_weight=weight
self._queue=collections.deque()
self._current_weight=0
def push(self,truck):
next_weight=self._current_weight+truck
if next_... |
da9d235d2c26db945093380dd6a6b496c277aef4 | ajerit/python-projects | /laboratory1/Lab4/Lab04Ejercicio1.py | 1,190 | 3.890625 | 4 | #
# Adolfo Jeritson. 12-10523
#
# Descripcion: Dados los coeficientes de un polinomio, lo construye y
# muestra el grado del mismo
#
# 5/05/2015
#
# Variables
# coef : array(0,M] of int
# c: int
# M: int
# polinom: array[0, len(coef)+1) of str
# grado: int
# i: int
# Valores Iniciales
M = int(input("Introduza el val... |
bab90ea66c283ac913ce142f60925e3c68c5615b | Superbeet/LeetCode | /Pinterest/English-formatted_Names.py | 3,615 | 4.3125 | 4 | # -*- coding: utf-8 -*-
# list of names) and returns a string representing the English-formatted
# conjunction of those names.. more info on 1point3acres.com
#
# For example, given these names: ['Alice', 'Bob', 'Carlos', 'Diana'].
#
# The output would be: "Alice, Bob, Carlos and Diana"
def conjunctNames(names):
... |
bf7eaab5362146a9537816c5bd67b0b7944a2d04 | plazotronik/test_2 | /var.py | 268 | 3.65625 | 4 | #нзначаем переменную
var = 8
print( var )
# summa
var = var + var -13
print( var )
#new chislo
var = 3.142
print( var )
# string
var = 'Python in easy steps'
print( var )
#logical
var = True
print( var )
""" bolshoy commentariy
nerealno
bolshoy"""
|
675cd499c16d4a91a272c3e32752c5efda852178 | jchiefelk/ITEC-430 | /kyle/Homework4/set#2.py | 236 | 4 | 4 | #!/usr/bin/python
Stringlist = ["robot", "developer", "engineer", "AI", "data", "quantum", "computing", "statistics", "backend", "frontend"]
n = len(Stringlist)
#print len(Stringlist[2])
for x in range(n):
print len(Stringlist[x])
|
3a487097f8e75cf6c913aa2d837c66d310a82738 | tjscollins/algorithms-practice | /Python/Data Structures/bst.py | 3,002 | 3.96875 | 4 | class BSTNode:
def __init__(self, key, data):
self.key = key
self.data = data
self.left = None
self.right = None
self.parent = None
class BST:
def __init__(self):
self.root = None
self.size = 0
def insert(self, key, data):
if self.root is ... |
f6aa43eb3031c8bf4392241742a8042203056b57 | TatsuLee/pythonPractice | /leet/singleLink.py | 1,407 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class Node(object):
def __init__(self, val, next):
self.val = val
self.next = next
def show(self):
print "Showing list:"
current_node = self
while current_node is not None:
print current_node.val, "->",
... |
6a91629a3c0dcfe993cb3ef9f66718a69a45e81f | nnininnine/Data_Structure_lab | /Test_Exam/testClass.py | 164 | 3.625 | 4 | from StackClass import stack
from Queue import queue
num = input('Enter your number : ').split()
l = queue()
for i in num:
l.enQueue(int(i))
print(l.mirror()) |
a4f2dce0a2d041b536435955ad980a993ce63570 | OkkarMin/approximate-computing-tool | /ErrorAnalyser/AdderErrorAnalyzer.py | 10,908 | 3.515625 | 4 | import random
import math
from . import ApproxAdders
## Error Calculations (AE, MAE, RMSE)
# HEAA
def HEAA(tot_num_bits, inaccurate_bits):
HEAA_estimate_AE = 0.0
HEAA_estimate_MAE = 0.0
HEAA_estimate_RMSE = 0.0
if tot_num_bits <= 10:
for num1 in range(2 ** tot_num_bits):
for nu... |
c40690532492e017e611074a1af7e749f819d2ac | sridharbe81/python_sample_program | /cont.py | 401 | 3.96875 | 4 |
# Normal Fibonacci
def fib(max):
numbers = []
a,b = 0,1
while a<max:
numbers.append(a)
a,b = b, a+b
return numbers
print(fib(10))
#Fibonacci using Generator
def fib(max):
a,b = 0,1
while a<max:
yield a
a,b = b, a+b
obj = fib(10)
print(obj)
pri... |
f23e7b3ac47c92141928c3a1b6d83fee2b2bd2dc | dionysus/cryptography | /caesarCipher_V03.py | 1,265 | 4.1875 | 4 | # ----- Caeser Cipher v03 ----- #
LIBRARY = '?aZbY1cXdW2eVfU3gTh4SiRj5QkPl6OmNn7MoLp8KqJ9rIs0HtG uFvE,wDxC.yBzA!'
def encrypt(plaintext: str, keyphrase: int) -> str:
'''
Using the Ceaser Cipher method to shift the alpha characters of the string
plaintext in lowercase by the key amount, then return the e... |
a3b2ee82b0496a2f85550fb08d2af35fe6ba377e | leofoch/PY | /ImfoPermanente.py | 2,230 | 3.546875 | 4 | import pickle
class Persona:
def __init__(self,nombre,genero,edad):
self.nombre=nombre
self.genero=genero
self.edad=edad
print("se creo una persona nueva con el mobre: ", self.nombre)
def __str__(self):
return "{} {} {}".format(self.nombre,self.genero,self.edad)
class... |
e693ea0bd9e59f9d0f22e384ef0e364c634b2555 | andrewFisherUa/Advanced_Python_Course | /Lesson_6/lesson_6_practical.py | 4,784 | 4.0625 | 4 | # 1) Создать свою структуру данных Список, которая поддерживает
# индексацию. Методы pop, append, insert, remove, clear. Перегрузить
# операцию сложения для списков, которая возвращает новый расширенный
# объект.
class MyCustomList:
def __init__(self, *args):
self._list = list(*args)
def __str__(self... |
00178d59307cf8873bf456313b566380c1d96f16 | ericbollinger/AdventOfCode2017 | /Day11/second.py | 1,251 | 3.796875 | 4 | import math
def findWayBack(x,y):
cur = 0
while (x != 0 or y != 0):
if (x == y):
return cur + x / 0.5
if (x == 0):
return cur + math.fabs(x - y)
if (y == 0):
return cur + (math.fabs(x - y) * 2)
if (x > 0):
x -= 0.5
else:
... |
df1a32083dc76a3d79c0eaba26b7abf98a51b4f5 | aluhrs/Optimal_Bike_Share_Locations | /elevation.py | 6,699 | 3.9375 | 4 | """
This file:
1) Pulls elevation data from Google Maps API for all of the points in the Crowd_Sourced table in the database.
2) Reads the json data from Google Maps and updates the elevation column in the database with the elevation data.
3) Pulls the elevation data back out, creates a radius of about 3 block radius a... |
c0876e0d0736e58163e3360e3a26f6b26861fd8e | Digm74/pythonProject_rep | /var.py | 865 | 4.28125 | 4 | print('Варианты записи физических и логических строк')
print('''i=5 # Физическая строка на ней расположена логическая строка
print(i) # Физическая строка на ней расположена логическая строка''')
i=5 # Физическая строка
print(i) # Физическая строка
print('''a=45;print(a) # Физическая строка на которой записаны две логи... |
e847ebbcba5a73040159704310aed86ca8c677e7 | j611062000/Coursera_Algo._Standford | /Graph Search, Shortest Paths, and Data Structures/medianMaintenance.py | 3,180 | 3.859375 | 4 | from heapDataStructure import Heap
def printHeap(HeapFormedian):
print("maxHeap.Heap=%s" % (HeapFormedian.maxHeap.Heap), end=" | ")
print("minHeap.Heap=%s" % (HeapFormedian.minHeap.Heap))
def printTop(HeapFormedian):
print(
"L Top:{} || R Top:{}".format(
HeapFormedian.leftTop,
... |
055ccfaef9fef5dad2cf63c86d560236745f6cc8 | kilbooky/hackerrank | /30days/11_2d_arrays.py | 1,798 | 3.75 | 4 | #!/bin/python3
import sys
# (provided by hackerrank -- get input into 2x2 array)
arr = []
for arr_i in range(6):
arr_t = [int(arr_temp) for arr_temp in input().strip().split(' ')]
arr.append(arr_t)
# now, sum values of each hourglass
#!/bin/python3
import sys
# (provided -- get input into 2x2 array)
arr = ... |
e649eb8b0d89e4682370ecde6b7edf573a80af7f | Allen-C-Guan/Leetcode-Answer | /python_part/Leetcode/DP/Mid/面试题14- I. 剪绳子/DP.py | 805 | 3.515625 | 4 | '''
这道题就应该用dp,作为一个python用户,如果没有用恰当的方法,根本就跑不过的
dp[i]定义的是: 以i为长度的绳子,最少减一刀的最大值。(这个值的是最小剪一刀的最优解)
i长度的组成分为两部分:
i-j 和 j
其中j部分是一定不剪开的(因为j会遍历的),而i-j要分为,i-j是一刀不剪(i-j)还是至少剪一刀(dp[i-j])
因此dp方程为:
dp[i] = max(dp[i-j]*j, dp[i], (i-j)*j)
'''
class Solution:
def cuttingRope(self, n: int) -> int:
if n <= 2: return 1
... |
982e1ee33b6dee3966fc3ef49963aae1121a3af6 | AMAN123956/Python-Daily-Learning | /Day20(Snake Game Part-1)/turtles.py | 255 | 3.8125 | 4 | from turtle import Turtle
segments=[]
position=[(0,0),(-20,0),(-40,0)]
for i in range(0,3):
new_segment = Turtle("square")
new_segment.color("white")
new_segment.penup()
new_segment.goto(position[i])
segments.append(new_segment)
|
bd16f48383b0b9446c3c722a7d683e1a089135eb | CyberKnight1803/ML_from_scratch | /ML_from_scratch/supervised_learning/FLD.py | 3,577 | 3.53125 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
class FLD():
def getWeights(self, X_p, X_n):
"""
Parameters :
Shape = (N, D) i.e (examples, features)
X_p : Positive examples
X_n : Negativ Examples
Return:
W : Unit Vector
... |
28b9b0bb14a1dc0d8ae3426e47d1302cc0128135 | stevenwang/flaskJSONRPCServer | /flaskJSONRPCServer/example/rr1.py | 502 | 3.671875 | 4 | data=[]
def arrMedian(arr, arrMap=None):
if not len(arr): return 0
elif len(arr)==1: return arr[0]
if not arrMap:
arrMap=sorted(range(len(arr)), key=lambda i:arr[i], reverse=False)
if len(arrMap)%2:
median=arr[arrMap[len(arrMap)/2]]
else:
median=(arr[arrMap[(len(arrMap)-1)/2]]+arr[arrM... |
0fab74bd50ebc8c49c4baabc75b4e1d1202b9e33 | JamCrumpet/Lesson-notes | /Lesson 7 function/7.13_making_an_argument_optional.py | 1,550 | 4.8125 | 5 | # sometime you have to make an argument optional so the user can choose to input the extra argument
# you can use default values to make an argument optional
# for example if we want to let users input their full names and make middle names optional
def get_formatted_name(first_name, middle_name, last_name):
... |
92d2e48959380fba1fcd622f3ef4cbd1104630ce | SasCezar/PedestrianTrajectoryClustering | /ptcpy/trajectory_clustering/common.py | 200 | 3.5 | 4 | """
Created on 4. 5. 2015
@author: janbednarik
"""
from math import *
def euclid_dist(p1, p2):
assert (len(p1) == len(p2))
return sqrt(sum([(p1[i] - p2[i]) ** 2 for i in range(len(p1))]))
|
5a491921d9b02016098a78da2a722a0ec8df6001 | Ankitsingh1998/ML-DL-AI_internship | /Day089_KMeans_clustering.py | 2,671 | 4.3125 | 4 | #Day089 - kMeans (Unsupervised Machine Learning)
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.read_csv('xclara.csv')
df.shape #shape of dataframe
df.columns.to_list() #column_names into list
df.ndim #dimension of dataframe
df.isnull().any(axis=0) #axis = 0 for row wise nu... |
b62a407d0bae68c178d7d8ebb1de373a3b71bf71 | MuhummadShohag/PythonAutomation | /OS_Module/introduction_os_module.py | 1,345 | 3.984375 | 4 | '''
OS_Module: This module is used to work/interact with operating system to automate many more task
like creating directory, removing directory, identifying current directory and many more
* You can work both operating system through os_module
'''
import os
# os.sep is the (or a most common) pathname se... |
0f9049d50ad970070a544e407d42411ff4bf0d47 | 824zzy/Leetcode | /G_BinarySearch/BasicBinarySearch/L1_1533_Find_the_Index_of_the_Large_Integer.py | 517 | 3.640625 | 4 | """ https://leetcode.com/problems/find-the-index-of-the-large-integer/
binary search
"""
class Solution:
def getIndex(self, reader) -> int:
l, r = 0, reader.length()-1
while l<r:
m = (l+r)//2
if (r-l)&1:
res = reader.compareSub(l, m, m+1, r)
i... |
ec5805e954cb371664cd0aa165d375b52063cab6 | sheauyu/sapy | /src/figures/F5_30_filter_images.py | 1,320 | 3.59375 | 4 | """ Demonstration on how to filter images """
# author: Thomas Haslwanter
# date: April-2021
# Import the standard packages
import numpy as np
import matplotlib.pyplot as plt
import os
# For the image filtering
from scipy import ndimage
# Import formatting commands
from utilities.my_style import set... |
12b2327626d2ae54ab17ac1943421f42dc9b21be | NicholasPiano/scripts | /scratch/Python/packing/packing.py | 397 | 3.734375 | 4 | #!usr/bin/python
#objects for box, field, and algorithm
#methods to run algorithm and return properties of box arrangement
#file output
import vector
#all vectors are in three dimensions
#field class
class field:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
class box:
def __init__(self, ... |
ad621e68466b60df795ec62e5d8660bf7a89a218 | csaden/euler | /0044euler_PentagonNumbers.py | 928 | 3.796875 | 4 | # Pentagonal numbers are generated by the formula,
# Pn=n(3n-1)/2. The first ten pentagonal numbers are:
# 1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...
# It can be seen that P4 + P7 = 22 + 70 = 92 = P8.
# However, their difference, 70 - 22 = 48, is not pentagonal.
# Find the pair of pentagonal numbers, Pj and Pk,
#... |
31b38157ec3fa4eb03334880cdef4a5a1a3e5e85 | Magnificent-Big-J/advent-of-code-2017 | /08/registers_part_two.py | 1,415 | 3.734375 | 4 | """
--- Part Two ---
To be safe, the CPU also needs to know the highest value held in any register
during this process so that it can decide how much memory to allocate to these
operations. For example, in the above instructions, the highest value ever held
was 10 (in register c after the third instruction was evaluat... |
bffb24698769188589de72b0454a4d94401b8f30 | hacktheinterview/hacktheinterview | /problems/58/Main.py | 371 | 3.78125 | 4 | import math
#--SPLIT--
#-class Solution:
# @param a : string
# @return an integer
#- def lengthOfLastWord(self, a):
#--SPLIT--
class Solution:
def lengthOfLastWord(self, a):
return 0
#--SPLIT--
if __name__ == "__main__":
test_cases = int(raw_input())
for i in range(test_cases):
a = raw_input()
solution ... |
b8f12627e88fea77b9f502cc3d751667eece6173 | cmnaveen/study_cmp | /python/break_continue.py | 572 | 3.859375 | 4 |
#prime number
for n in range(2,19):
for x in range(2,n):
if n % x == 0:
print n, 'equals',x,'*',n/x
break
else:
print n, 'is a prime number'
# even odd numbers
for num in range(2,19):
if num % 2 == 0:
print "even num:",num
continue
pri... |
39e2a7b43ca07dc7df05a06d6b3b181d6d9c56d1 | xSandie/python_data_structure | /C1_LinkedList/reverse_neighbor_1_7/reverse.py | 1,075 | 3.984375 | 4 | from C1_LinkedList.LNode import LNode
def reverse(head):
#判断链表是否为空
if head is None or head.next is None:
return
cur = head.next#对cur与cur.next进行对调
pre = head
next_next = None#当前节点的后继节点的后继节点
while cur is not None and cur.next is not None:
next_next = cur.next.next
pre.nex... |
6d10e93b7da1c117c5d83631b521341a8a58d6f9 | humrochagf/flask-reveal | /flask_reveal/tools/helpers.py | 1,976 | 3.609375 | 4 | # -*- coding: utf-8 -*-
import os
import shutil
import tarfile
import zipfile
try:
# Python 3
FileNotFoundError
except NameError:
# Python 2
FileNotFoundError = IOError
def move_and_replace(src, dst):
"""
Helper function used to move files from one place to another,
creating os replacing... |
03542bb32e7b68802d29dd3edb6a972f75a3e75a | PFZ86/LeetcodePractice | /Math/0326_PowerOfThree_E.py | 587 | 4.03125 | 4 | # https://leetcode.com/problems/power-of-three/
# Solution 1: the iterative method
class Solution(object):
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
if n <= 0:
return False
while n > 1:
if n%3 != 0:
... |
120c25b2aa19af0bb271502061f37e560bde57b6 | ar2126/Ngram-Viewer | /N Gram Viewer/trending.py | 1,979 | 4.0625 | 4 | """
Finds the top 10 and bottom trending words based on a given start and end year
author: Aidan Rubenstein
"""
from wordData import *
import operator
class WordTrend(struct):
_slots = ((str, 'word'), (float, 'trend'))
def trending(words, startYr, endYr):
"""
Iterates through the words dic... |
75f1e68ca1452cb36f240627012de4b7a84aac68 | mtharanya/python-programming- | /largestnum.py | 223 | 3.65625 | 4 | alist=[-45,0,3,10,90,5,-2,4,18,45,100,1,-266,706]
largest, larger = alist[0], alist[0]
for num in alist:
if num > largest:
largest, larger = num, largest
elif num > larger:
larger = num
print larger
|
cd621b5d4391d5c48cdb3ef7c6c0369d07d740d6 | Take-Take-gg/20460065-Ejercicios-Phyton | /Ejercicios-05/Datos_compuestos-01.py | 900 | 4 | 4 | # Datos compuestos 01
"""
1.- Realiza una función separar(lista) que tome una lista de números enteros
desordenados y devuelva dos listas ordenadas. La primera con los números pares y la
segunda con los números impares.
"""
numeros = []
for var in range(int(input("Cuantos numeros agregaras a la lista? "))):
numero... |
12b936b19c003f2e7dfa5d65eadf7dc4a23d4335 | mshekhar/random-algs | /general/sequence-reconstruction.py | 1,873 | 3.78125 | 4 | import collections
from Queue import Queue
class Solution(object):
def construct_graph(self, seqs):
graph = {}
for seq in seqs:
i = 0
while i < len(seq):
if seq[i] not in graph:
graph[seq[i]] = set()
if i + 1 < len(seq) an... |
b77981ed595cb39f899498dcd2f0b9b550a68d0d | benjiaming/leetcode | /test_reverse_words_in_string_iii.py | 456 | 3.78125 | 4 | import unittest
from reverse_words_in_string_iii import Solution
class TestSolution(unittest.TestCase):
def test_reverse_words_in_string_iii(self):
solution = Solution()
self.assertEqual(solution.reverseWords(""), "")
self.assertEqual(solution.reverseWords(" "), "")
self.assertEqua... |
3d1c8214ab319ba022751b38a13b1651e270a71b | sent1nu11/password-manager | /main.py | 1,257 | 3.5625 | 4 | from tkinter import *
# ---------------------------- PASSWORD GENERATOR ------------------------------- #
# ---------------------------- SAVE PASSWORD ------------------------------- #
# ---------------------------- UI SETUP ------------------------------- #
window = Tk()
window.title("Password Manager")
window.con... |
9f28e93d0f84132cebac314e086dcc5b3330cb9a | IronE-G-G/algorithm | /leetcode/101-200题/108convertSortedArr2BST.py | 1,468 | 3.859375 | 4 | """
108 将有序数组转化成二叉搜索树
将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
示例:
给定有序数组: [-10,-3,0,5,9],
一个可能的答案是:[0,-3,9,-10,null,5],它可以表示下面这个高度平衡二叉搜索树:
0
/ \
-3 9
/ /
-10 5
"""
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):... |
c1753f0d9186180204b79ee8abc22111fa3d7bbf | cowboybebophan/LeetCode | /Solutions/784. Letter Case Permutation.py | 995 | 3.8125 | 4 | """
https://leetcode.com/problems/letter-case-permutation/discuss/342024/Python3-recursive-solution-beats-98-with-explanation
"""
# DFS + Recursion
class Solution:
def letterCasePermutation(self, S: str) -> List[str]:
res = []
self.dfs(S, 0, res, '')
return res
def dfs(self, S, in... |
e2b376b685ba3c63471935f3918f1a6304f84d75 | vaishnavi-consultants/Computer-Science | /Python-Draft1/Projects/sqlite/sqlite_insert.py | 789 | 4.375 | 4 | # Python code to demonstrate table creation and
# insertions with SQL
# importing module
# python sqlite.py Insert Accounts employee "3, 'Maha', '240000', 'M', 'Software'"
import sqlite3
def sqlite3_insert_rec(dbname, tablename, rec):
# connecting to the database
db_name = dbname+".db"
co... |
9efa904f7c715d03ba90eb8422fbaaa1655e707e | spezifisch/leetcode-problems | /search-insert-position/one.py | 444 | 3.875 | 4 | class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
i = 0
len_nums = len(nums)
while i < len_nums:
if nums[i] >= target:
return i
i += 1
return i
# Runtime: 40 ms, faster than 49.32% of Python3 online submissions for... |
8c88d0a5871946a56d708cef8ea365d54795d5d7 | Aygulx/AI_P2_AygulBayramova | /csp.py | 8,479 | 3.609375 | 4 |
# defining CSP
class CSP:
"""
A class used to represent a CSP problem.
...
Attributes
----------
variables : list
Vertives of the graph
neighbors : dictionary
Represents neighbors of each vertex
domain : list
All possible values(colors)
Methods
--... |
04f4ba4f2c4113e63be5102688e806f6867dd03e | rezmont/prep | /moderate/check-tic-tac-toe.py | 851 | 3.578125 | 4 | import random
def print_grid(grid):
print '\n'.join([str(l) for l in grid])
def check_if_won(grid):
"""row"""
for i in xrange(3):
set_row = set()
set_col = set()
for j in xrange(3):
set_row.add(grid[i][j])
set_col.add(grid[j][i])
if len(set_row)==1... |
5f995166a5b818e1fe0f8194a71f1d26b58e36fd | francescaser/pyAcademy | /Esercizi base 22-02/FuncContOccorrenzaLettera.py | 420 | 3.75 | 4 | # Crea una funzione che presi in input una stringa (nome) e
# un carattere (i.e. stringa di lunghezza 1),
# conti le occorrenze del carattere all’interno della stringa
def find(parola, lettera):
contatore = 0
i = 0
while i<len(parola):
if parola[i]==lettera:
contatore += 1
... |
b54fe1f28056991042cf8eb75995ad1ebefbb866 | hermesvf/Calculator-the-game | /solve.py | 3,356 | 3.890625 | 4 | #!/usr/bin/env python3
from sys import argv
from itertools import product
DEBUG = 0
def debug(s):
if DEBUG == 1:
print(s)
actions = { 'addition' :'+', \
'substract' :'-', \
'product' :'*', \
'division' :'/', \
'exchange' :'X', \
'append' :'A', \... |
3602d74c9e268d133efe4d19b05c15d677a93d66 | t0etag/Python | /Python2/Labs/Lab06cX.py | 2,381 | 4.15625 | 4 | """LAB 06c
In your data file is a program named servercheck.py. It reads two files
(servers and updates) and converts the contents into two sets. The
updates are not always correct. You will find all of the set
operations/methods in Python Notes. Using just these
operations/methods, your job is as follows:
1. Det... |
c35252e4110e7c0ef3ead3a40cd4435fdcb888ca | Jbflow93/projectpython | /projectattm@.py | 1,509 | 4.125 | 4 | import random #any time i use random have to import first
def about_me():
print("Hi, My name is Jabari\n Im from Chicago\n My favorite team are the Denver Nuggets") # \n helps space out your strings
def q():
question1 = ["what state you live in?","How old are you?", "What is your favorite animal?"] #[] whe... |
71f59141147284855dbb9c3e61de5e080ddc759f | mrPepcha/devops-python | /HW_lesson_7/HW_lesson_7.3.py | 2,076 | 3.703125 | 4 | #3. Реализовать программу работы с органическими клетками, состоящими из ячеек.
# Необходимо создать класс Клетка. В его конструкторе инициализировать параметр,
# соответствующий количеству ячеек клетки (целое число). В классе должны быть реализованы методы перегрузки
# арифметических операторов: сложение (add()), в... |
c5fe33b12d65204cf065aeff0ffb7db2c37fa916 | dotastar/Leetcode-Design-CompanyEx | /Array/Insertion_Sort_List.py | 1,031 | 4.15625 | 4 | Sort a linked list using insertion sort.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param head, a ListNode
# @return a ListNode
def insertionSortList(self, head):
if not head:
r... |
b15c7f66e5d574148dc9ac92344d92440ec0744f | arossouw/study | /python/math/factorial.py | 204 | 4.28125 | 4 | #!/usr/bin/python
# recursive function for factorial
# factorial example: 4! = 4 * 3 * 2 * 1 = 24
def factorial(n):
if n == 0:
return 1
return n * factorial(n-1)
print factorial(4)
|
44d49e8ac8d2be472d6386b68844b56ab2c761fc | AK-1121/code_extraction | /python/python_22977.py | 176 | 3.96875 | 4 | # Dictionaries in Python and different ways of accessing it
for key in phonebook:
if key.startswith("Sm"):
print "Phone number of %s is %d" % (key, phonebook[key])
|
fa1b8c59f4a190a26a09156e186791a0e9ca7896 | josecervan/Python-Developer-EOI | /module2/exam/p2.py | 416 | 3.6875 | 4 | import datetime
def meetup_date(year, month):
assert year > 0
assert 1 <= month <= 12
new_date = datetime.date(year, month, 1)
while new_date.strftime('%A') != 'Thursday':
new_date += datetime.timedelta(days=1)
new_date += datetime.timedelta(days=7)
return new_date
print(meetup_dat... |
36e360ab9854a1059c4d8fb9c01aa4f1ede54866 | VasilyShcherbinin/LCS-Suite | /XCS/Problem_Parity.py | 3,792 | 3.65625 | 4 | """
Name: Problem_Parity.py
Author: Vasily Shcherbinin
Created: December 29, 2018
Description: Parity Problem
Input: Binary string
Output: No. of 1’s modulo 2
"""
import random
bits = 11
instances = 10
def generate_parity_instance(bits):
""" """
num_bits = sanity_check(bits)
if num_bits is None:
... |
5e8519d5e072edf669177340f6eb56a9426a7f5d | nadhiyap/play2 | /smin.py | 142 | 3.65625 | 4 | a=int(input("enter number"))
l=[]
for i in range(a):
b=int(input("enter number"))
l.append(b)
b=min(l)
l.remove(b)
print(min(l))
|
eed94712e305b261d97adc901df6081e77f553b9 | ivhak/TDT4113 | /a4/src/calculator.py | 6,075 | 3.75 | 4 | '''
Calculator that runs in a loop and evaluates expressions given by the user
'''
import math
import numbers
import re
import sys
import numpy as np
from containers import Queue, Stack
from wrappers import Function, Operator
class Calculator():
'''
The calculator takes a string in the form of an equation, p... |
cfc1924b593305f8eb3bbb5cdf7bc5fe41ac9b82 | mananvyas/python-practice | /operators.py | 304 | 3.859375 | 4 | #Operator supports multiplying string
lotsOfHello = "hello" * 10
print(lotsOfHello)
#Do not support string and number concat wtih +
#lotsOfHello = "hello" + 10
#print(lotsOfHello)
#Supports forming new list with * operator similar to support with string as above
mylist = [2,3,4]
print(mylist * 3)
|
8a9741489abbe7d6f25b7468e0ee6fecba94c74a | adityasingh108/python-Practice | /DSa/algorithm/insertion_sort1.py | 161 | 3.71875 | 4 | # from tkinter.constants import NUMERIC
def insertion_sort():
numbers=[i for i in range(100) if i%2!=0]
print(numbers)
insertion_sort() |
ffc56cf0367f4d06cf1052261fadd055c6332e40 | jihunroh/ProjectEuler-Python | /ProjectEulerCommons/GeometricalNumbers.py | 702 | 3.59375 | 4 | from math import sqrt
from itertools import count
def generate_triangular():
for i in count(1):
yield int(i* (i + 1) * 0.5)
def generate_pentagonal():
for i in count(1):
yield pentagonal(i)
def pentagonal(i):
return int(i* (3 * i - 1) * 0.5)
def is_triangular(n):
return ((-1 + sqrt(1 ... |
0a9ed1c1ef632080c2cd82b204ee5a552d0204c2 | Evangeline-T/6.009-1-solution | /lab7/lab.py | 14,817 | 3.5 | 4 | # NO ADDITIONAL IMPORTS!
import doctest
from text_tokenize import tokenize_sentences
class Trie:
def __init__(self, key_type):
self.value = None
self.children = dict()
self.key_type = key_type
def __setitem__(self, key, value):
"""
Add a key with the given value to th... |
e070dc6d07b0cb71425c3510bf98c4d147ed2908 | StRobertCHSCS/ics2o1-201819-igothackked | /unit_2/2_7_2_Loop_Patterns.py | 123 | 4.09375 | 4 |
number = int(input("Enter a number: "))
while number > 0:
print(number)
number = number - 1
print("Blastoff!!!") |
3a3d63af71de70e7c62e7a29d9fc8e911f16a8df | gnibre/leetcode | /super_ugly_number.py | 1,661 | 3.65625 | 4 | import heapq
# heapq, is a heap or not? why can't i use first n
class Solution(object):
def nthSuperUglyNumber(self, n, primes):
"""
:type n: int
:type primes: List[int]
:rtype: int
"""
# k <=100;
# O(N) to get smallest
# rule, l... |
068fc2f88ec93d2599259cf7f2d7f33332dbfea3 | PandaRec/Laba1 | /Laba1/7.1.py | 263 | 3.75 | 4 | count_of_rows = int(input())
rows = list()
flag = False
for i in range(count_of_rows):
rows.append(input())
for txt in rows:
if txt.lower().__contains__("кот"):
print("МЯУ")
flag = True
break
if not flag:
print("нет")
|
ff6b38c5446ef10c35c67a318be36a030458b206 | Zetinator/cracking_the_coding_interview | /python/string_rotation.py | 514 | 4.21875 | 4 | """1.9 String Rotation: Assume you have a method isSubst ring which checks if one word is a substring
of another. Given two strings, 51 and 52, write code to check if 52 is a rotation of 51 using only one
call to isSubstring (e.g., "waterbottle" is a rotation of "erbottlewat").
"""
def string_rotation(string_1: str, st... |
e5f8f54b4b2f7c8e4c3d2a9eafa4854928b5dd04 | zhouyuanp/python | /Object/Inherit.py | 814 | 4.03125 | 4 | #测试继承的基本使用
class Person:
def __init__(self,name,age):
self.name = name
self.__age = age #私有属性
def say_age(self):
print("我也不知道是该坚持还是该放弃")
class Student(Person): #子类继承父类的属性和方法
def __init__(self,name,age,score):
Person.__init__(self,name,age) #调用父类的构造器 #调用父类的方法 父类名.方法名(... |
0fac0007644bbaad9ba489ca138ec9cc256f2249 | anishst/Learn | /Programming/Python/DateTime Operations/DateTime_Practice.py | 1,413 | 3.875 | 4 | import time #https://docs.python.org/2/library/time.html
import datetime
from datetime import timedelta
# strftime #https://docs.python.org/2/library/time.html#time.strftime
print(time.strftime("%m/%d/%Y"))
print(time.strftime("%Y-%m-%d"))
print(time.strftime("%d-%m-%Y %H:%M:%S %p")) # timestamp
print(time.tzna... |
0234fe70753c553dd4352bf84ff1c83c24652355 | lamkavan/cs-learning-2019 | /Lessons/Section_3/Docstring/Docstrings.py | 2,965 | 4.53125 | 5 | ### The following describes basic docstrings for Python ###
# We use docstrings to document our code. Documenting the code makes it easier to read
# and understand. It is good practice, but not required for the code to work.
# We only cover docstrings for classes and functions/methods here.
# Note that there ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.