blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
37c4fa9faeeb177efd561ab00cf6920d462808e5 | sainihimanshu1999/FB-List | /KclosestPointtoOrigin.py | 467 | 3.578125 | 4 | '''
we make max heap in this question and as heappusppop, inserts the element and then pop out minimum of them
'''
from heapq import *
def kclosestorigin(points,k):
heap = []
for x, y in points:
dist = -(x*x+y*y)
if len(heap)==k:
heappushpop(heap,(dist,x,y))
else:
... |
4f1b724a1d68eb3d41dc4e251e8c8a49520eb212 | DmitryGlyuz/german_numbers | /cli.py | 2,025 | 3.75 | 4 | # This file contains functions for working via the command line
import core
def try_int(incoming_str, min_int=1, max_int=999999999999999, default=None):
def print_error(message):
if default:
beginning = ''
ending = f'\nThe default value will be used: {default}'
else:
... |
952f28f65bee8cd088e68ab5f577d7d763c42cbd | ramya42043/RAMYA_VT_WORK | /Assesments_exams/python/10.py | 333 | 3.5 | 4 | import csv
import sqlite3
mydb = sqlite3.connect("FaceBase.db")
cursor = mydb.cursor()
csv_data = csv.reader(file('file.csv'))
for row in csv_data:
cursor.execute('INSERT INTO People(names, \
classes, mark )' \
'VALUES("%s", "%s", "%s")',
row)
mydb.commit()
cursor.close()
... |
558b10d57b82d5a7250cb48579403a27b16e6c38 | nvnsaharan/placement_practice | /Sorting/BubbleSort.py | 316 | 3.828125 | 4 | # We can improve it by using one extra flag. No more
# swaps indicate the completion of sorting.
def sort(A):
for i in range(len(A)):
for j in range(i, len(A) - 1):
print("A")
if A[j] > A[j + 1]:
A[j], A[j + 1] = A[j + 1], A[j]
print(A)
sort([2, 1, 5, 3])
|
2136dcdddb1a05691e4dde0adbe46ec76562bfd8 | MajetyPrashanth/My-Coding-Practice | /StringReverse.py | 186 | 4.0625 | 4 | def reverseWord(s):
str1 = s[::-1]
return str1
if __name__ == "__main__":
t = int(input())
while(t>0):
s = input()
print(reverseWord(s))
t = t-1
|
ae15e32d8377694b2a4bffdf253993dd92651b7b | Ford-z/LeetCode | /559 N 叉树的最大深度.py | 818 | 3.921875 | 4 | #给定一个 N 叉树,找到其最大深度。
#最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。
#N 叉树输入按层序遍历序列化表示,每组子节点由空值分隔(请参见示例)。
#来源:力扣(LeetCode)
#链接:https://leetcode-cn.com/problems/maximum-depth-of-n-ary-tree
#著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = va... |
5595cd11b4f77028a95b35c7cf0cb0e89cdc699b | phanminhphuong118/phanminhphuong-fundamentals-c4e22 | /Session2/homeworksession2/serious4.py | 616 | 4.0625 | 4 | for i in range(20):
print("*",end=' ')
print()
n=int(input("enter your number of stars "))
for i in range(n):
print("*",end=' ')
print()
for i in range(4):
print("x *",end=' ')
print("x")
print()
n=int(input("enter your number of stars and xs "))
for i in range(n//2):
print("x *",end=' ')
for i in range... |
6d912d2afe317248aa34b064dd0a89a86e2374bb | l3112/Guess | /guess.py | 471 | 4.0625 | 4 | import random
GuessNum = random.randint(1,40)
print('Hi - What\'s your name?')
name = input()
print('Okay,' + name + 'I\'m thinking of a number between 1 and 40')
for guessTake in range(1,20):
print('Guess!')
guess = int(input())
if guess < GuessNum:
print('Too low')
elif guess > GuessNum:
... |
af1ac24a005dcc8c77a292ac4be476c1dbcbbb50 | Torasian/CS2108Assignment2 | /deeplearning/preprocessing/extract_audio.py | 670 | 3.59375 | 4 | __author__ = "xiangwang1223@gmail.com"
# The simple implementation of obtaining the audio clip of a original video.
import moviepy.editor as mp
def getAudioClip(video_reading_path, audio_storing_path):
clip = mp.VideoFileClip(video_reading_path)
clip.audio.write_audiofile(audio_storing_path)
if __name__ ==... |
be49a1ab5b5d7d93e7329c85ed04c31f79fccee7 | cbosco/udacity | /CS258_Software_Testing/3_Random_testing/sudoku_solver.py | 14,476 | 4.03125 | 4 | # CHALLENGE PROBLEM:
#
# Use your check_sudoku function as the basis for solve_sudoku(): a
# function that takes a partially-completed Sudoku grid and replaces
# each 0 cell with an integer in the range 1..9 in such a way that the
# final grid is valid.
#
# There are many ways to cleverly solve a partially-completed S... |
8d0abdb6a0a0cb07c68d0ed99a88c69fced73780 | posguy99/comp660-fall2020 | /src/M4_variable_length_argument.py | 984 | 4.4375 | 4 | #!/usr/bin/env python3
# this is a cheat. The example from Lecture 4-5 is just:
# def print_scores(score, *scores):
# print('Test scores are:')
# print(score)
# for i in scores:
# print (i)
# print_scores(10)
# print_scores(30,50,53,92)
#
# and what you get for output is:
# Test scores are:
# 10
#... |
a81fffa378f4051eae33dffa40914ada092d1490 | AriyandaP/GitPushPull | /010.py | 3,559 | 3.71875 | 4 | import math
### LIST
# mobil=['alya','xenia',86]
# print(mobil)
# motor=[
# 'revo',
# 'mio',
# 'pulsar'
# ]
# print(motor)
# print('mobil 0 :'+mobil[0])
# print('motor 2 :'+motor[2])
# #bisa call dari belakang [-1] = [terakhir]
# print(motor[-1])
# print('mobil -2 : '+mobil[-2])
# print(mobil[:])
###
... |
85114355316d792101c2f9bc7249b736690aabe2 | PickleEric/CapstoneLabs | /Lab5/miles.py | 1,565 | 4.21875 | 4 | import sqlite3
db_url = 'miles.db' # Assumes the table miles have already been created.
"""
Before running this code, ensure that miles.db exists and contains the miles table
If not, create expected miles table with
create table miles (vehicle text, total_miles float);
"""
class MileageError(Exception):
pass
... |
fa4ded0b16291542b1c078e6c24f8c760cf70e99 | NicHagen/project_euler | /problem2.py | 1,002 | 4.34375 | 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 whose values do not exceed four million,
find the sum of the even-valued terms.
"... |
7ebce4fb2ccfd4c501aa99250021e49a0b374eae | jiji4000/AIZU_ONLINE_JUDGE_PYTHON | /Volume0/0032.py | 298 | 3.734375 | 4 | rectangle = 0
parallelogram = 0
while True:
try:
a,b,d = (int(x) for x in input().split(","))
if d * d == (a * a) + (b * b):
rectangle += 1
elif a == b:
parallelogram += 1
except EOFError:
break
print(rectangle)
print(parallelogram)
|
5ac6b777efd9e6e9fecdd3cec3691881ad7d4b12 | ssWitcher/pythonTutorial | /async/threads_queued.py | 669 | 3.515625 | 4 | import time
import random
import queue
from threading import Thread
counter = 0
counter_queue = queue.Queue()
def increment_manager():
global counter
time.sleep(random.random())
while True:
increment = counter_queue.get()
time.sleep(random.random())
counter += increment
print(f"The new value of the coun... |
3ba4878135c42bd967aa1573b84721522f2bbd53 | hheungsu/python_study | /testingProject/c22/C22_1_4_갤런리터변환.py | 340 | 3.6875 | 4 | print("------------------")
print("1.갤런을 리턴으로 변환:")
print("2.리턴을 갤런으로 변환:")
print("------------------")
inp=input("메뉴를 선택하세요 => ")
val=float(input("양을 입력하세요"))
rtn=0
if inp=='1':
rtn=val*3.785
elif inp=='2':
rtn=val/3.785
print("값은: ",rtn) |
9e86a07640241038405f0ab6ecb5a91b9e46d462 | dgpshiva/PythonScripts | /Array_ProductExceptSelf.py | 534 | 3.640625 | 4 | class Solution(object):
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
output = []
output.append(1)
for i in range(1, len(nums)):
output.append(output[i-1] * nums[i-1])
right = 1
for i in range... |
2d7e9f015852faaed561a9ba08fab49371322253 | SowmyaGayam/PYTHONPRACTISE | /TwentyFour.py | 159 | 4.125 | 4 | year=int(input("Enter a year"))
if((year%4==0 and year%100!=0) or (year%400==0)):
print(f"{year} is LEAP YEAR...")
else:
print(f"{year} is COMMON YEAR....")
|
08ae9893f31f3bab82fe19d31280e100c077b4fc | McHogardty/Command | /command/command.py | 6,382 | 3.703125 | 4 | import argparse
import collections
import inspect
from .argument import Argument
class Command(object):
"""The base class for a command-line program. It allows for a declarative-
style syntax for quickly and simply creating python programs. At the
moment it is essentially a wrapper around the argparse mo... |
86af897b469f748d87d6a0f5ddb4f693e83664cf | HBrauer/PythonProjects | /Test/Tutorial2Part3.py | 1,572 | 3.65625 | 4 | from tkinter import *
from tkinter import messagebox
from tkinter import ttk
def quit_app():
root.quit()
def show_about(event=None):
messagebox.showwarning("About", "This Awesome Program was Made in 2016")
root = Tk()
the_menu = Menu(root)
file_menu = Menu(the_menu, tearoff=0)
file_menu.add_command(label... |
058eba6695728a18307d3fb68c3171f9d3fb82eb | daftstar/learn_python | /01_MIT_Learning/week_5/lectures_and_examples/python_classes_oop.py | 531 | 4 | 4 | class Coordinate(object):
def __init__(self, x, y):
self.x = x
self.y = y
def distance(self, other):
x_diff_sq = (self.x-other.x) ** 2
y_diff_sq = (self.x-other.y) ** 2
return (x_diff_sq + y_diff_sq) ** 0.5
c = Coordinate(3, 4)
origin = Coordinate(0, 0)
print (c) ... |
5f60db25d360e9037a9b861beda65962dc60bbf9 | beidou9313/deeptest | /第一期/苏州-早安阳光/第2次作业/kehouxiti/009-3.py | 431 | 3.59375 | 4 | '''
Created on 2018年1月21日
@author: 早安阳光
'''
for i in range(100, 1000):
sum = 0
temp = i
while temp:
sum = sum + (temp%10) ** 3
temp //= 10 # 注意这里要使用地板除哦~
if sum == i:
print(i)
# 如果一个 3 位数等于其各位数字的立方和,则称这个数为水仙花数。例如:153 = 1^3 + 5^3 + 3^3
# 因此 153 就是一个水仙花数
|
eb900f5305d03ad27eb627fd89b4152fae4fe109 | skgbanga/Sandbox | /python/teaching/longest_substring_without_repeat.py | 503 | 3.75 | 4 | #!/usr/bin/env python3
def length_of_longest_substring(s):
occurs = dict()
begin, end = 0, 1
longest = 0
def length():
return end - begin - 1
for idx, c in enumerate(s):
if c in occurs:
longest = max(longest, length())
previous = occurs[c]
for ... |
ef01bb2d8a4bdc8f81d478500b41042cac805430 | xiyueyiwan/Diff-FSPM | /algorithm/ngramspan/Main.py | 1,906 | 3.5 | 4 | '''
Usage: python Main.py
Input parameters:
epsilon, n_max, l_max, dataset
'''
import sys
import getopt
from lib.NGramSet import *
def Usage():
print
print " Usage: python Main.py [arguments]"
print " where [arguments]... is a list of zero or more optional arguments"
print
print " Arg... |
ea811a5a2f908e7c9b258364d55080ade454d2dd | morrissmile/learning | /LESSION/le8.py | 1,021 | 4.03125 | 4 | # 那如果有了key,想要把dict中相對應的資料取出來應該要怎麼做呢? 作法有兩個:
#
# d[key]: 這個做法相對不安全,key如果不存在的話就會出現KeyError (如同上面我們所示範的)。
# d.get(key, default_value): 是比較安全的作法,如果key不存在的話就會回傳 default_value (下面例子中的deafult_value就是’找不到耶’)。
# ● 小練習
#
# 一年一度的世界歌王大賽來啦!身為評審的你,請輸入三個歌手的名字與成績。接下來會有三次查詢的機會,每次查詢都可以讓觀眾輸入一個名字、來查看心愛的歌手。
#
# 如果歌手不在名單中,請輸出’這個人沒參賽喲’;如果歌手... |
62b1625abca4a4bc4699e9275f19a9c1a75fc4ba | tsumo/solutions | /other/arithmetics_with_plus.py | 679 | 4.125 | 4 | #!/usr/bin/env python3
"""
Implement * - / using only +
"""
def mult(a, b):
""" Works only for positive numbers and zero """
c = 0
for i in range(b):
c += a
return c
def sub(a, b):
""" Works only when a >= b """
c = 0
while a != b:
b += 1
c += 1
return c
def d... |
eb8106a13a1ff32087c65d1ceb7cc5b4de314167 | danno-s/tarea5-imagenes | /vertex.py | 1,556 | 3.71875 | 4 | class Vertex():
'''Class that defines a vertex in the graph.
Used by Cluster to perform union-join operations.
'''
def __init__(self, coordinates):
'''Initializes this vertex with itself as its parent (and root).
----------
Parameters:
coordinates:
nu... |
bf6d13443a4d967f39af907606ba4fac5b7af880 | wesenu/MITx600 | /6001xExercises/Final Exam/Problem3.py | 328 | 4.21875 | 4 | def isPalindrome(aString):
'''
aString: a string
'''
if aString == "":
return True
return (aString[0] == aString[-1]) and isPalindrome(aString[1:-1])
aString_list = ['', 'abba', 'aboba', 'adoba', 'able', 'a']
for aString in aString_list:
print(aString + " is palindrome?", isPalindrome(a... |
344b7a93d171159eb338cbaf0ea83bb09f2346f6 | kannanpradeepkumar/my_breakout | /main.py | 1,005 | 3.515625 | 4 | import time
from turtle import Screen
from paddle import Paddle
from brick_manager import BrickManager
from ball import Ball
screen = Screen()
screen.title("breakout")
screen.setup(800, 600)
screen.bgcolor("black")
screen.tracer(0)
paddle = Paddle()
screen.listen()
screen.onkey(paddle.move_left, "Left")
screen.onkey... |
7fc724a447611d4a0c283a781ce8a44150e3e955 | nicktfranklin/IndependentClusters | /model/gridworld.py | 30,571 | 3.578125 | 4 | import copy
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import time
""" the purpose of this code is to take a subject's trial and create the relevant grid-world for that
Things needed:
1) walls
2) grid world shape
3) veridical action map
4) veridical goal location
5) context number (not ... |
c2f2704331115fb156e7d0709e70a7d3abe017a6 | sunheehnus/Python-Challenge | /level1_map.py | 828 | 3.5 | 4 | #!/usr/bin/python
import urllib2
startLower=ord("a")
startUpper=ord("A")
endLower=ord("z")
endUpper=ord("Z")
def Shiftby2(c):
if c.isalpha():
if startLower <= ord(c) <= endLower:
if ord(c)+2 > endLower:
return chr(startLower+ord(c)+2-endLower-1)
else:
... |
29bbf776c28771819d1a07b36ea813756ae7ffa0 | efitr/CS-1.3-Core-Data-Structures | /Lessons/source/search.py | 2,761 | 4.28125 | 4 | #!python
def linear_search(array, item):
"""return the first index of item in array or None if item is not found"""
# implement linear_search_iterative and linear_search_recursive below, then
# change this to call your implementation to verify it passes all tests
# return linear_search_iterative(array,... |
80c17360d194f8e8bbf433b5ac8eafa33fe0a448 | Yuvv/LeetCode | /1701-1800/1704-determine-if-string-halves-are-alike.py | 815 | 4.28125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @File : 1704-determine-if-string-halves-are-alike.py
# @Date : 2021/01/24
# @Author : Yuvv <yuvv_th@outlook.com>
class Solution:
VOWELS = set(('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'))
def halvesAreAlike(self, s: str) -> bool:
s_len = len... |
1e70e4bb65142399e597de8c3a683192b0f66832 | 13scoobie/advent-of-code | /2020/day6/main.py | 1,463 | 3.765625 | 4 | """
"""
def load_file(filename):
for row in open(filename, "r"):
yield row
def part_two():
all_questions_answered = 0
group = {}
number_of_people_in_group = 0
for line in load_file("input.txt"):
# print(line)
number_of_people_in_group += 1
for char in line.rstrip(... |
d0baa639d2444c6d255e312dfb658f6ab0c44d05 | RobertNguyen125/PY4E | /ex_09_dict/9_1_2listVsDict.py | 182 | 3.859375 | 4 | #a list
lst = list()
lst.append(21)
lst.append(183)
print(lst)
lst[0] = 23
print(lst)
#a dict
ddd = dict()
ddd['age'] = 21
ddd['course'] = 192
print(ddd)
ddd['age'] = 23
print(ddd)
|
21841441c0e6c09937c9e8f300a2b21a4586ea73 | estib-vega/search-engine | /pdf_parser.py | 1,605 | 3.921875 | 4 | """
the pdf parser opens a pdf and converts it into json
data for the string parser
for parsing we use the library PyPDF2
"""
import PyPDF2, json
# write to json file
def write_json_data(json_file, obj):
with open(json_file, 'w') as f:
json.dump(obj, f)
print('parsed to', json_file)
# return... |
8abfd2b4e9d7c9cbee6992e308a9cb1450a3fde3 | bhanuone/learning | /prime_factors.py | 410 | 3.59375 | 4 | """
program for finding prime factors of a given number
- Bhanu Prakash P
15/5/2016
"""
import math
n = 55686132
factors = []
i = 3
while n % 2 == 0:
n /= 2
factors.append(2)
max_factor = math.floor(math.sqrt(n))
while(i < max_factor):
while(n % i == 0):
factors.append(i)
n /= i
... |
4d8e6365f2cd9b69d615a106adf2ce6e69759218 | vmchenni/PythonTest | /Module-2-Assignment/Two.py | 914 | 4.40625 | 4 | # Write a program for String Formatting Operator %, which should include the following conversions:
# a.Character
# b.Signed decimal integer
# c.Octal integer
# d.Hexadecimal integer (UPPERcase letters)
# e.Floating point real number
# f.Exponential notation (with lowercase 'e')
# a.Character
mychar = 'A'
print("Hello... |
3f9073b4381b0103c5cc570a7f8244468444e238 | lindsaymarkward/cp1404_2019_1 | /week_09/inheritance.py | 459 | 3.65625 | 4 | class Thing:
def __init__(self, x):
self.x = x
def area(self):
pass
def __len__(self):
return self.x
class Other(Thing):
def __init__(self):
super().__init__(0)
pass
def area(self):
pass
t = Thing(5)
print(len(t))
# t = Thing(3)
# o = Other()
... |
4ada0b03e877f12676d5a70ee19c1c44de8a7618 | ltsuda/python-crash-course | /chapter_06/alien.py | 682 | 3.640625 | 4 | alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color'])
print(alien_0['points'])
new_points = alien_0['points']
print(f'You just earned {new_points}!')
alien_0['x_pos'] = 0
alien_0['y_pos'] = 25
print(alien_0)
alien_1 = {}
alien_1['color'] = 'green'
alien_1['points'] = 25
print(f"The alien one is {alien_1[... |
41607d4608eb462160f4e5f7621c0dc0611a8eb3 | DoseDjalmadaDunhaJunior/Estudo-de-python | /Arquivos/mapas.py | 616 | 4.21875 | 4 | '''
Mapas e dicionarios são a mesma coisa
são representados por {}
'''
receita = {'jan': 100, 'fev': 250, 'mar': 400}
print(receita)
#para interar sobre dicionarios
for chave in receita:
print(chave)
for chave in receita:
print(receita[chave])
for chave in receita:
print(f'{chave} : {receita[chave]}')... |
f29d318ac749317cee89bf568136d4ecdfcd8208 | gevanoff/Code | /python/interview/AnagramCheck.py | 1,032 | 3.890625 | 4 | def normal_string(string):
string = string.lower()
string = string.replace(" ","")
lst = list(string)
lst.sort()
ordered_string = "".join(lst)
return ordered_string
def is_anagram(s1,s2):
list1 = normal_string(s1)
list2 = normal_string(s2)
if list1 == list2:
return True... |
0f1bcb4b73b83c87547d6eb9059625a0ed33ad88 | geovanemorcatti/pesquisa-codigo | /python/matrizes multiplicaçao/main.py | 1,285 | 3.65625 | 4 | # This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
# Press the green button in the gutter to run the script.
import time
class Matriz:
def __init__(... |
c0585a5ba8dd8048eae4eb47c8b7d09033b6243c | span/taxrunner | /Score.py | 3,294 | 3.5625 | 4 | # This is the scoring class that reads and writes high scores to a file. It also keeps
# track of the players current score. This class can also be used to get printable strings
# to print the menu.
#
# Author: Daniel Kvist
# E-mail: danielkvist81@gmail.com
# Python version: 2.7
# OS: OS X
import csv
import os
import ... |
758a78b6faa0b74ea47af5369025818253a5f59b | dhananjay1438/Python | /OOP/classes/polymorphism.py | 365 | 3.734375 | 4 | class Dog:
def __init__(self, name, age):
self.age = age
self.name = name
def speak(self):
print("woof!")
class Cat:
def __init__(self, name, age):
self.name = name
self.age = age
def speak(self):
print("meow!")
alex = Dog("alex", 1)
franchis = Cat("... |
05d224042566437c95021d1fa06a6b905649130e | rikithreddy/codeinpy | /codechef/easy/solved/SPOON.py | 484 | 3.578125 | 4 | import numpy as np
t = int(input())
for _ in range(t):
r,c = map(int,input().split())
lists = []
flag = False
for _ in range(r):
str_ = input().strip()
if 'spoon' in str_.lower():
flag = True
lists.append(list(str_))
if not flag:
lists = list(np.array(lists).T)
for x in lists:
if 'spoon' in "".j... |
b9aa5698b591f29b58ade3d1e6ff903c1b39f77b | parkbyungnam/Algorithm_study | /baejoon/기초/8958.py | 675 | 3.625 | 4 | #OX퀴즈
# "OOXXOXXOOO"와 같은 OX퀴즈의 결과가 있다.
# O는 문제를 맞은 것이고, X는 문제를 틀린 것이다.
# 문제를 맞은 경우 그 문제의 점수는 그 문제까지 연속된 O의 개수가 된다.
# 예를 들어, 10번 문제의 점수는 3이 된다.
# "OOXXOXXOOO"의 점수는 1+2+0+0+1+0+0+1+2+3 = 10점이다.
# OX퀴즈의 결과가 주어졌을 때, 점수를 구하는 프로그램을 작성하시오.
for _ in range(int(input())):
sum = 0
temp = 0
arr = list(input())
fo... |
6d58a38a1a0fc305bb0bab6f92464af6f6985773 | datacarpentry/semester-biology | /code/debugging-example-exponential-growth.py | 741 | 3.59375 | 4 | """Exponential growth debugging example"""
def get_pop_size_at_t(init_pop_size, reprod_rate, time_of_sample):
n = init_pop_size
for t in range(1, time_of_sample + 1):
n_tplus1 = n + reprod_rate * n
n = n_tplus1
return n_tplus1
def doubling_time_exponential_growth(reprod_rate, init_pop_size... |
fd1c1fd381447ea25c360cf4c1d35938e234a024 | kaushiks90/PythonPrograms | /PythonPrograms/BasicPrograms/SelectionSort.py | 343 | 3.96875 | 4 | def SelectionSort(inputArray):
for x in range(0,len(inputArray)):
for y in range(x+1,len(inputArray)):
if inputArray[x]>inputArray[y]:
(inputArray[x],inputArray[y])=(inputArray[y],inputArray[x])
for x in range(0,len(inputArray)):
print(inputArray[x])
list=[7,5,1,2,3]
... |
e3cd7a2f0e54a10fc4c1dbbad7ea95947c714229 | luizfranca/project-euler | /python/p10.py | 1,122 | 4 | 4 | # Summation of primes
# def primers(n):
# primers_list = [2]
# sum_numbers = 2
# number = 2
# while number < n:
# number += 1
# for i in primers_list:
# if number % i == 0:
# break
# else:
# primers_list.append(number)
# sum_numbers += number
# return sum_numbers - number
import math
def i... |
997354a691cbd5e34a7dcdbf53643c7443f4614a | TimBossuyt/5WWIPython | /Toetsen/Toets 2/Niet-starter.py | 233 | 3.625 | 4 | getal = float(input('Geef een getal tussen 0 en 1'))
som = 0
aantal_termen = 0
breuk = 0.5
while som < getal:
som += breuk
breuk *= 0.5
aantal_termen += 1
uitvoer = '{} {}'
print(aantal_termen, som)
|
201a700f5469571105c2de239b4354c91b0ec3eb | GeoffSpielman/Hackathin_Examples | /Sprites/Sprites_From_Pygame.py | 2,800 | 3.65625 | 4 | import pygame
import random
import time
MAX_SPEED = 2.5
#mostly taken from http://programarcadegames.com/python_examples/f.php?file=sprite_collect_blocks.py
#this class is derived from the Sprite class (you get all that functionality)
class Block(pygame.sprite.Sprite):
#constructor
def __init__(self, colour, wid... |
a8648c99771988f000bf9322d2ebdc4dda3e919b | HumphreyHao/Pattern-for-python | /30_2.py | 303 | 3.671875 | 4 | #better way, read from end to head
def backspace_compare(str1, str2):
res1 = read(str1)
res2 = read(str2)
return res1== res2
def read(str1):
res1 = []
for i in str1:
if i !='#':
res1.append(i)
else:
res1.pop(len(res1)-1)
return res1
|
0888e0ca964dd851582df3c51ee44cebe81b8b43 | dijsilva/competitive-programming | /uri/python/distancia_entre_dois_pontos.py | 241 | 3.578125 | 4 | ponto_1 = str(input())
ponto_2 = str(input())
x_1, y_1 = [float(x) for x in ponto_1.split(" ")]
x_2, y_2 = [float(x) for x in ponto_2.split(" ")]
distance = (((x_2 - x_1) ** 2) + ((y_2 - y_1)** 2)) ** 0.5
print("{:.4f}".format(distance)) |
5c3d5450f0957c48d6bc5187089b96c9a4b5e9f4 | tannguyen1024/pet_hotel_server | /db.py | 1,065 | 3.546875 | 4 | # Import flask
from flask import Flask
app = Flask(__name__)
# Install psycopg2 using: pip3 install psycopg2
import psycopg2
# Establishes connection with postgres
con = psycopg2.connect(
host="localhost",
database="pet_hotel",
port = 5432)
#cursors are the vessel/command in which... |
93cfe6767fe9f56e5f4509522ce4089c1228b0a7 | LachezarKostov/SoftUni | /00_Demos/basic_conditions_and_loops/Biggest Numbeer.py | 243 | 3.765625 | 4 | a = float(input())
if a == 0:
print("zero")
else:
if abs(a) < 1:
print("small", end=" ")
elif abs(a) > 1000000:
print("large", end=" ")
if a < 0:
print("negative")
else:
print("positive")
|
6c1253773ee3a95c489b5c2af6049cae2a1cc811 | morrissmile/learning | /LESSION/LE2.py | 182 | 3.703125 | 4 | #wait user input and type is str
a=input()
print('a=', a)
print(type(a))
b=input()
c=input()
print(int(b)+int(c))
print(int(b)*int(c))
print(int(b)/int(c))
d=int(input())
print(d) |
2642d2d2cafdbf1e2dec0d1b07094418f3823f90 | kottongs/Mypythoncodes | /rolldice.py | 281 | 3.828125 | 4 | import random
min = 1
max = 6
while True:
roll = random.randint(min,max)
print(roll)
ask = input('will you like to roll again ? ').lower()
if ask == 'yes':
continue
elif ask == 'no':
break
else:
print("i dont understand you oooo")
|
63c7873142ae5ac395e7f7f951d3fe4e57a09b4c | javierp183/python | /ej2.py | 256 | 3.578125 | 4 | #!/usr/bin/python3
vector = []
max = False
pos = 0
#Cargamos el vector
for i in range(50):
vector.append(i)
for i in vector:
if max == False:
max = vector[i]
# else:
if vector[i] > max:
max = vector[i]
print(max)
|
3dfb42bafb37ec01f493ca072bfdd60243b2d9d1 | Redbird90/Whole-Genome-Visualizer | /WGV/parse_DB_line.py | 1,778 | 3.640625 | 4 | #-------------------------------------------------------------------------------
# Name: parse_DB_line
# Purpose: The purpose is stated below. The robustness is decreased with
# this module due to the strictness of the arg line's structure.
#
# Author: jkougl
#
# Created: 29/08/2014
... |
e8c90f5ff3065e648b371c255fec1d12f0b4c9ab | yangninghua/python_songsong | /Week4(56集)/day20(6集)/代码/day20_线程与协程/deadlock02.py | 1,404 | 4.03125 | 4 | # 死锁
'''
开发过程中使用线程,在线程间共享多个资源的时候,
如果两个线程分别占有一部分资源并且同时等待对方的资源,就会造成死锁。
尽管死锁很少发生,但一旦发生就会造成应用的停止响应,程序不做任何事情。
避免死锁:
解决:
1. 重构代码
2. 使用timeout参数
'''
from threading import Thread, Lock
import time
lockA = Lock()
lockB = Lock()
class MyThread(Thread):
# def __init__(self,name):
# pass
... |
7b506e357195216d45bb67e1d84e54974d97c0ed | vovapasko/Fletcher-Reeves-method | /tools.py | 6,672 | 3.671875 | 4 | import math
import numpy as np
import sympy
from sympy import diff
from function import *
import matplotlib.pyplot as plt
def draw_plot(values, min_point):
plt.plot([x[0] for x in values], [x[1] for x in values], 'b')
plt.plot(min_point[0], min_point[1], 'r-o')
plt.show()
def count_grad(point):
diff... |
ec1aa3f301b3461dab45cc46856a8e7a92ec717f | javierramon23/Python-Crash-Course | /4.- Trabajando con Listas/animals.py | 221 | 3.78125 | 4 | animals = ['leon', 'tigre', 'leopardo']
for animal in animals:
print('El {} es un felino con unas impresionantes garras.'.format(animal.title()))
print('Todos estos animales pertenecen a la familia de los Felinos.') |
2031c697a3684d2b42f2ed9098dc7f9e7365fb06 | twickatwk/codingchallenges | /Algoexpert/Arrays/threeNumberSum.py | 633 | 4 | 4 |
# Time: O(N^2) | Space: O(N)
def threeNumberSum(array, targetSum):
# Write your code here.
result = []
array.sort()
for i in range(len(array) - 2):
currentNum = array[i]
leftIdx = i + 1
rightIdx = len(array)-1
while(leftIdx < rightIdx):
currentSum = currentNum + array[leftIdx] + array[rightIdx]
... |
923444d720920c19754debbaf4257583677990cf | chloechao/coursera | /2048/merge.py | 780 | 4.03125 | 4 | #!/usr/bin/python
def merge(line):
"""
Function that merges a single row or column in 2048.
"""
new_line = []
#removed all zero item
new_line += [ item for item in line if item != 0 ]
#replaced with a tile of twice the value
index = 0
while index < len(new_line)-1:
if n... |
add64f0470ed72dedf1210d41345b9d5647ec4d4 | kawerewagaba/Andela | /Bootcamp/Binary/binary_search.py | 1,814 | 4.125 | 4 | class List(object): # creates the list to be searched by the binary search
def __init__(self, a, b):
self.length = a # number of elements in list
self.step = b # number of steps between elements
self.created_list = []
def create_list(self):
counter = 1
curren... |
2d9bb37d60f4529203df35ae04b3405d9dc999b7 | Deniston2K/Python-Assignment | /ST 1.py | 589 | 4.28125 | 4 | def c_to_f(c_temp):
farenheit=(9/5)*c_temp + 32
return farenheit
def f_to_c(f_temp):
celsius=5*(f_temp-32)/9
return celsius
temp=int(input("Enter the tempertature:"))
temp_type=str(input("Enter the temperature type in which you want to convert,type celsius or farenheit:"))
if temp_type=='celsius':... |
110ad3970a01a10537fca4015020a5c916d3ffb3 | trips-adyasha/Adyasha_25 | /third.py | 194 | 3.734375 | 4 | a=int(input("Enter a number"))
i=1
s=0
while i<a:
if a%i==0:
s+=i
print(i)
i+=1
if s==a:
print(a, "is a perfect number")
else:
print(a, "is not a perfect number") |
95cd73267f33e76aafb272c6fc36dd88e3d19ac5 | michaelsoft/PythonTest | /TestThread2.py | 1,189 | 3.828125 | 4 | from threading import Thread, Lock
from time import time, sleep
class Account(object):
def __init__(self):
self._balance = 0
self._lock = Lock()
def deposit(self, amount):
self._lock.acquire()
try:
b = self._balance + amount
sleep(1)
self... |
d8b6677f96a32075ba0fdac98fc1a793463160f4 | Genie1106/TIL | /Quiz/2448.py | 303 | 3.625 | 4 |
N = int(input())
blank = " "
star = "*"
half = int((N-1)/2)
print(half*blank+star)
for i in range(1,half+1):
a = half - i
b = int(N-2-(half/2-1)*2)
print(a*blank + star + blank*b + star)
# print(i*blank+star)
# print((i-1)*blank+star+blank*1+star)
# print((i-2)*blank+star+blank*3+star) |
72d241d8658a4d7e5363fb0bbf1e696d49b5b2b7 | VNAndrei/events-management | /Service/sortari.py | 1,757 | 3.53125 | 4 | """
Created on Jan 7, 2019
@author: Andrei
"""
def selection_sort(lista, key=lambda x: x, invers=False):
if invers == True:
for i in range(0, len(lista) - 1):
for j in range(i, len(lista)):
if key(lista[i]) < key(lista[j]):
lista[i], lista[j] = ... |
c08dd26c1a6a96dace634c1e6ad4f88d958d2a7f | GiliamD/IASD2 | /functions.py | 21,953 | 3.5625 | 4 | ########################################################################################################################
#
# File name: functions.py
# Authors: Maciej Przydatek & Giliam Datema
# Created: 15/11/2015
#
# Course: Artificial Intelligence & Decision Systems
# Assignment:... |
4909ccc34b85cb971ee3f0c190821a7f4770f17b | fnwiya/atCoder | /abc/abc012/a.py | 120 | 3.625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
a, b = map(int, input().split())
tmp = a
a = b
b = tmp
print(a + " " + b)
|
2d3b7a7036f64a2ce57eef891ac5a8be462d6404 | CCM-Balderas-Pensamiento-Comp/listas | /assignments/19SumaMatrices/src/exercise.py | 996 | 3.703125 | 4 | def suma_matrices(matriz1, matriz2):
matriz_suma=[]
for i in range(len(matriz1)):
renglon=[]
for j in range(len(matriz1[0])):
suma_valores=matriz1[i][j]+matriz2[i][j]
renglon.append(suma_valores)
matriz_suma.append(renglon)
return matriz_suma
def lee_matriz_p... |
021493547b85466ea78945f0ff428e05e4cc33e3 | meighanv/05-Python-Programming | /LABS/DICTIONARIES-SETS/dict-set-encrypted.py | 1,876 | 4.0625 | 4 | #Configuring the encryption dictionary
codebook = {}
alphanum ='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
encoded = '098765432!@$#%^&*()_+=-][}{;\'":\\`~}]abcdefghijklmnopqrstuvwxyz'
# Modified to use zip function to replace this code
# for i in range(len(alphanum)):
# key = alphanum[i]
# ... |
cb10cf8e513b7f50de9201f9e241ab48e2715b02 | michael16574/Scout | /bin/ScoutAI/CommandQueue.py | 642 | 3.5625 | 4 | from collections import deque
class CommandQueue:
def __init__(self):
self.commands = deque()
def add_command(self, command):
# Add command to the command queue at the index signaled by the user
self.commands.append(command)
#commands.insert(index+1, command)
def ... |
ab22e749f2cebadf6586ee0e1eed92c5b0f112cb | hsakabe/mysite | /python/Basic-04-Class-b.py | 2,663 | 4.125 | 4 | # 複数のインスタンス
# menu_item1, menu_item2
class MenuItem:
pass
menu_item1 = MenuItem()
menu_item1.name = 'サンドイッチ'
print(menu_item1.name)
menu_item1.price = 500
print(menu_item1.price)
# MenuItemクラスのインスタンスを生成してください
menu_item2 = MenuItem()
# menu_item2のnameに「チョコケーキ」を代入してください
menu_item2.name = 'チョコケーキ'
# menu_item2のn... |
b16ec44fc53affa9c264e1d6624385c6ec16e043 | valen280/fundamentos_programacion | /fundamentos de programación/prg_06.py | 533 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 16 15:00:00 2021
@author: Valentina Hurtado Prada
"""
# Declaracion de librerías
# Declaración de variables y/o constantes
# Entrada - Captura de datos
var_ent_distancia = int(input("Digite la distancia (m): "))
var_ent_tiempo = int(input("Digite el t... |
b8c0314e621785fa80764758452883ac50799617 | tmarice/cp | /hackerrank/contests/openbracket_delaware/because_owlery_is_too_lazy.py | 307 | 3.609375 | 4 |
def main():
address = raw_input()
try:
user, domain = address.split("@")
if len(user) == 5 and user.islower() and domain == "hogwarts.com":
print "Yes"
else:
print "No"
except:
print "No"
if __name__ == "__main__":
main()
|
944f657f869e2823e808496dbb9607c4411d7aa0 | Hygens/hackerearth_hackerrank_solutions | /python_problems_competitive/Apaxiaaaaaaaaaaaans.py | 100 | 3.546875 | 4 | l = list(input())
st = ''
for x in l:
if st=='' or st[-1]!=x: st+=x
print(st)
|
b98fe796836db9d5e1223dfaa009c7404deec110 | rolkotaki/DataAnalysisGadgets | /file_management/df_save_load_csv.py | 3,878 | 3.5625 | 4 | import pandas as pd
import numpy as np
# ********** Reading CSV into pandas dataframe
# https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html
df1 = pd.read_csv('../data/taxi.zip', skiprows=1, skip_blank_lines=True, delimiter=',', warn_bad_lines=True,
header=None, # None... |
eec6f75c30875e08bed178fd13cfa49b4638dc00 | Arno98/Python-3-Basics | /Chapter 2 (Lists and Corteges)/lists_3.py | 411 | 3.875 | 4 | names = ['Elon', 'Sherlock', 'Jim', 'Tony', 'Edmond']
for n in names:
print("\n" + n)
print(names[0])
print(names[1])
print(names[2])
print(names[3])
print(names[4])
for n in names:
print("You are my friend " + n.title())
machines = ['Porshe', 'Bugatti', 'Audi']
print("I want to buy a " + machines[0... |
7e0e32800ff9c843ce37a4cc9f58de63839e5b4c | CUCEI20B/zodiaco-IvanBM18 | /main.py | 2,598 | 4.09375 | 4 | #Captura y validacion de dia
dia = int(input("Ingresa tu dia de nacimiento: "))
while (dia < 1 or dia > 31) :
print("Error: Ingresa un dia valido")
dia = int(input("Ingresa tu dia de nacimiento: "))
#Captura y validacion de mes
mes = int(input("Ingresa el numero de tu mes de nacimiento: "))
while (mes < 1 or me... |
6e6dd4df5efb9e12e614b2808ca2e86cc0d34c2c | Mause/PerthCodeDojo | /kata2/haskell_reimp/src/checkout.py | 1,796 | 3.546875 | 4 | import math
class Checkout(object):
def __init__(self):
self.items = []
self.discounts = []
def add_to_cart(self, item):
assert isinstance(item, Item)
self.items.append(item)
def add_multiple(self, items):
self.items.extend(items)
def calculate_total(self) ->... |
9442493104862030dc519bdb81c6639911c69a70 | Demonorium/clientProgramm | /MainClient/Log.py | 1,326 | 3.53125 | 4 | from datetime import datetime
class Log:
'''Класс записывает в указанный при создании файл при вызове метода write.
write ведёт себя точно также, как print, но имеет дополнительные опции'''
def __init__(self, fname):
self.fname = fname
def write(self, *args, console = True, time = True... |
dad5a96b6055d25eabf08a56a72d64953306df53 | daniel-reich/turbo-robot | /vq3x6QP77d7Qwe8be_1.py | 1,355 | 4.28125 | 4 | """
Create a function that takes an array of numbers, and returns the size of the
biggest square patch of odd numbers. See examples for a clearer picture.
### Examples
odd_square_patch([
[1, 2, 4, 9],
[4, 5, 5, 7],
[3, 6, 1, 7]
]) ➞ 2
# The 2x2 square at the lower right
# ([5... |
c2513c34453f3c98b15c3fad1960fef1a7280f1e | makcmoscow/geek_university | /homework_1_3_easy.py | 1,548 | 4.125 | 4 | # Постарайтесь использовать то, что мы прошли на уроке при решении этого ДЗ,
# вспомните про zip(), map(), lambda, посмотрите где лучше с ними, а где они излишни!
# Задание - 1
# Создайте функцию, принимающую на вход Имя, возраст и город проживания человека
# Функция должна возвращать строку вида "Василий, 21 год(а), ... |
fd29891fc2709320db53b05ad3b900f4c3412fa8 | billm79/COOP2018 | /Chapter05/U05_Ex08_CaesarCipher.py | 3,851 | 4.15625 | 4 | # U05_Ex08_CaesarCipher.py
#
# Author: Bill Montana
# Course: Coding for OOP
# Section: A3
# Date: 11 Oct 2017
# IDE: PyCharm Community Edition
#
# Assignment Info
# Exercise: 8
# Source: Python Programming
# Chapter: 5
#
# Program Description
# Encode and decode Caesar ciphers
#
# Algorithm (pseudo... |
20e4a0f8cf6e6a5d8ac53a3c4c10b1e65036a7f8 | cabaude/helloword | /graphe.py | 917 | 3.6875 | 4 | class Graphe:
def __init__(self,nom):
self.nom = nom
self.noeuds = []
self.arrete = []
def ajouterNoeud(self,noeud):
self.noeuds.append(noeud)
def ajouterArrete(self,noeud1,noeud2):
self.arrete.append(noeud1 + ':' + noeud2)
def isNoeudConnecte(self,noeud1,noeu... |
f9548d58a96c5f17d492bea25928fdc623561526 | Fischer-L/Puzzles | /House_Robber_III/solution.py | 647 | 3.65625 | 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 rob(self, root):
"""
:type root: TreeNode
:rtype: int
"""
money = self._dfs(root)
ret... |
6a27376a92143ce9409de6f5d86bf3c5d547180c | szhongren/leetcode | /19/main.py | 1,147 | 3.71875 | 4 | """
Given a linked list, remove the nth node from the end of list and return its head.
"""
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type hea... |
d002bcec85d96ea158e29c05e33a6e563c8e6702 | heiyanbin/lintcode | /141_sqrtx/sqrtx.py | 531 | 3.984375 | 4 | # coding:utf-8
'''
@Copyright:LintCode
@Author: heiyanbin
@Problem: http://www.lintcode.com/problem/sqrtx
@Language: Python
@Datetime: 14-12-12 00:09
'''
class Solution:
"""
@param x: An integer
@return: The sqrt of x
"""
def sqrt(self, x):
# write your code here
a, b= 1, x
... |
16115f25e2671ef55a2900d1ab1fed16c9038384 | DPICART/python-scripts | /turtle-fun.py | 2,541 | 3.890625 | 4 | import turtle # https://docs.python.org/3.3/library/turtle.html
# Nous allons créer un logiciel permettant de dessiner un labyrinthe depuis une liste
# Observez le plateau ci-dessous
# On indique les "passages"
plateau = [
[
"HautDroite", "GaucheDroite", "GaucheBas"
],
[
"BasDroite", "Gauc... |
3ba833c419030d091868978d70f107b2c31aa005 | Mayur-Debu/Object-Oriented-programming- | /Minor Project #1.py | 2,711 | 4 | 4 | """
MINOR PROJECT NO: 1
This minor project is a library management system based on object oriented programming concepts.
"""
class Library(object):
bookDictionary={}
books=["C Programming","C++ Programming","Java Programming","Python Programming","Javascript Programming"]
def __init__(self,name):... |
b67b72b83f75056a6052193aeb394cdda0b320fa | sv456/algorithmic_toolbox | /week2/fibonacci.py | 261 | 3.703125 | 4 | #python2
def fib_fast(n):
a=list()
a.append(0)
a.append(1)
if n<=1:
return n
i=2
while i<=n:
a.append(a[i-1]+a[i-2])
i+=1
return a[n]
if __name__=='__main__':
num=int(raw_input())
print fib_fast(num)
|
c8949be627b281daeb4b88934026f9f43a05adb7 | klimkiewicz/szkolenie | /test_passwords.py | 1,862 | 3.8125 | 4 | import unittest
from passwords import get_password_for_database, check_password
class PasswordsTestCase(unittest.TestCase):
MAX_PASSWORD_LENGTH = 100
def testPasswordLengthOK(self):
"Passwords stored in DB need to be at most 100 chars long."
password_for_db = get_password_for_database('Test'... |
4d9433dcc2262ac09f08b1390a175305bc293aaf | vijayvenkatesh1986/Python-Practice | /Divisionwithout.py | 560 | 3.921875 | 4 | def division(numerator,denominator):
neg=0
quotient=0
if numerator<0:
numerator=-numerator
neg=1
if denominator<0:
denominator=-denominator
neg=0
if denominator<0:
denominator=-denominator
neg=1
if numerator<0:
... |
2ea1d34ff0c9aa14dba7bbe2a998e7a48650c47e | daniel-reich/turbo-robot | /jT7PY2yTWTuxcqpJe_10.py | 498 | 4.125 | 4 | """
Given a matrix of m * n elements (m rows, n columns), return all elements of
the matrix in spiral order.
### Examples
spiral_order([
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]) ➞ [1, 2, 3, 6, 9, 8, 7, 4, 5]
spiral_order([
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12... |
f554fbefd0024b64051c7ab50eea4fd859936409 | DeepDeepLearning21/PythonProgramming | /program4_LinearModel.py | 9,350 | 4.21875 | 4 |
# define a list
list_ls = [6, 7, 8, 10]
# print the firsr item in the list
print(list_ls[0])
# print the last item in the list
print(list_ls[-1])
# print the first, the second and the third items
print(list_ls[0:3])
# create a 2D list
vec1 = [1, 2, 3]
vec2 = [3, 4, 5]
list_ls2 = [vec1, vec2]
print(list_ls2[0])... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.