blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
dec0e1b90ed4b66d708ec6df3607b37a693ce04a | netotz/codecamp | /meta/preparation/interview_simulation/answer_query.py | 5,483 | 3.78125 | 4 | '''
Answer a Query
Imagine a length-N array of booleans, initially all false. Over time, some values are set to true, and at various points in time you would like to find the location of the nearest true to the right of given indices.
You will receive Q queries, each of which has a type and a value. SET queries have ty... |
ad589031f1f69af75ce28b0e39c66e36a1fd104c | JohnDoe-cyber/DSA-Practice | /Level-2/Array/reverse_array3.py | 648 | 3.75 | 4 | def leftRotate(arr, n, d):
if d == 0:
return arr
else:
a1 = arr[0:d]
a2 = arr[d:n]
print(a1, a2)
listy1 = []
for i in range(len(a1)-1, -1, -1):
listy1.append(a1[i])
print(listy1)
listy2 = []
... |
1dd7b747e3088626031eda8db9b1d10ef14ad0c3 | dotheright/mylovelycodes | /python/myLearnPythonTheHeardWay/ex32.py | 348 | 3.890625 | 4 | #!/usr/bin/env python
num = [0,1,2,4,5]
fruit =["apple","orange","banana"]
mix = [1,"people",2,"animals",3,"plant"]
for i in num:
print "num is %i"%i
for i in fruit:
print "fruit is %s"%i
for i in mix:
print "mix is %r"%i
element =[]
for i in range(6):
element.append(i)
for i in element:
... |
c352f1cc83cd320e7c776704fdb2cc7bf700e8ea | bananaradiation/projectEuler | /euler2.py | 612 | 3.890625 | 4 | # Each new term in the Fibonacci sequence is
# generated by adding the previous two terms.
# By starting with 1 and 2, the first 10 terms will be:
# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
# By considering the terms in the Fibonacci sequence
# hose values do not exceed four million, find the
# sum of the even-valued t... |
14dc6b2a8e07a27e56632ca8943c2556c23204eb | mozzieongit/Bike-Project | /pi_code/ctoi.py | 420 | 3.53125 | 4 | def ctoi():
print("------------------------------------------------0123456789ABCDEF")
str = raw_input("Enter name to convert (less then 16 Character): ")
if len(str)<=16:
x = [0] * 16 #array filled with zeroes
for i, w in enumerate(str):
x[i] = ord(w)
return x
... |
91ffac8954f1bf2f7fc6978e235895adff069dc5 | lijiayan2020/Code | /Python/Computer_level2_python3.5.4/p61.py | 993 | 3.640625 | 4 | ###输出整数的百位及以上
##i=eval(input("请输入一个整数:"))
##i=i/100
##i=int(i)
##print(i)
###获得字符串,按照空格分割,逐行打印
##s = input("请输入一段文字:")
##str = s.split()
##for i in str:
## print(i)
####星期几
##s=eval(input("请输入星期几(数字1-7):"))
##if s==1:
## print("星期一")
##elif s==2:
## print("星期二")
##elif s==3:
## print("星期三")
##elif s==4:
## ... |
94855765f30f4bdb7e5af236c8c34e2595d0ac3a | wuyuanpei/GomokuAI | /GomokuGame.py | 2,324 | 3.671875 | 4 | from state import State
from GameBoard import GameBoard
from MiniMax import MiniMax
import time
class GomokuGame():
"""五子棋游戏 方便测试"""
def __init__(self, player = 2, size = 15):
""" 构造器
player: 玩家执方 默认2为白棋
size: 棋盘大小
"""
self.player = player
self.size = ... |
4fa8b285068dd91ed6fac98751b2fc5129569686 | PodssilDev/Ejercicios-de-Python-Beginner-Friendly- | /Ejercicios de todo tipo/LetraRepetida.py | 910 | 3.96875 | 4 | '''Construya un programa en Python que reciba como entrada un string y
determine cual es la letra que mas se repite.
Restriccion: no utilice el m ́etodo count()'''
'''NOTA: A pesar de que este ejercicio proviene de una guia de funciones,
el ejercicio se puede realizar sin la necesidad de definir alguna funcion'''
# B... |
aa6fea623619cc50e15210e50feed7ed4a900f09 | Huanjue12138/date_structure | /高级python/10.9栈 队列.py | 1,824 | 3.84375 | 4 | # class Stack:
# def __init__(self,data):
# self.stack = []
# self.size = 0
# def push(self,data):
# self.stack.append(data)
# self.size += 1
# def pop(self):
# if self.stack:
# temp = self.stack.pop()
# self.size -= 1
# return temp... |
5e45a35acf69ad32a1efafcdfce173463d5dfc8e | marielitonmb/Curso-Python3 | /Desafios/desafio-81.py | 869 | 4.0625 | 4 | # Aula 17 - Desafio 81: Extraindo dados de uma lista
# Ler varios numeros e coloca-los numa lista. Depois mostrar:
# - quantos numeros foram digitados
# - a lista ordenada de forma decrescente
# - se o valor 5 foi digitado e esta ou nao na lista
lista = []
while True:
lista.append(int(input('Digite um valor: ')))... |
eb6fefb5fd5433bc658e855c8bc18285e969f171 | RobertGodin/CodePython | /ExempleMethodesSpecialesIterNext.py | 226 | 3.578125 | 4 | # -*- coding: utf-8 -*-
une_liste = [3,1,2]
un_iterateur = une_liste.__iter__()
print(un_iterateur)
print(un_iterateur.__next__())
print(un_iterateur.__next__())
print(un_iterateur.__next__())
print(un_iterateur.__next__())
|
cecddf158073db99024c0dbcaeee70b3db788f1b | danny128373/Practice-ML-and-Data-Science | /chapter3/groupby.py | 693 | 3.96875 | 4 | import pandas as pd
# Dictionary that's going to be used for dataframe
data = {'Company': ['GOOG', 'GOOG', 'MSFT', 'MSFT', 'FB', 'FB'],
'Person': ['Sam', 'Charlie', 'Amy', 'Vanessa', 'Carl', 'Sarah'],
'Sales': [200, 120, 340, 124, 243, 350]}
# Creating data frame
df = pd.DataFrame(data)
print(df)
# gr... |
ace1790a4330b47eb91d4bb493b6b0a2e96849e7 | ac3680/Caesar | /api/send_request.py | 3,277 | 3.609375 | 4 | #Module to assist in calculating security signatures in order to make requests.
#To use as main, run python send_request.py "http request message"
#in command line.
#Example:
#python send_request.py "POST --data \"uid=blanks&name=Nina Baculinao\" http://localhost:9002/K12"
#Things to Note:
#1) You must put \ before ... |
8a38fd6c4a94b206b1b8cd665be4f3835e95c487 | enjangse/hackerrank | /py-arithmetic.py | 287 | 3.84375 | 4 | #!/usr/bin python3
if __name__ == '__main__':
a = int(input("Masukkan angka pertama: "))
b = int(input("Masukkan angka kedua: "))
sum = a+b
dif = a-b
prod = a*b
print("Hasil Pertambahan " + str(sum))
print("Hasil Pengurangan " + str(dif))
print("Hasil Perkalian " + str(prod))
|
d509a70f3c9d7124ba425dd37dd8f8ffa9d1f9e6 | ErickRosete/Data-Structures-Python | /BinarySearchTree.py | 3,808 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 10 11:42:36 2019
@author: erick
"""
class BinarySearchTreeNode():
def __init__(self, value):
self.value = value
self.rightChild = None
self.leftChild = None
class BinarySearchTree():
def __init__(self):
self.root = None
... |
08f39600d1317de7f62254aadd50acf0a1031177 | Wellsjian/20180826 | /xiaojian/xiaojian/first_phase/day05/exersice06.py | 255 | 3.546875 | 4 | '''
list1 = [56,36,68,44,868]
将list1中所有元素的个位存入list2中
'''
list1 = [56, 36, 68, 44, 868]
list2 = [i % 10 for i in list1]
print(list2)
str1 = "I want to study Python"
list3 = str1.split(" ")
str2 = " ".join(list3[::-1])
print(str2)
|
bd995a6e9b351d51c7148caebeb8d7b04920d6e7 | natalie-i/gh | /HT_3/7.py | 480 | 3.765625 | 4 | ''' 7. Написати функцію, яка приймає на вхід список і підраховує кількість однакових елементів у ньому.
'''
def func_1(a):
b={}
for i in a:
if i in b:
b[i]+=1
else:
b[i]=1
print('Кількість однакових елементів у списку', a,':',b)
return()
func_1(input('Введіть через пробіл дані для створення списку:').spli... |
b4d05463d0ec93ba89d70c9b5c5e1479a2f7d92e | ctyVegetableDog/leetcode | /helloLeet/2496.py | 533 | 3.90625 | 4 | # 数组中字符串的最大值
'''
一个由字母和数字组成的字符串的 值 定义如下:
如果字符串 只 包含数字,那么值为该字符串在 10 进制下的所表示的数字。
否则,值为字符串的 长度 。
给你一个字符串数组 strs ,每个字符串都只由字母和数字组成,请你返回 strs 中字符串的 最大值 。
'''
class Solution:
def maximumValue(self, strs: List[str]) -> int:
return max([int(each) if each.isdecimal() else len(each) for each in strs])
|
90e727e033abdbbb2db6b31cb446a6fc4c57ec3a | top-notch07/TwoWaits | /Task1/Python Basics/Program2.py | 202 | 3.71875 | 4 | n=5
for i in range(1,6):
for j in range(1,(2*n-1)+1):
if(j>=(n-(i-1)) and j<=(n+(i-1))):
print("*",end="")
else:
print(" ",end="")
print("\n")
|
3c03948c479cf8419b3c3df33ed11d19c8bb47b0 | qhuydtvt/C4E3 | /Assignment_Submission/minhdn/Session 7 - Assignment/3. Compute the distance between two points.py | 246 | 4.09375 | 4 | def distance():
AB = ((xA-xB)**2 + (yA-yB)**2)**0.5
return AB
xA = int(input('Enter xA: '))
yA = int(input('Enter yA: '))
xB = int(input('Enter xB: '))
yB = int(input('Enter yB: '))
print('The distance between A and B is:', distance())
|
66db7f658aa1a316ecf1c326ff1c3ab4c207989e | aliyoge/Leetcode_Python | /72.编辑距离.py | 1,981 | 3.59375 | 4 | #
# @lc app=leetcode.cn id=72 lang=python3
#
# [72] 编辑距离
#
# https://leetcode-cn.com/problems/edit-distance/description/
#
# algorithms
# Hard (56.42%)
# Likes: 562
# Dislikes: 0
# Total Accepted: 31.9K
# Total Submissions: 56.5K
# Testcase Example: '"horse"\n"ros"'
#
# 给定两个单词 word1 和 word2,计算出将 word1 转换成 word2 ... |
65ab540241d7b4cf6e0e3ac5a8c8b159e77a0a56 | ssarangi/self_driving_cars_term3 | /naive_bayes/python/PredictionExercise/prediction.py | 1,377 | 3.515625 | 4 | #!/usr/bin/env python
from classifier import GNB
import pandas as pd
def convert_to_labels(df):
new_df = pd.DataFrame(df['states'].values.tolist(),
columns=['s', 'd', 's_dot', 'd_dot'])
new_df['labels'] = df['labels']
return new_df
def person_test():
# Create an empty dataframe
data = pd.DataFrame()
... |
d37b0f773f720caf70f189a78f691486c182f313 | IMDCGP105-1819/text-adventure-Barker678 | /AoA-chapter-1.py | 17,522 | 3.65625 | 4 | import time
import random
class WEAPONS(object):
def __init__(self):
self.WEAPONS = {
'Fist': (3,8),
'stick': (4,9),
'pulse_baton': (5,10),
'alien_blaster': (5,12),
}
self.current_weapon = WEAPONS['Fist']
def add_WEAPONS(self,name, weapon):
... |
38c8c3b8a2838e5334cb49cb99c3aee1be6267a8 | gschen/where2go-python-test | /1906101007李和龙/第十周练习题/4.py | 470 | 3.875 | 4 | """
4、 找到年龄最大的人,并输出。字典“{"li":18,"wang":50,"zhang":20,"sun":22}”
"""
dict1 = {"li":18,"wang":50,"zhang":20,"sun":22}
value = list()
for i in dict1.values():
value.append(i)
# print(sorted(a)) #sorted()可以给列表排序
value = sorted(value)
b = value[3]
value1=list()
for n in dict1.values():
value1.append(n)
# prin... |
24ce29905b71d7ed3700fb0feb48f2098434b64b | Madhav-Somanath/LeetCode | /June/03-TwoCityScheduling.py | 584 | 3.734375 | 4 | """
There are 2N people a company is planning to interview. The cost of flying the i-th person to city A is costs[i][0],
and the cost of flying the i-th person to city B is costs[i][1].
Return the minimum cost to fly every person to a city such that exactly N people arrive in each city.
"""
# SOLUTION
def twoCitySch... |
cefa426c9caec673b4696f49d028b5d0bb0ade34 | millenagena/Python-Scripts | /###COMANDOS AULA21.py | 701 | 3.90625 | 4 | def linha():
print('-='*20)
def fatorial(n = 1): #Parametro opcional(caso nao seja passado valor pra n ele vale 1)
f = 1
for c in range(n, 0, -1):
f = f * c
return f
def par(n=0):
if n % 2 == 0:
return True
else:
return False
#Programa Principal
num = int(input('Dig... |
263f4ef651757abd0162494895ccd59d91bf3712 | YagelSalazar/python-actosoft | /condicionales.py | 199 | 3.953125 | 4 | calificacion = int(input('ingresa calificacion: '))
if calificacion >= 7:
print('ya pasaste')
elif calificacion >= 5 and calificacion < 7:
print('apenas y pasaste')
else:
print('ya ni vengas') |
ff444d3080fcfff25ecf05930b1fd91e2abe10e4 | danielazagorska/Dani-Python | /problems/9.4.py | 450 | 3.5625 | 4 | __author__ = 'daniela.zagorska'
import string # New Code
fname = raw_input('Enter the file name: ')
try:
fhand = open(fname)
except:
print 'File cannot be opened:', fname
exit()
counts = dict()
for line in fhand:
line = line.translate(None, string.punctuation) # New Code
line = line.lower() # New Code
wo... |
36181f87fd8857a7d8737adc8f28a3b45217acd0 | lmokto/ilovec | /traslate_py_C/example2.py | 221 | 3.828125 | 4 | n = int(raw_input("Dame un numero: "))
m = int(raw_input("Dame otro numero: "))
if n * m == 100:
print "El producto %d * %d es igual a 100" % (n, m)
else:
print "El producto %d * %d es distinto de 100" % (n, m)
|
7494cc7899d263443bc5543b319b192a6ad4f338 | jossrc/LearningPython | /D025_Working_with_CSV_Data/main.py | 523 | 3.953125 | 4 | import csv
"""
El paquete csv permite trabajar de manera sencilla los archivos de ese tipo,
ya que cuenta con métodos que permiten leerlos. El método `reader()`
retorna un objeto de tipo reader, el cual al ser trabajado en un ciclo for
obtendremos la fila como una lista de string
"""
with open("weathe... |
f67b2724be9c45306a36455b39d36216a41c6d3a | CambridgeProgrammerStudyGroup/machine-learning | /05-genetic-algorithms/python/ga/character_set.py | 367 | 3.671875 | 4 | #!/usr/bin/env python
import string
CHARACTER_SET = string.lowercase # change to string.printable for grater output variety
CHARACTER_SET_SIZE = len(CHARACTER_SET)
CHARACTER_TO_VALUE = {}
VALUE_TO_CHARACTER = {}
for index, printable_char in enumerate(CHARACTER_SET):
CHARACTER_TO_VALUE[printable_char] = index
... |
2ee46c1fc143101ea2f2f5de2a05533f3a0c99ba | fatemehKi/DMASM | /Linear_Regression.py | 1,618 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri May 10 11:39:22 2019
@author: mfatemeh
"""
import pandas as pd
dataset = pd.read_csv('weight-height.csv')
#remove unnecessary
dataset.drop('Gender', axis=1, inplace=True)
dataset.corrwith(dataset.Weight)
#we don't need the coloumns below but we need a data set hterefore w... |
af733205ee8dc3141a4060aa95ba716e91e647c5 | lelilia/supermarket_simulation | /supermarket_simulation/supermarket.py | 1,578 | 3.640625 | 4 |
from random import random
from supermarket_simulation.customer import Customer
from supermarket_simulation.cashier import Cashier
class Supermarket():
'''
manages multiple Customer instances that are currently in the market.
'''
def __init__(self, adding_prob=0.02):
self.customers = []
self.cashiers = []
s... |
a53157e08bf0c1f524eddb839da69f3fdbfd3324 | douxiaotian/Courseworks | /Foundations of Computer(I)/Homework2/角谷猜想.py | 275 | 3.625 | 4 | n = int(input())
if n == 1:
print('End')
else:
while n != 1:
m = n
if n % 2 != 0:
n = n*3 + 1
print('%d'%m+'*3+1='+'%d'%n)
else:
n = n/2
print('%d'%m+'/2='+'%d'%n)
else:
print('End')
|
cd84dabf7c50ba99499c970c3b72f0d0ab61b33b | TheInvincible26/Competitive-Programming | /Kattis/Quadrant Selection/quadrant.py | 118 | 3.546875 | 4 | x, y = map(int, (input() for _ in range(2)))
if x > 0:
print(1 if y > 0 else 4)
else:
print(2 if y > 0 else 3) |
c9040b74d27ce481c8b0b92fe35c9151f2400ce9 | imaspen/First-Term | /sdd/practicals/three/infinite_temperature_analyzer.py | 648 | 4.1875 | 4 | """
Takes any number of temperature readings and displays the highest, lowest, and average reading.
AT
11-10-2018
"""
readings = []
while True:
try:
readings.append(float(input("Enter a temperature reading or anything other than a number to finish: ")))
except ValueError:
if len(readings) == ... |
000bbb57fcc8f79ca67c0d045c15e291827f947a | aisha2006/c97 | /CountingWords.py | 306 | 4.1875 | 4 | intro = input("enter your intro: ")
print(intro)
characterCount = 0
wordCount = 1
for character in intro:
characterCount=characterCount+1
if(character==" "):
wordCount=wordCount+1
print("number of words: ")
print(wordCount)
print("number of characters: ")
print(characterCount) |
541df90e69069d2cf4fab95e37c7ce17b0a68e31 | Taoge123/OptimizedLeetcode | /LeetcodeNew/python2/LC_1246.py | 5,377 | 3.625 | 4 |
"""
https://www.youtube.com/watch?v=40plVtFcUSI
https://www.geeksforgeeks.org/minimum-steps-to-delete-a-string-after-repeated-deletion-of-palindrome-substrings/
https://leetcode.com/problems/palindrome-removal/discuss/555111/Python%3A-DFS-%2B-Memo-but-TLE
https://leetcode.com/problems/palindrome-removal/discuss/74516... |
445aaaefb5a79019b2ae72fae9c0dab9cf88d94a | adrianomucha/npd_c2_a2 | /main.py | 2,793 | 3.890625 | 4 | '''Contains shape classes and does fun things with them
hapes:
Triangle
Square
Circle
Data Atributes:
shape_type
edge_length
nanme
allies
enemies
Methods:
area perimeter updae_edge_length
add_ally
add_enemy
'''
class Square(object):
shape_type ='square'
def __init__(self, edge_length, name,allies,enemies):
... |
da4fbad6a5a2285a232cc965d5c9d95af9bf25a5 | Swati77708/assignment1.py | /assign1.py | 3,415 | 4.15625 | 4 | Assignment 1 (17/09/2020)
1) Write a program to print your name, your place of stay, your stream of study, your college name in different lines.
ANS: name="Swati gokhe"
study="MSc biotech"
place="bhopal"
clg_name="dr. dy patil biotechnology and bioinformatics"
print(name)
print(study)
print(place)
... |
34b23924c56d31bbe4480f478809abbfa11cc0eb | truongsa92/exercism_python | /bracket-push/bracket_push.py | 334 | 3.6875 | 4 | def check_brackets(strings):
match = dict(("()","{}","[]"))
queue = []
for char in strings:
if char in match:
queue.append(match[char])
elif char in match.values():
if len(queue) <= 0 or char != queue[-1]:
return False
queue.pop()
retur... |
ce0c9707e1520e9f2f8fa915858395f17649956e | dictator-x/practise_as | /algorithm/leetCode/0706_design_hashmap.py | 1,301 | 3.71875 | 4 | """
706. Design HashMap
"""
class MyHashMap:
def __init__(self):
"""
Initialize your data structure here.
"""
self.size = 1000
self.buckets = [ [] for _ in range(self.size) ]
def put(self, key: int, value: int) -> None:
"""
value will always be non-neg... |
730751146c97e5a7c7a473f7e28ce0b579cb853d | General-Mudkip/Computer-Science-y10 | /Hangman/hangmanGUI.py | 789 | 3.59375 | 4 | import tkinter as tk
from PIL import Image, ImageTk
from tkinter import font as tkFont
import random
hm_window = tk.Tk()
hm_window.title("Hangman || By Bence Redmond")
hm_window.geometry("500x300")
# Creates fonts
helv10 = tkFont.Font(family = "Helvetica", size = 10)
helv15 = tkFont.Font(family = "Helvetica", size = ... |
46308e5f1e6adc54a3d5c825b2c25a9bad9c4477 | tab0r/Week0 | /day1/test/unittests_worldcup.py | 1,686 | 3.515625 | 4 | '''Unit Tests for DS python-workshop/day1
To run the tests: go to the root directory, day1
run `make test`
'''
from __future__ import division
import unittest as unittest
from src import worldcup as worldcup
class TestWorldCup(unittest.TestCase):
def test_1_read_game_info(self):
result = worldcup.read_ga... |
07d47d406208fab17a030fd7d1fe7cc889185ff2 | guruc-134/Py_programs | /createList.py | 266 | 4.09375 | 4 | # DAY--2 Assignment
"""
create a empty list and append elements
"""
def createList():
n=int(input("enter the number of elements\n"))
print("enter %d elements"%(n))
count=0
return [int(x) for x in input().split()]
newlist=createList()
print(newlist)
|
e2809968d040be01749fc4af261985cebe2c0a5b | seanreed1111/project-euler | /1-20/001_multiples_of_3_and_5.py | 484 | 4.625 | 5 | '''
001: Multiples of 3 and 5
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
'''
target = 1000 # up to but not including
def divisible_by_three_or_five(num): #boolean
return num... |
1621adc479f5af5adeea9450877895f8ac564b4f | iwi/project_euler_python | /p05_smallest_multiple.py | 2,727 | 3.859375 | 4 | #!/usr/bin/python
# Project Euler (projecteuler.net)
#
# Problem 5: Smallest multiple
#
# 2520 is the smallest number that can be divided by each of the numbers from
# 1 to 10 without any reminder
# What is the smallest positive number that is evenly divisible by all of the
# numbers from 1 to 20?
#
from p3_largest_p... |
147fb7d73134223d2742440e854d42258fd21c2f | alexkelliott/alexkelliott.github.io | /sort/sorter.py | 1,780 | 3.5625 | 4 | # Sorting algorithims and pygame practice
import pygame
import random
pygame.init()
DATA_LENGTH = 250
screen_height = 500
screen_width = 500
main_surface = pygame.display.set_mode((screen_width, screen_height))
clock = pygame.time.Clock()
array = [] #data on the screen
height_list = [] #list containing every height ... |
30cfc7daed937508f3aa1c550fb810f7b3870ca7 | alok-kumar8765/basic_python_practicse | /python_basics/Milestone_2/cards.py | 3,998 | 4.125 | 4 | #CARD
#Suit, Rank, VALUE
from math import atan
import random
values={'Two':2,'Three':3,'Four':4,'Five':5,'Six':6,'Seven':7,'Eight':8,'Nine':9,'Ten':10,'Jack':11,'Queen':12,'King':13,'Ace':14}
suits=('Hearts','Diamonds','Spades','Clubs')
ranks=('Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Jack','Queen... |
6b2b4785befa7428aed4f82e49ab32de3354a5ff | SuhwanJang/Code_History | /Python/CSVFileSorting/algorithm/sort.py | 901 | 3.8125 | 4 | def bubble_sort(L):
loop = 0
for j in range(0, len(L)):
for i in range(0, len(L)-1):
if L[i] > L[i+1]:
temp = L[i]
L[i] = L[i+1]
L[i+1] = temp
return L
def selection_sort(L):
U = []
for i in range(0, len(L)):
U.append(L[i])... |
e8a8857386a0275cd73387cdff91c1ce0965b3d7 | Bor1s/algorithmic_toolbox | /Week 4/divideandconquer-starter-files/inversions/invs.py | 811 | 3.65625 | 4 | # Uses python3
import sys
number_of_inversions = 0
def merge_sort(li):
if len(li) < 2: return li
m = len(li) / 2
return merge(merge_sort(li[:m]), merge_sort(li[m:]))
def merge(l, r):
global number_of_inversions
result = []
i = j = 0
while i < len(l) and j < len(r):
if l[i] ... |
e2a02084e6c58a4dfaea07a12ac4d6ac12433274 | rajarahulray/fluent_python_progs | /fluent_prog_1.py | 683 | 3.875 | 4 | # -*- coding: utf-8 -*-
import collections
Card = collections.namedtuple('Card', ['rank', 'suit'])
class FrenchDeck:
ranks = [str(n) for n in range(2, 11)] + list('JQKA')
suits = 'spades diamonds clubs hearts'.split()
def __init__(self):
self._cards = [Card(rank, suit) for suit in self.suits
... |
f13596e0880e63ae3788457dab47417a3541ce72 | kgashok/algorithms | /data-structures/tree/median-updates/median-updates.py | 3,712 | 3.90625 | 4 | #!/usr/bin/env python
import sys
from queue import PriorityQueue
WRONG_MESSAGE = "Wrong!"
class HeapMultiSet(object):
def __init__(self, prioritizer):
self.prioritizer = prioritizer
self.heap = PriorityQueue()
self.counts = {}
self.length = 0
def offer(self, value):
... |
e895da0e933f8bb7398f2498345b8bb0ea173be4 | akashjnvlko/simulations-statistical-mechanics | /estimation of pi .py | 575 | 3.578125 | 4 | # lets calculate value of pi using monte - carlo simulation
import random
import math
import matplotlib.pyplot as plt
n = 2000
hits = 0
for i in range(0,n):
x = random.randint(-10000,10000)
x= x/10000
y = random.randint(-10000,10000)
y= y/10000
print(x,y)
plt.plot(x,y,color= ... |
dc6536b95565317cbeaad5f5a7ceb44d19a6bb53 | kevin98paguay/Semana-1-2-3-4-5-6-7-8-10-11-12-13-14-15 | /ejercicio15.py | 1,253 | 3.71875 | 4 | class Gente:
siguiente = 0
def __init__(self, nombre="invitado", activo=True):
# persona._siguiente= gente._siguiente+1
self.__codigo = gente._siguiente()
self.__nombre = self.__nombremayucula(nombre)
self.activo = activo
@property
def nombre(self):
return self.... |
b733775617967b5a908d232fe0482a634abd72dc | yuhangc/planning_algorithms | /environment/robots/robot2d_base.py | 3,660 | 3.53125 | 4 | import numpy as np
import matplotlib.patches as patches
class Robot2dBase(object):
"""
A base class for simple 2d robot.
"""
def __init__(self):
self.x = 0.0
self.y = 0.0
self.th = 0.0
self.vis = None
def set_pose(self, new_pose):
self.x, self.y, self.th =... |
a99b76688a27cad637548116e0e487d6ec900eba | DannyGalvan/practica_python | /dic_num.py | 391 | 3.671875 | 4 | import math
def run():
# dictionary = {}
# for i in range (1,101):
# if i % 3 != 0:
# dictionary[i] = i**3
# print(dictionary)
# dictionary = {keys:keys**3 for keys in range(1,101) if keys % 3 != 0}
dictionary = {round(math.sqrt(i),2): i for i in range (1,1000) if ke... |
67a2ed84920af4656de9da54af0b014e38c9b577 | Vitra-Veri-Bilimi-Bootcamp/yilmaz_mert_akin | /Patika/Week2- Basic Python/list_comprehension.py | 696 | 4 | 4 |
#Task
#You are given three integers and representing the dimensions of a cuboid along with an integer n.
# Print a list of all possible coordinates given by on a 3D grid where the sum of x,y,z is not equal to n.
#link= https://www.hackerrank.com/challenges/list-comprehensions/problem
if __name__ == '__main__':
... |
15dffb507af9c070694466e09665e67af803febf | ravisrhyme/CTCI | /hackerrank/trader_profit/trader_profit.py | 1,627 | 3.984375 | 4 | """
Trader Profit described in pdf document.
Time Complexity : O(nk)
Space Complexity : O(n)
This is a slight modification of famous stocks problem.
"""
__author__ = "Ravi Kiran Chadalawada"
__email__ = "rchadala@usc.edu"
__credits__ = ["Hackerrank.com","goldmansachs"]
__status__ = "Prototype"
def find_max_pro... |
424c0312853d08c883ffd2261ecc408889927838 | tom-dell/Random_Scripts | /list_to_line.py | 449 | 3.578125 | 4 | """
This script will convert a list of
1
2
3
to 1, 2, 3
Instructions
paste your list into input.txt
save input.txt
run listtoline.py
output.txt will open
replace the last "," with a "."
"""
import os
i = open("input.txt", "r")
o = open("output.txt", "w")
for line in i.readlines():
o.write (line.replace("\... |
98c81f807549b79e171e6b83f5afee79df71f6a2 | allen655915/PythonStudyNotes | /homework/homework2/bmi_com.py | 332 | 3.90625 | 4 | height = float(input('请输入您的身高(米):'))
weight = float(input('请输入您的体重(千克):'))
bmi = weight / height ** 2# 计算BMI值
print('您的BMI值为:{:.1f}'.format(bmi))
if bmi <= 18.4:
print('偏瘦')
elif bmi < 23.9:
print('正常')
elif bmi < 27.9:
print('过重')
else:
print('肥胖') |
3602c7af8730a17db61d69a46710e64adfa9daf9 | i32ropie/Informatica | /3Anio/primerCuatri/PW/Practica1/palabras.py | 809 | 3.78125 | 4 | import random
import sys
def devPalabras(fichero):
f= open(fichero, "r")
lineas = []
for linea in f:
lineas.append(linea)
return lineas
def seleccionaElemento(lista):
return random.choice(lista)
def introLetra():
a= raw_input("Introduce una unica letra: ")
while len(a)!= 1 or a.isdigit():
a= raw_input("Int... |
68eb6a732325d0463b9b3bec1587755c0ce5247d | robertoffmoura/CrackingTheCodingInterview | /Python/Chapter 02 - Linked Lists/q6.py | 781 | 3.875 | 4 | class Node:
def __init__(self, value, next):
self.value = value
self.next = next
def __len__(self):
return (1 + len(self.next)) if self.next is not None else 1
def helper(node, i):
if (i == 0):
return True, node
if (i == 1):
return True, node.next
result, last = helper(node.next, i-2)
if result == Fal... |
b71d247a126319320bfc110d9f4c3f1a1a117375 | d-dodd/civicu-pythonii-summer-2017 | /student-work/Dylan/week_2/day_1/working_with_csvs/comprehensions.py | 1,316 | 4.1875 | 4 | #please add any of the toy examples you build with comprehensions here
fish_tuple = ('blowfish', 'clownfish', 'catfish', 'octopus')
# make a list of all fish with a for loop
fish_list = []
for fish in fish_tuple:
if fish != 'octopus':
fish_list.append(fish)
# make a list of all fish using a list c... |
e69ccb33300c115615bd73e5e87132414060284e | saismaran33/Python-Lab-Assignments | /Python/Lab-Assignment-2/Source/three.py | 1,854 | 3.859375 | 4 | #Hotel Management System
class Hotel:
def __init__(self, name):
self.hname = name
self.__value=5 #private member of the class
def dis(self):
print("The name of the Hotel is: ",self.hname)
class Employee(Hotel): #Inheritance
def __init__(self,name, n,age,salary):
super().__in... |
ed5760f2d71541e0169c61e6b2a96870ecb5c3e2 | qorjiwon/LevelUp-Algorithm | /Queue/Baek_2164.py | 337 | 3.5 | 4 | """
백준 2164번 카드2
Prob https://www.acmicpc.net/problem/2164
End Day : 2020. 1. 1
"""
from collections import deque
card_num = int(input())
card_deque = deque([i for i in range(1, card_num + 1)])
while len(card_deque) != 1:
card_deque.popleft()
card_deque.rotate(-1)
print(card_deque[0])
"""
6
> ... |
965b0faab5b904876cee3582255fbea538546ef3 | yesy12/aprendendo_python | /script/aula19c.py | 263 | 3.578125 | 4 | locadora = [{
"titulo":"Star Wars",
"ano":1977,
"diretor":"George Lucas"
},
{
"titulo":"Avengers",
"ano":2012,
"diretor":"Joss Whedon"
},
{
"titulo":"Matrix",
"ano":1999,
"diretor":"Machowski"
}
]
print(locadora[0]["ano"])
print(locadora[0]["titulo"]) |
2068edb668d887c120d9173a69f886b859b38792 | Hong-Gu/Groudstation | /calculator333.py | 2,472 | 3.6875 | 4 | import sys
from tkinter import Tk, StringVar, Entry, Button
class calculator:
def __init__(self):
root = Tk()
root.title("Calculator")
self.string = StringVar()
txtDisplay = Entry(root,textvariable = self.string,insertwidth = 1 , font = "Helvetica 17 bold")
txtDisplay.g... |
600cd973d04d2efe96b3973b4dffeabe1a5e3994 | abrahamq/interviewStudy | /trees/bst.py | 2,563 | 4.03125 | 4 | class node:
def __init__(self, value):
self.left = None
self.right = None
self.value = value
#inserts under this node
def insert(self, value):
if value > self.value: #go right
if self.right == None: #need to create the node
self.right = nod... |
18773dc7fb4d6b0a1c327c80a14b2612ea2ad0d9 | levyGril/python | /Object/extend.py | 1,030 | 3.609375 | 4 | #coding:utf-8
__author__ = 'jiliwei'
# 子类的类型判断
# isinstance
# issubclass
# python可以多继承
# case
class Programer(object):
hobby = "play Computer"
def __init__(self,name,age,weight):
self.name = name #可以公开访问
self._age = age #私有属性
self.__weight = weight #部分私有属性
@classmethod
def... |
0b76039685ca1e58847114ab06f01f57e7aec65a | leejseo/NBody | /main/generate/nbody_simulate.py | 3,291 | 3.578125 | 4 | ##############################
########## CONSTANT ##########
##############################
import math
from vector import *
from graphicslib import *
G = 6.673E-11
##############################
class Graphics:
def __init__(self, xmin, xmax, ymin, ymax, bodies):
'''
Make a canvas that visual... |
6a07f681ba7de4a28bb435479e15d3ba30a68cb1 | PhysicistSouravDas/python-programs | /exponent_calculator.py | 472 | 4.46875 | 4 | def calculate_exponent(num, exp):
"""
num: int or float
exp: int
various methods to find num^exp, contrary to the standard method num**exp
"""
#By iterative loops
final = 1
for i in range(1, exp + 1):
final = final * num
return final
"""
OR
i = 1
answer = num
while i < exp:
answer... |
6dee67c448743767c7de970b823425c42fd431a2 | vandanagarg/practice_python | /learning_python/functions/functions/check_letters.py | 334 | 4 | 4 | import string
def check_letters(inp_str):
alphabet = string.ascii_lowercase
missing_letters = []
for letter in alphabet:
if letter in inp_str:
continue
else:
missing_letters.append(letter)
return missing_letters
print(check_letters("he quick brown fox jumps t... |
a0c37ef1fa9509e55b43dc57181c99e838db8702 | phmduytin/PythonStart | /Practice_QuanTriMang/Level3/25.py | 1,004 | 3.765625 | 4 | # Viết chương trình tính tần suất các từ từ input.
# Output được xuất ra sau khi đã sắp xếp theo bảng chữ cái.
# Giả sử input là: New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3.
# Thì output phải là:
# 2:2
# 3.:1
# 3?:1
# New:1
# Python:5
# Read:1
# and:1
# between:1
# choosing:1
# o... |
7e071c57a6040cd8a4063fee1b8d316440b95d01 | malaffoon/euler | /python/problems/problem34.py | 1,000 | 3.609375 | 4 | """Problem 34 - Project Euler
Digit factorials
145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
Find the sum of all numbers which are equal to the sum of the factorial of their digits.
Note: as 1! = 1 and 2! = 2 are not sums they are not included.
NOTE: algorithmically very similar to Problem 30
"""
... |
7764b68c2a577c94552ebe6adae748e1e641f511 | chirag9127/programming_puzzles | /misc/valid_parenthesis.py | 930 | 3.828125 | 4 | """
Given a string containing just the characters '(', ')', '{', '}', '[' and ']',
determine if the input string is valid.
"""
import pytest
@pytest.mark.parametrize("string,expected_output", [
("()", True),
("()[]{}", True),
("(]", False),
("([)]", False),
("(())", True),
("(", False),
])
def... |
e8d6b0584d6bc42f344a29961bc6b638fe916753 | doyouseemyname01/hello-world | /kieudulieungay2.py | 19,964 | 3.6875 | 4 | #Chuỗi trong Python
#thay đổi hoặc xóa chuỗi
#các chuỗi trong Python không thể thay đổi - chúng là cố định giống như tuple,xóa toàn bộ chuỗi bằng del:
#bạn không thể xóa hoặc loại bỏ ký tự ra khỏi chuỗi
#Nối chuỗi
#nối bằng dấu (+) hoặc dấu (*)
x = 3 * "un" + 'in'
print(x)
#output: unununin
#Hai hoặc nhi... |
cdcd91b2484949908aea2ddf280207b817e62e68 | AlvaroCC96/MediumData | /FileWriter.py | 586 | 3.859375 | 4 | import sqlite3
import pandas as pd
import sys
"""
@author Alvaro Castillo , Patricio Araya
"""
# Gets the books with rating 4.5 and stores them in a csv.
def get_books_rating45():
conn = sqlite3.connect("books.sqlite")
query = "Select * from books where rating > 4.5"
dataFrame = pd.read_sql_query(query, ... |
8019194e5bcee7422072c0db9681375fea8cfacd | rickbr6/dojo | /python_stack/python/selection_sort.py | 784 | 3.9375 | 4 | def selection_sort(arr):
current_idx = 0
# Loop through one time for each element in the array
while current_idx < len(arr)-1:
# Set the pointer index for the current pass
lowest_num_index = current_idx
lowest_num = arr[lowest_num_index]
# Check each remaining element to ... |
1bfb62f02adbafc4903ac95f71d6f3fbd4aa98fa | Mohit991/Data-Capstone-Project | /911 Calls.py | 17,024 | 3.65625 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as s
# reading the dataset
df = pd.read_csv('911.csv')
# check the info of this dataset
# print(df.info())
# check the head
# print(df.head())
# zip title timeStamp twp \
# 0 195... |
fe21b6d6d6abb9220c5857863313a6ce699edb07 | SCCroix/techdegree-project-2 | /app.py | 4,859 | 4.03125 | 4 | import constants
def add_player_to_team(player, team):
player['team'] = team
def average_height_of_team(team, players):
heights = []
for player in team_players(team, players):
heights.append(player["height"])
return sum(heights) / len(heights)
def balance_teams(teams, players):
""" Dist... |
be79400b65ef364d9cb196bfa9ebe19e286b2f9a | svponomarev/machine-learning | /python/perceptron.py | 4,370 | 3.578125 | 4 | import numpy as np
import random
"""
perceptron.py
Класс перцептрона + функция для визуализации динамики обучения (график количества ошибок от числа итераций).
"""
random.seed(42)
class Perceptron:
def __init__(self, w):
"""
Инициализация перцептрона
w - вектор весов размерностью (n + 1, 1... |
17cff97c262d5ec3259f0c204501135bab6f527b | SaiVK/Leetcode-Archive | /code/Day-of-the-Week.py | 332 | 3.546875 | 4 | import datetime
class Solution(object):
def dayOfTheWeek(self, day, month, year):
a = ['monday', 'tuesday', 'wednesday',
'thursday', 'friday', 'saturday', 'sunday']
x = datetime.datetime.strptime(
'{}-{}-{}'.format(day, month, year), '%d-%m-%Y')
return a[x.weekday... |
35aa16d189cb0456e98b20de38d674a34012dac7 | OllyNelson1/hangman.python | /Definition practice.py | 217 | 3.859375 | 4 |
def waiting():
counter = 0
while counter < 12:
print("Waiting" + count * "z")
count = count + 1
if waiting():
True
else:
False
if True:
print("Yay")
else:
print("No")
|
0f85f7cdfe69d28daa8a083f0e75c1f6f2e1dc18 | Daniel-Tilley/College | /Year3/Sem_1/CloudComp/lab2/fibo.py | 179 | 3.515625 | 4 | final = 0
first = 1
next = 2
temp = 0
while temp < 4000000:
temp = first + next
if temp%2 == 0:
print first
final = final + temp
first = next
next = temp
print final
|
c7d2901cd5cd77c29c6dc0f920c6c02985c5e200 | travisbhartwell/advent-of-code-2020 | /01/part-02.py | 1,391 | 3.8125 | 4 | import itertools
import math
def find_sum(target_sum, element_count, numbers):
all_permutations = itertools.combinations(numbers, element_count)
return set(
frozenset(permutation)
for permutation in all_permutations
if sum(permutation) == target_sum
)
def find_sum_rec(target_sum... |
1839ce7216c13770a904e0822cac9742cec0ec4f | miltonluaces/problem_solving | /TF/Ck03_LReg/c08LogisticRegression.py | 3,656 | 3.796875 | 4 | # Logistic Regression
#----------------------------------
#
# This function shows how to use Tensorflow to
# solve logistic regression.
# y = sigmoid(Ax + b)
#
# We will use the low birth weight data, specifically:
# y = 0 or 1 = low birth weight
# x = demographic and medical history data
import matplotlib.pyplot as... |
fb613e07953ca17a02bbf3aaa3c49557a4e60d95 | shaurtoonetwork/Data-Structures-Implemented-In-Python | /OOps/Method Overriding with Multiple Inheritance.py | 291 | 3.625 | 4 | class Parent1:
def show(self):
print("Inside Parent1")
class Parent2:
def display(self):
print("Inside Parent2")
class Child(Parent1,Parent2):
def show(self):
print("Inside Child")
o = Parent2()
s = Parent1()
p = Child()
p.show()
s.show()
o.display() |
8c44788e4eef0bc22e6f71a26799981c4103b8d8 | amensh07/start_python- | /homework-1.3.py | 165 | 3.640625 | 4 | print('Добрый день!Напишите любое число от 1 до 9')
n = int(input())
print(n + int(str(n) + str(n)) + int(str(n) + str(n) + str(n)))
|
b9618da92c0f119dd3601178517c1d4fcdb81742 | kdaivam/PythonPrep | /TwoSum.py | 275 | 3.6875 | 4 |
def twoSum(nums, target):
lookup = {}
for i, num in enumerate(nums):
if target-num in lookup:
print(lookup)
return [ lookup[target-num], i]
lookup[num] = i
nums = [2,7,11,12]
target = 14
print(twoSum(nums, target))
|
31204c24e28fd4e3d85f5c957a5b2b162d0da5ca | Frank-Lochtenberg/Blok-2-Praktijktoets---Frank-Lochtenberg | /Blok 2 Praktijktoets - Frank Lochtenberg.py | 26,663 | 3.65625 | 4 | # Made by Frank Lochtenberg
# Version 8
import re
import matplotlib.pyplot as plt
import tkinter
from tkinter import messagebox
def read_fasta():
""" Reads the fasta file and puts the lines from the file in a list.
:return: list of lines from the fasta file.
"""
try:
f... |
a4adc0c422c9dc8146ea378ffeeb512920d0fb4c | Jorholt/AppBio | /Ass2/dna2aa.py | 4,318 | 3.734375 | 4 | #Function that splits sequences in input file into a list
def splitFile(file):
data = ''
outdata = []
for line in file:
data += line
splitData = data.split('>')
for element in splitData:
newElement = '>' + element
outdata.append(newElement)
return outdata
#Splits input ... |
1b4a151e974ba52e8441c4d52b2b1e93a7bee750 | MatriMariem/AirBnB_clone_v2 | /models/amenity.py | 1,165 | 3.640625 | 4 | #!/usr/bin/python3
"""This is the amenity class"""
from models.base_model import BaseModel, Base
from sqlalchemy import Column, String, ForeignKey, Integer, Float, Table
from sqlalchemy.orm import relationship
place_amenity = Table('place_amenity', Base.metadata,
Column('place_id', String(60),
... |
11260700e785befa7c40d33eb1c4578735f6eed0 | wleklinskimateusz/hackerRank | /String_validators.py | 611 | 3.984375 | 4 | #!/usr/bin/python3
if __name__ == '__main__':
s = input()
output = False
for char in s:
if char.isalnum():
output = True
print(output)
output = False
for char in s:
if char.isalpha():
output = True
print(output)
output = False
for char in s:
... |
bb9485311ca24bf0b28b80d66188670316a65ec6 | CodingDojoDallas/python_march_2017 | /erica_snider/Assignments/coin_tosses.py | 592 | 3.890625 | 4 | import random
def tosses():
print "Starting the program..."
tails = 0
heads = 0
for i in range(0,5000):
toss = round(random.random())
if (toss == 0): # 0 is tails
result = "tail"
tails += 1
elif (toss == 1): # 1 is heads
result = "head"
... |
9a62d5674cde8f9b2b192178d17c42975238f5b8 | encodingl/Courseware | /C01/L07_面向对象/l01_面向对象.py | 1,054 | 3.75 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on 2017-10-26 16:40:44; @author: joinpython.com
'''
class menu:
def __init__(self,name,**materials):
self.name="m1"
self.materials=materials
class buyer:
def __init__(self,name):
self.name=name
def buy(self,menu):
... |
2739b517074ffcb0eb34334790d19bc7a7e1c52b | SteeveJose/luminarpython | /pattern/pyramidfun.py | 99 | 3.84375 | 4 | def function(num):
for i in range(1,num+1):
print(" "*(num-i)+("*"+" ")*i)
function(5) |
d54ab1f8c06278af393fb9c9945a06826b3a26c3 | frankhn/Pytorch_level_up | /linear_regression.py | 1,467 | 3.5 | 4 |
# ********************************************** #
# Training Pipeline proceducte in pytorch
# 1 ) Design model (input, output size, fowrd pass)
# 2 ) construct loss optimizer
# 3 ) Training loop
# - forward pass: copute prediction
# - backward pass: gradients
# - update weights
# *********************... |
dc3d6d6f5f195c7cace345481a6709e52c56279b | pitcany/practice | /coursera exercises/fibonacci_partial_sum.py | 657 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 23 08:57:22 2019
@author: yannik
"""
# Uses python3
import sys
def fibonacci_sum(n):
if n <= 1:
return n
previous = 0
current = 1
for _ in range((n+1)%60):
previous, current = current, (previous + current)%10
... |
ae50a7a8ce4180dc141c72981b51c46a3038d7f7 | JairGF05/python_bd_covid | /funciones.py | 8,878 | 3.734375 | 4 | from conector import *
def show_data_bases():
## executing the statement using 'execute()' method
cursor.execute("SHOW DATABASES")
## 'fetchall()' method fetches all the rows from the last executed statement
databases = cursor.fetchall() ## it returns a list of all databases present
## print... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.