blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
8ef8684758adf0c7047dd92dd1eaa34f9cb28ed5 | yehongyu/acode | /2019/dynamic_programming/minimum_swaps_to_make_sequences_increasing_1016.py | 895 | 3.546875 | 4 | class Solution:
"""
@param A: an array
@param B: an array
@return: the minimum number of swaps to make both sequences strictly increasing
"""
def minSwap(self, A, B):
# Write your code here
if len(A) != len(B): return -1
n = len(A)
swap = [n] * n
swap[0] =... |
c1867ca930794c75c86d0395e61e6329364e9d15 | jeimynoriega/uip-prog3 | /Laboratorios/quiz2.py | 605 | 3.78125 | 4 | #quiz2
descuento1 = 0.35
descuento2 = 0.20
descuento3 = 0.10
comprador = 0
while comprador < 5 ;
monto = int(int(input("ingresar monto:"))
comprador +=1
if (monto >= 500):
subtotal1 = monto * descuento1
total = monto - subtotal1
print("el total es {0}:".format(total))
elif (monto < 500 and monto >= 200):
sub... |
9ecc8f8e161737fac1fa37a78b2c374641999be8 | mreishus/aoc | /2021/python2021/aoc/day22_failed2.py | 8,945 | 4.03125 | 4 | #!/usr/bin/env python
"""
Advent Of Code 2021 Day 22
https://adventofcode.com/2021/day/22
"""
from typing import List
import re
import math
from copy import deepcopy
def ints(s: str) -> List[int]:
return list(map(int, re.findall(r"(?:(?<!\d)-)?\d+", s)))
def parse(filename: str):
with open(filename) as file... |
7f57b2e7530c7722fa63160d95b47ecbad160866 | imaimon1/Learn-Python-the-Hard-Way | /ex42.py | 763 | 3.71875 | 4 | class Animal(object):
pass
##is a
class Dog(Animal):
def __init__(self,name):
## has a
self.name = name
class Cat(Animal):
def __init__(self, name):
##has a
self.name = name
class Person(object):
def __init__(self,name):
##has a
self.name = name
self.pet= None
##isa
c... |
01e2a37f2f681d7892df5b7311704530b33a5a78 | Basilio0505/CS_303E-Assignments | /SelectionSort.py | 361 | 3.65625 | 4 | def selectSort(alist):
for x in range(0,len(alist)):
temp = alist[x]
for y in range(x,len(alist)):
if temp > alist[y]:
temp = alist[y]
alist[y] = alist[x]
alist[x] = temp
def main():
mylist = [24,6,54,45,67,82,10]
select... |
b8c09a24728d84ec2e2fbbfc19abbdc3f1284db9 | ShreeyaVK/Python_scripts | /random_numbers.py | 1,334 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Aug 25 12:28:24 2017
@author: Sadhna Kathuria
"""
## generate random numbers
import numpy as np
#random number between 1 and 100
print np.random.randint(1,100)
#random number between 0 and 1
print np.random.random()
#function for generating multiple random numbers
def r... |
7c3b34189aebe769f5bfa6880d0326a7db5702b9 | skoolofcode/SKoolOfCode | /TrailBlazers/Prisha/Practice/httyd.py | 18,241 | 3.671875 | 4 | twoOne = 10
TwoTwo = 11
TwoThree=12
TwoFour = 13
TwoFive = 14
TwoSix = 15
TwoSeven = 16
TwoOneOne =17
TwoOneTwo = 18
TwoTwoOne = 19
TwoTwoTwo = 20
TwoTwoThree = 21
TwoThreeOne = 22
TwoThreeTwo = 23
TwoThreeThree=24
TwoThreeFour=25
TwoFourOne = 26
TwoFourTwo = 27
TwoFiveOne=28
TwoFiveTwo=29
TwoSixOne=30
TwoSixTwo = 31
T... |
d24d2024851e7c8e34cff86db00bbfec15851c18 | doaa-altarawy/molssi_api_flask | /tests/pyMongo_test.py | 1,759 | 3.8125 | 4 | from pymongo import MongoClient
client = MongoClient('localhost', 27017) # defaults
# same as
client = MongoClient('mongodb://localhost:27017')
# By specifying this database name and saving data to it,
# you create the database automatically.
db = client.pymongo_test
# or the dictionary-like access
#db = client['pymon... |
7c8a5362d886ca893627d5b59a7075a0affb7e3c | piggymei/mycode | /nasa01/downloadimage.py | 843 | 3.515625 | 4 | import requests
import wget
datepic = input("what date do you like for the image? (YYYY-MM-DD) ")
resolution = input("would you like the image in High definition or standard definition?(High or Standard) ").lower()
API_KEY = "8EWWTP0IkiMrdVGucP6AOEMJsviwqjbPzHZ3zqLr"
url = "https://api.nasa.gov/planetary/apod?date=" ... |
88307d6148e43e0bc82e8746409a55ad2e774061 | JeevanMahesha/python_program | /Data_Structure/LinkedList/linked_list.py | 662 | 3.796875 | 4 | class Node:
def __init__(self,val=None):
self.DataValue = val
self.NextValue = None
class LinkedList():
def __init__(self):
self.HeadValue = None
def listprint(self):
printval = self.HeadValue
while printval is not None:
print (printv... |
bc8321aa33f1be0a2ac129cb69816be66a1e8ee3 | eden-r/iskills-python | /pig_latin_translator.py | 994 | 4.125 | 4 | def pigLatinTranslator(word):
"""
This function takes a word as its input and returns a version of the word
translated into Pig Latin. It does not work on words that contain numbers
or are only one character long.
"""
vowels = "aeiouAEIOU"
word = str(word)
if not word.isalpha():
... |
46d13e41b151a2edbf2f49043caf11eacd1f28af | shubhamthorat07/Python-Dictionaries | /dict.py | 526 | 4.03125 | 4 | d = {"Movie" : "Titanic", "Genre" : "Romance", "Hours": "210mins", "Budget": "$200m"}
print(d)
d["Actor"] = "Leonardo Di Caprio"
print(d)
d["Actress"] = "Kate Winslet"
print(d)
print(d["Movie"])
print(d["Budget"])
print(d.get("Genre"))
print(d.get("Movie"))
for x in d... |
67c5f72068ca3a2e0059298c95cf7e6c757d74df | roysegal11/Python | /While/Grades.py | 218 | 3.8125 | 4 | grade = int(input("Input grade: "))
sum = 0
count = 0
while grade >= 0 and grade <= 100:
if grade >= 60:
sum = sum + grade
count += 1
grade = int(input("Input grade: "))
print(count)
print (sum) |
8ace3168e1d5c94791cc36202e67f522186fe4bd | atenudel/483hw | /mycode.py | 1,491 | 3.71875 | 4 | #Art Tenorio
#CISC483
import csv
import numpy as np
import pandas as pd
#simply edit the path to load the file at your convenience...
df = pd.read_csv("/home/art/Downloads/data.csv",
skiprows=0)
#dataset attr names would mess up without this
df.columns=df.columns.str.strip()
#had to rename the class attribute, since cl... |
93d34f8297ab344863b05c40ada896259e8f1b13 | sankhaMukherjee/mlPipes1 | /kfpReusableComponents/readData/program.py | 780 | 3.578125 | 4 | import os
def main():
pwd = os.path.dirname(os.path.realpath(__file__))
print(f'The current folder = {pwd}\n')
print('+---------------------------------')
print('| Folder Contents')
print('+---------------------------------')
files = os.listdir('.')
for f in files:
if os.path.isdi... |
f328ed3fdef0fc497d1fc148b6e6135ecd87e7c9 | Offliners/Python_Practice | /code/216.py | 346 | 4.03125 | 4 | # is the number an armstrong number?
# example: 153 is.
# 153 = 1^3 + 5^3 + 3^3
# 3 is the length of the number
def is_armstrong(n):
pwr = len(str(n))
s = sum([int(x) ** pwr for x in str(n)])
return s == n
print(is_armstrong(153)) # Yes
print(is_armstrong(154)) # No
print(is_armstrong(1634)) # Yes
# Outp... |
54adc6a99bb40da64d2c93f4b3587a25c6e49c3d | Jiangyiyi1028/Project | /Animal.py | 1,370 | 4.09375 | 4 | # _*_ coding: utf-8 _*_
# @Time : 2021/1/23 0023 下午 16:55
# @Author : jiangyiyi
# 比如创建一个类(Animal)【动物类】,类里有属性(名称,颜色,年龄,性别),类方法(会叫,会跑)
# 创建子类【猫】,继承【动物类】,
# 重写父类的__init__方法,继承父类的属性,
# 添加一个新的属性,毛发 = 短毛,
# 添加一个新的方法, 会捉老鼠,
# 重写父类的【会叫】的方法,改成【喵喵叫】
class Animal:
# 属性
name = 'Alice'
colour = 'orange'
age = 3
... |
388cc665bc3470825ba2d5621b3161e084a28667 | othaderek/DnA | /matrixElementSum.py | 796 | 3.703125 | 4 | def matrixElementsSum(matrix):
# loop over each array simlutaneously
# add numbers not underneath a zero
# as soon as I see a zero i rule out the rest everything underneath it
matrixSum = 0
l_to_r = 0
t_to_b = 0
while l_to_r < len(matrix[0]):
while t_to_b < len(matrix):
p... |
5a2c9c0d1985366856532d660db67b50f4a478e0 | nisholics/Practical-Python | /p2_1.py | 1,596 | 3.984375 | 4 | '''
2.1. Create Regular Expressions that
a) Recognize following strings bit, but, bat, hit, hat or hut
b) Match any pair of words separated by a single space, that is, first and last names.
c) Match any word and single letter separated by a comma and single space,
as in last name, first initial.
d) Match simple ... |
50d2f0d83d8165dd5fc49235e2b07f5e47550245 | horkheimer8/PGE_projects_CVUT | /1_Robot_Mining_Simulation/PGE_first_assignment.py | 870 | 3.734375 | 4 | # [7 1 3 2 5 2 4 6 1]
# Given:
# s: start position:6
# d: direction of movement 0... left 1...right
# n: num of visited positions in the move.
# Goal: total sum of all visited values in one move.
# More commands of the same format
def moveValueGetSum(s, d, n):
arr = [7, 1, 3, 2, 5, 2, 4, 6, 1]
sum = 0... |
eab1bba365d6375e93c055fd88d1a2879de7085f | ruchi2ch/Python-Programming-Assignment | /week 2/2.4.py | 571 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 4 19:20:57 2020
@author: HP FOLIO 9480M
"""
'''Problem 2_4:
random.random() generates pseudo-random real numbers between 0 and 1. Write a program to use only random.random()
to generate a list of random reals between 30 and 35.'''
import random
def problem2_4()... |
e6ec18b3cc01e05179775495cb94863bc09be4be | crazcalm/problem_solving_with_algorithms_and_data_structures_using_python | /Chapter_1/Fraction.py | 4,301 | 3.78125 | 4 | class Fraction:
"""
A module to deal with basic fractions.
"""
def __init__(self, top, bottom = 1):
common = gcd(top, bottom)
self.num = top //common
self.den = bottom //common
def __str__(self):
return str(self.num) + "/" + str(self.den)
def __repr__(self):
return self.__str__()
def sho... |
4d3c6fb718eec67017d5782f7562a4a16be69695 | hyunjun/practice | /python/problem-string/shortest_distance_to_a_character.py | 1,771 | 3.53125 | 4 | # https://leetcode.com/problems/shortest-distance-to-a-character
# https://leetcode.com/problems/shortest-distance-to-a-character/solution
from typing import List
class Solution:
# 78.70%
def shortestToChar(self, S, C):
cIdx, res = -1, []
for i, c in enumerate(S):
if C == ... |
d7e7c7d249b22fd0bdb29139bb768b48ef933d99 | des-learning/struktur-data | /src/09/binary.py | 2,039 | 3.5625 | 4 | class Node:
def __init__(self, value, parent=None):
self.parent = parent
self.value = value
self.left = None
self.right = None
def addLeft(self, value):
if self.left is None:
node = Node(value, self)
self.left = node
else:
self... |
09330f672f835b2b7e17232529d59caee1aa60ae | szhmery/algorithms | /sorting/ShellSort.py | 474 | 3.6875 | 4 | # https://www.cnblogs.com/chengxiao/p/6104371.html
def shellSort(arr):
n = len(arr)
gap = int(n / 2)
while gap > 0:
for i in range(gap, n):
temp = arr[i]
j = i
while j >= gap and arr[j - gap] > temp:
arr[j] = arr[j - gap]
j -= gap... |
4868efae039403027acc5b814ed76480a7cedfb7 | ranvsin2/PythonBasics | /for.py | 424 | 4.0625 | 4 | #range(start,stop,step)
#step:print every no after step.
for i in range(1,6,2):
print(i)
fish=['rohu','katla','shark','mangur']
for f in fish:
print(f)
for item in range(len(fish)):
fish.append('jhinga')
print(fish)
sammy='Mangur'
for letter in sammy:
print (letter)
fish_dict={'name':'rohu','color':... |
a78666a57c4e34b35e76b64ef19f884ce6a5a6db | vukovicofficial/Programsko-inzenjerstvo- | /vjezba_1/Razlomak.py | 3,924 | 3.6875 | 4 | '''
Može se lakše uraditi preko ugrađene biblioteke 'fractions'
'''
'''
Stvori datoteku razlomak.py
Napravi klasu Razlomak koja će imati dva atributa brojnik i nazivnik.
Brojnik i nazivnik se šalju kao argumenti tijekom inicijalizacije klase
Napravi svojstva za čitanje i pisanje brojnika i nazivnika.
Napravi metodu s... |
1c41e1a104f733e8d0a8667fe02963be3618458e | MED-B/DiabitesDetectorPY | /main.py | 2,712 | 3.671875 | 4 | #Description : this is a program that detect whether someone has diabites with ML and Python
#Import libraries
import pandas as pd
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from PIL import Image
import streamlit a... |
1ec0c74519b72a68da6a807720040a6cdca893d3 | AnishHota/Coding-Problems | /Palindrome Permutation.py | 346 | 3.9375 | 4 | string = input()
count=0
for i in string:
if string.count(i.lower())%2!=0 and i!=' ':
count+=1
length = len([1 for i in string if i!=' '])
if length%2!=0 and count==1:
print('Permutation of a Palindrome')
elif length%2==0 and count==0:
print('Permutation of a Palindrome')
else:
print('Not a Perm... |
93843b8294ba36836e6e0f0330941ddc068e0efb | lucasbbs/APC-2020.2 | /dicionario/questao4/main.py | 292 | 3.78125 | 4 | string = input()
def histogram(s):
d = dict()
for c in s:
d[c] = d.get(c,0)+1
return d
print(histogram(string))
def histogram(s):
d = dict()
for c in s:
if c not in d:
d[c] = 1
else:
d[c] += 1
return d
a = input()
print(histogram(a))
|
a2473012b612bcc8accb855637d8f3662d158b24 | tony-andreev94/Python-Fundamentals | /02. Lists/03. Smallest number v2.py | 538 | 4.28125 | 4 | # Write a program to read a list of integers, finds the smallest item and prints it.
# This is another solution, instead to search for the smallest number the list is sorted and the first item is printed
def list_sort_func(input_list):
sorted_list = sorted(input_list)
return sorted_list[0]
if __name__ == "... |
8644f104a40f2b5f748836f58442eb9d47a514f4 | cesarfois/Estudo_Livro_python | /#Livro_Introd-Prog-Python/cap-6/Listagem 6.7 - Apresentação de numeros.py | 537 | 3.65625 | 4 | print('=' * 72)
print('{:=^72}'.format(' Listagem 6.7 '))
print('{:=^72}'.format(' By César J. Fois '))
print('=' * 72)
print('{0:=^72}'.format(' Listagem 6.7 - Apresentação de Numeros'))
print('=' * 72)
print('')
numeros = [0, 0, 0, 0, 0]
x = 0
while x < 5:
numeros[x] = float(input('Numero %d: ' % ... |
6c15e5be19d0549994d1ae7e060553f83b40792c | kiran-kotresh/Python-code | /test_python_dummy.py | 173 | 3.6875 | 4 | #
# result = [x ** y for x in [10, 20, 30] for y in [2, 3, 4]]
# print(result)
from functools import reduce
result = reduce((lambda x, y: x * y), [1, 2, 3])
print(result)
|
fb8339c7c5d619e79d090c53a6d7e3eb63e27ce3 | Dmitry892/Py111-Arefev | /Tasks/b2_Taylor.py | 1,028 | 3.828125 | 4 | """
Taylor series
"""
from typing import Union
def factorial(fac: int) -> int:
factorial_ = 1
for f in range(fac, 0, -1):
factorial_ *= f
return factorial_
def ex(x: Union[int, float]) -> float:
"""
Calculate value of e^x with Taylor series
:param x: x value
:return: e^x value
... |
596d94f42e2a47f2c2bd70afb1c6da243b4b3a61 | invintrar/CS50WP | /Python/name.py | 51 | 3.5 | 4 | name = input("Name: ")
print("His name is: ", name) |
73179cbe10f4a6c658238bb249c41d6efcff2ab9 | wongyee11/PythonLearning | /Projectexception/exceptMsg.py | 487 | 3.6875 | 4 | #!/usr/bin/env.python
# coding=utf-8
print("只要有一行出现了异常就会'print()'异常信息,但是当打印异常时,我们并不能准确地知道到底是哪一行代码引起了异常")
print("我们在'BaseException'后面定义了'msg'变量用于接受异常信息,并通过'print'将其打印出来")
print("此处的写法在'Python2'里用逗号','代替'as'")
try:
open("abc.txt", 'r')
print(hello)
except BaseException as msg:
print(msg) |
578ffac6c8072432b1098cee56344a11525a4dd9 | tayloradam1999/AirBnB_clone | /tests/test_models/test_place.py | 2,607 | 3.703125 | 4 | #!/usr/bin/python3
"""
Unit test module for Place class
"""
import unittest
import os
from models.engine.file_storage import FileStorage
from datetime import datetime
from models.place import Place
place1 = Place()
class TestPlace(unittest.TestCase):
""" Class for Place tests """
def test_id(self):
... |
f787cfa52ecb32d1fd508a63c34c0bb64ccf4e33 | asomodi/PYTHON_single_tasks | /hangman_game.py | 820 | 4 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[2]:
word="GUESS"
guessed=0
current_guess=["_"]*len(word)
count=0
print("HANGMAN Experience :-)\nThe word has " + str(len(word)) + "letters.\nGOOD LUCK\n\n")
print(("_"+" ")*len(word))
while count <6:
guess=input("\nGuess your letter: ").upper()
for... |
863055d42f0ab5eeba5d3c2bde9ea14277f436d0 | Aigerimmsadir/BFDjango | /week1/CodeingBat/max_end3.py | 146 | 3.796875 | 4 | def max_end3(nums):
maxx = max(nums)
nums[0]=maxx
nums[1]=maxx
nums[2]=maxx
return nums
print(max_end3(input().split())) |
96140dfc5b32b5e251fa9c17e62b61552b111728 | shatuji/python | /zipAndLambdaAndMap.py | 324 | 3.953125 | 4 | #zip lambda map
a = [1,324,32]
b = [12,34,2]
obj = zip(a,b)
#print(list(obj))
#for u in list(obj):
#s print(u)
#for i , j in obj:
# print(i*2,j*3)
def function1(x , y):
return x+y
#this is just liking invoked function that get it return data
result_map = map(function1,[2,32],[3,23])
print(list(result_ma... |
6aadbce268cc472e41b8ee0a2a562a9071778a42 | leeejihyun/Grade-Management | /main.py | 5,401 | 3.8125 | 4 | def getaverage(student):
average = (student['Midterm'] + student['Final'])/2
average = round(average,1)
return average
def getgrade(student):
average = student['Average']
if average >= 90:
grade = 'A'
elif average >= 80:
grade = 'B'
elif average >= 70:
grade = 'C'
... |
32a3b85370beee49dd86b481fa66e33909f70fe7 | adikabintang/kolor-di-dinding | /programming/basics/crackingthecodinginterview/recursion_and_memoization/2_robot_in_a_grid.py | 1,342 | 3.515625 | 4 | # class Point:
# def __init__(self, x, y):
# self.x = x
# self.y = y
class Solution:
def __init__(self):
self.paths = []
self.__forbidden_points = set([(2, 2)])
def is_offlimit(self, row, column) -> bool:
return (row, column) in self.__forbidden_points
def ... |
cc9118229ede1bd0379c4a074bc4e7f941d6c379 | liulizhou/leetcode | /utils/sort.py | 2,297 | 3.671875 | 4 | import random
# sort
class Solution:
def heap_sort_pos(self, nums):
def max_heap(nums, root, size):
p = root
while(p * 2 + 1 < size):
l, r = p * 2 + 1, p * 2 + 2
if r < size and nums[l] < nums[r]:
nex = r
else:
... |
5109ceb6663fa1be9edd06ad5604eac8b5d9dbc4 | leomcp/Algorithms | /Python/Data Structure/Trees/tree_identical.py | 1,425 | 3.9375 | 4 |
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
class BSTree:
def __init__(self):
self.root = None
def get_root(self):
if self.root:
return self.root
def insert(self, node_data):
if self.root is None:
self.root = Node(node_data)
else:
self._inse... |
a73815c6b1000d77172a3cbb8f3820a36e44a70a | wzwhit/leetcode | /剑指offer/面20表示数值的字符串.py | 396 | 3.875 | 4 | # -*- coding:utf-8 -*-
import sys
class Solution:
# s字符串
def isNumeric(self, s):
# write code here
try:
p = float(s)
return True
except:
return False
while True:
try:
line = sys.stdin.readline().strip()
if not line:
br... |
b2a6d14a03925db180cf96cb3c870657b074cf84 | nindalf/euler | /25-fibonacci.py | 788 | 4.0625 | 4 | #!/usr/bin/env python3
"""
Searched online for a better way of knowing the index of the current iteration.
Found that the enumerate() function does just that. Updated a previous program
to use this.
An excellent pen and paper solution to this problem.
http://www.mathblog.dk/project-euler-25-fibonacci-sequence-1000-digi... |
db84f97977120139c1f2d5caf434056c0e74a3b5 | elainy-liandro/mundo1e2-python-cursoemvideo | /Desafio42.py | 504 | 3.953125 | 4 | print('-='*20)
print('Desafio 42 - Triângulos')
r1 = float(input('Primeiro segmento: '))
r2 = float(input('Segundo segmento: '))
r3 = float(input('Terceiro segmento: '))
if r1 < r2 + r3 and r2 < r1 + r3 and r3 < r1 + r2:
print('Os seguimentos acima PODEM FORMAR Triângulo',end='')
if r1 == r2 == r3:
pri... |
b9b350d763ccf61b56af719ef0e674d24937ca9a | HAKSOAT/Timely | /calendar_picker/CalendarDialog.py | 1,618 | 3.609375 | 4 | import tkinter
from calendar_picker import ttkcalendar
from calendar_picker import tkSimpleDialog
class CalendarDialog(tkSimpleDialog.Dialog):
"""Dialog box that displays a calendar and returns the selected date"""
def body(self, master):
self.calendar = ttkcalendar.Calendar(master)
self.cal... |
3349b20b387f4434cfefbbcc22655af873a06913 | maridigiolo/python-exercises | /pyexe/madlib.py | 255 | 4.0625 | 4 | print (" Please fill in the blanks below: ")
print (" 's favorite subject in school is .")
name = input("What is your name? ")
subj = input ("What is you favorite subject in school? ")
print (name + "'s favorite subject in school is " + subj)
|
762c14fad9a80b66c672c65180b704fc20e3c2d6 | milenaS92/HW070172 | /L03/exercise5.py | 670 | 4.21875 | 4 | # A program to compare Celsius and Farenheit temperatures
def main():
print("********************************************************")
print("This program compares Celsius and Farenheit temperatures")
print("********************************************************")
for i in range(0, 110, 10):
... |
53d15e4b5757fb0581933a87c9c9bfef85743594 | cielavenir/procon | /aizu/tyama_aizuALDS1~2D.py | 550 | 3.8125 | 4 | #!/usr/bin/python
import sys
if sys.version_info[0]>=3: raw_input=input
def insertionSort(a,g):
global cnt
for i in range(g,len(a)):
v = a[i]
j = i - g
while j >= 0 and a[j] > v:
a[j+g] = a[j]
j = j - g
cnt+=1
a[j+g] = v
def shellSort(a):
global cnt
cnt = 0
g = []
h = 1
while h <= len(a):
g... |
77ee09399ade81f8873ef47fe94a9475602bfd07 | andiegoode12/Intro-to-Computer-Programming | /Assignments/Assignment45.py | 502 | 3.703125 | 4 | """
Andie Goode
10/26/15
File I/O: Line Numbers
"""
#prompt user for filename
name = input("Enter a filename: ")
print("")
#open file
file = open(name,'r')
#ouput statement
print("Contents of",name)
#set lines equal to reading file
lines = file.read()
#set line equal to a list of each seperate line
line = lines.split('... |
c4ad54304524270f2c244b47c30ffb7b54987f62 | Shalini2801/S.Shalini-csc | /Task14(2).py | 978 | 4.375 | 4 | #2.Design a simple calculator app with try and except for all use cases
def calculate():
try:
print('+')
print('-')
print('*')
print('/')
print('%')
print('**')
operation = input("Select an operator:")
print("Enter two numbers")
number_1 = int(... |
eba99a49ea7f77606186b5747a71c6bb2c073820 | kilik42/tkinter_appPython | /grid.py | 642 | 4.625 | 5 | from tkinter import *
root = Tk()
#creating label widget
#myLabel1 = Label(root, text="hello world!")
##myLabel2 = Label(root, text="my name is jake dawn!")
#myLabel3 = Label(root, text="dumas is the name!")
#shoving it on the screen
#myLabel.pack()
#myLabel1.grid(row=0, column=0)
#myLabel2.grid(row=1, column=0)
#myL... |
6fc69be211b1159860d14f4caceb83ea9375fe1f | retuam/pyadvanced | /homework_06/homework_06_02.py | 2,649 | 3.96875 | 4 | # 2) Создать свою структуру данных Словарь, которая поддерживает методы,
# get, items, keys, values. Так же перегрузить операцию сложения для
# словарей, которая возвращает новый расширенный объект.
class MyDict:
def __init__(self, **kwargs):
self._current = 0
self._structure = {}
for key... |
47759affc32dc878ecc6ea164e893b236c98a551 | Marist-CMPT120-FA19/STUREBORG-VERONICA-Project3 | /tree.py | 339 | 4.21875 | 4 | #CMPT 120L 200
#Veronica Stureborg
#Program to display a tree on screen using text characters
#i is equal to the row
#h is the height of the tree
def main():
h=int(input("How high would you like the tree to be?"))
for i in range (h):
print(((h-i-1))* ' '+(i*2+1)* '#')
print((h-1)* ' '+'#') ... |
3a984e01afccce5e87875486738da27f719e9b11 | kevinnaguirre9/python-from-zero | /CalculadoraPython.py | 2,864 | 4 | 4 | import numpy as np
from math import *
def menu():
while True:
print("1.- Sumar")
print("2.- Restar")
print("3.- Multiplicar")
print("4.- Dividir")
print("5.- Potencia")
print("6.- Raíz")
print("0.- Exit")
try:
op = int... |
30ec9be80209d5a43efa1276186f8f7625745869 | 777preethi/PythonSample | /syntax.py | 307 | 3.796875 | 4 | print("Python Basic Syntax")
print("Python Indentations:")
if 5 > 2:
print("Five is greater than two!")
print("Python Comments:")
#This is a comment.
print("There is a comment above.")
print("Python Docstrings:")
"""This is a
multiline docstring."""
print("There is a multiline docstring above.") |
b7b191993866d8d10c92cc9e299bdb294d5d819e | rcsbiotech/learnerboi | /03_rosalind/old_stronghold_scripts/19_SharedMotif.py | 1,431 | 4.125 | 4 | #!/usr/bin/env python3
"""
-----------------------------------------------------------------------------
A common substring of a collection of strings is a substring of
every member of the collection. We say that a common substring
is a longest common substring if there does not exist a longer
common substring. For... |
5f7a69e20d383e4a64c2a21a09d0455454adecaa | bloverton/MiningSomeData | /scripts/preprocessing/test.py | 1,012 | 3.515625 | 4 | import time
import json
import pandas as pd
import matplotlib.pyplot as plt
def main():
print('Starting review_count normalization')
df = pd.read_csv("optimized_yelp_academic_dataset_user1.csv")
print("Finished Reading .csv file")
#print(df.info(memory_usage='deep'))
print("Processing min-max al... |
91827ba07dc8123c9639b27f049b860aa5b9a127 | albertojr/estudospython | /ex024.py | 270 | 4.03125 | 4 | nome = input('Digite o nome de uma cidade: ').strip().upper()#removo os espaço e deixo tudo maisculo
print('Se o retorno for true, tem a palavra SANTO.\nCaso for False, não tem a palavra')
print('\n\nRetorno:{}'.format(nome[:5] == 'SANTO'))#leio as 5 primeiras letras
|
9c4b1dc3fc9f48e7fd400dc10fd441de2e3074bc | Asurada2015/Python-Data-Analysis-Learning-Notes | /Matplotlib/demo_00Mofandemo/00_ceshi_demo.py | 223 | 3.671875 | 4 | """测试linspace,meshgrid函数"""
import matplotlib.pyplot as plt
import numpy as np
nx, ny = (3, 2)
x = np.linspace(0, 1, nx)
y = np.linspace(0, 1, ny)
xv, yv = np.meshgrid(x, y)
# print(x)
# print(y)
print(xv)
print(yv) |
81c5006758e185cbb5127558096946ac2360422b | praneethaa83/The-Sparks-Foundation---Task-1 | /task1.py | 1,414 | 3.59375 | 4 | #TASK 1
#M.PRANEETHAA
#importing the required libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn import metrics
# importing the dataset ... |
82a5880a96f86590c01e5bf99f41c9c36df722f5 | arumnenden/pdpbo3-Nenden-Bucin | /main.py | 7,139 | 3.625 | 4 | from tkinter import *
import sqlite3
root = Tk()
root.title("Halaman Reservasi")
root.geometry("600x410")
#Databases
#Create a database or connect to one
conn = sqlite3.connect('data.db')
#Create cursor
c = conn.cursor()
#create table
# c.execute(""" CREATE TABLE couple(
# nama_cowo text,
#... |
99548b09f52a00a531433a1414024d5519898b4f | codeAligned/Programming-Interviews-Problems | /The Algorithm Design Manual/fibo.py | 438 | 3.5 | 4 |
def fibo_rec(n):
if n==0:
return 0
if n == 1:
return 1
else:
return fibo_rec(n-1)+fibo_rec(n-2)
def fibo_it(n):
result=0
prv=1
prvprv=0
if n<2:
return n
for i in range(1,n):
result= prv + prvprv
prvprv=prv
prv=result
i+=1
return result
fibTable = {1:1, 2:1}
def fib_rec_hash(n):
... |
0e6b0712f81f93e857905496e43064971d45e78e | CodingClubGECB/practice-questions | /Python/Week-1/01_multiplication_table.py | 146 | 4.34375 | 4 | #1.Write a program to print the multiplication table of a number upto 10.
n = int(input())
for i in range(11):
print(n, " x ", i, " = ", n*i)
|
5989c6094c599ba9d3cc0ab2dc974f81123a7b91 | gabriellaec/desoft-analise-exercicios | /backup/user_058/ch21_2019_08_26_20_34_56_596427.py | 105 | 3.71875 | 4 | X=(float(input("Qual o valor da conta? ")
y=(1.1)*x
print("Valor da conta com 10%: R$ {0:.2f}".format(y)) |
42eb7fcda7769533db5f422ffc69734ef15081e7 | bodii/test-code | /python/python-cookbook-test-code/5 section/13.py | 2,479 | 3.734375 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
Topic: 第五章:文件与 IO
Desc: 所有程序都要处理输入和输出。这一章将涵盖处理不同类型的文件,包括文本和二
进制文件,文件编码和其他相关的内容。对文件名和目录的操作也会涉及到。
Title; 获取文件夹中的文件列表
Issue:你想获取文件系统中某个目录下的所有文件列表
Answer: 使用 os.listdir() 函数来获取某个目录中的文件列表
"""
import os
names = os.listdir('../test file/')
'''
结果会返回... |
45c8452783f848095d41f37c9d5737ce6e5cc7da | Harishkumar18/data_structures | /450_qn_ds_lb/move_neg_no_one_side.py | 367 | 4.03125 | 4 | """
Move all the negative elements to one side of the array
"""
def move_negative_nos(arr):
neg = 0
pos = len(arr)-1
while neg <= pos:
if arr[neg] < 0 :
neg += 1
else:
arr[neg], arr[pos] = arr[pos], arr[neg]
pos -= 1
return arr
arr = [9, -8, 5, 0, ... |
ec846a3040ebb614f27740762657c8709145598b | InjiChoi/algorithm_study | /정렬 알고리즘/quicksort.py | 440 | 3.796875 | 4 | # 퀵 정렬 구현
def quicksort(data):
if len(data)<1:
return data
left = list()
right = list()
pivot = data[0]
for i in range(1, len(data)):
if pivot > data[i]:
left.append(data[i])
else:
right.append(data[i])
return quicksort(left) + [pivot] + qui... |
649600fdd1eb2bea61ac49c67384e5dcc85808df | AdamZhouSE/pythonHomework | /Code/CodeRecords/2711/58547/272200.py | 1,171 | 3.5 | 4 | def is_avail(word0, word1):
if len(word0) != len(word1):
return False
diff_index = []
i = 0
while i < len(word0):
if word0[i] != word1[i]:
diff_index.append(i)
if len(diff_index) > 2:
return False
i += 1
if len(diff_index) != 2:
retur... |
d0163eed15aa96bb9b2f01c56eee36a340b952a2 | MayKeziah/CSC110 | /assn6_funcs.py | 2,229 | 4.28125 | 4 | #Keziah May
#05/16/18
#CSC110
#Assn6
def main():
print("This program calculates fuel efficiency on a multi-leg journey.\n"
"It returns the MPG per leg and the MPG overall.\n")
#get the starting odometer reading
StartMiles = float(input("\nPlease enter your starting odometer reading:\n"))
Buil... |
c636d9e00ff9cf0fff8218de3c3c6a1e90b70278 | MaximeWbr/Expedia_Project | /Pokemon_Game/Package_Object/Object.py | 134 | 3.75 | 4 | from abc, import ABC, abstractmethod
class Object(ABC):
def __init__(self):
self.name = ""
self.price = 0
super().__init__()
|
0826e76a4f39803c8b2c0bb9c6c9487b8e748500 | VladiGH/FP_Python | /Labo6_ejercicio9.py | 709 | 3.84375 | 4 | """Hacer un programa que dado un rango de números (por ejemplo de 10 hasta 100) y
muestre todos los números que son múltiplo de x número en
ese rango (por ejemplo los múltiplos de 3)"""
flag = 0
while(flag == 0):
try:
limInferior = int(input("Ingresa el lim inferior del rango: "))
limSuperior = ... |
bd9a610d76da05f2bf63bc11a74ac228a8c1177f | Nooder/Cracking-Codes-With-Python | /Chapter 15 - HACKING THE AFFINE CIPHER/AffineHacker.py | 1,832 | 4.0625 | 4 | #!python3
# Chapter 15 Project - Hacking the Affine Cipher
import AffineCipher, CryptoMath, DetectEnglish
SILENT_MODE = False
def main():
message = """5QG9ol3La6QI93!xQxaia6faQL9QdaQG1!!axQARLa!!AuaRLQADQALQG93!xQxaGaAfaQ1QX3o1RQARL9Qda!AafARuQLX1LQALQI1iQX3o1RN"Q-5!1RQP36ARu"""
hackedMessage = hackAff... |
57a3213207726e011f38bcd944bdc1b91ababb79 | jacktnp/PSIT60 | /Week 11/4-RunLengthDecoding.py | 499 | 3.609375 | 4 | """ PSIT Week 11
Wiput Pootong (60070090)
Run Length Decoding
"""
def main():
""" Convert encoded string into decoded """
strings = input()
counts = []
chars = []
temp = ""
for char in strings:
if char.isdigit():
temp += char
else:
counts.append(int(tem... |
646b571b771c1a79b88bf78728ac29727eb25aaf | greshem/develop_python | /check_chinese.py | 1,098 | 3.6875 | 4 | #!/usr/bin/python
#coding:utf-8
def is_chinese(uchar):
"""
#判断一个unicode是否是汉字
"""
if uchar >= u'\u4e00' and uchar<=u'\u9fa5':
return True
else:
return False
def contains_chinese(input):
chinese = unicode(input, "utf-8")
for each in chinese:
if is_chinese(each):
... |
d59910760266b28aa8dc2ed468a4de275b33873f | tainenko/Leetcode2019 | /leetcode/editor/en/[1716]Calculate Money in Leetcode Bank.py | 1,390 | 3.59375 | 4 | # Hercy wants to save money for his first car. He puts money in the Leetcode
# bank every day.
#
# He starts by putting in $1 on Monday, the first day. Every day from Tuesday
# to Sunday, he will put in $1 more than the day before. On every subsequent
# Monday, he will put in $1 more than the previous Monday.
# ... |
79f8d1b6d92fe6e5c5bda0b9b30a557ec432281c | kautilya/billing | /Identity.py | 1,388 | 3.5 | 4 | import logging;
class Entity:
def __init(self):
pass;
def __init__(self, name, email, spouse, semail):
self._name = name;
self._email = email;
self._spouse = spouse;
self._semail = semail;
def printData(self) :
logging.info("Entity: %s <%s>\n", self._name, self._email);
def name(self... |
1922f14e27907d4b02f0e55c64e007fe8b7eebf3 | ash/python-tut | /course/tasks/count-words-in-file.py | 197 | 3.9375 | 4 | filename = input('File name: ')
content = ''
for line in open(filename):
content += line
#print(content.split())
words_count = len(content.split())
print('%d words in the file' % words_count) |
7bbc94e35ba64c9288f5dc2c398d2c865b2dc125 | fwparkercode/IntroProgrammingNotes | /Notes/Spring2020/Ch7LabStarterCode.py | 1,263 | 3.734375 | 4 | '''
Chapter 7 Lights Out
'''
import random
done = False
# print numbers 0 to 9 using a for loop
# override "\n" by using keyword argument end = " "
print("Francis", end=" ")
print("Parker")
# create a random X O list
lights = []
for i in range(10):
flip = random.randrange(2)
if flip == 0:
lights.... |
ce9915bca1ad0951f097d777cb752091269336c1 | rajadavidh/learning-opencv-python | /source/_11_template_matching.py | 1,251 | 3.703125 | 4 | # Run command: python _11_template_matching.py
# We are going to implement basic object recognition by finding identical
# regions of an image that match a template we provide.
# Further reading:
# https://docs.opencv.org/master/d4/dc6/tutorial_py_template_matching.html
# Importing libraries as shortcut
import numpy a... |
87e7ea2ba8d88dca72ee07940707872a8dd68816 | nickfang/classes | /projectEuler/webScraping/problemTemplates/348.py | 587 | 3.859375 | 4 | # Sum of a square and a cube
#
#Many numbers can be expressed as the sum of a square and a cube. Some of them in more than one way.
#Consider the palindromic numbers that can be expressed as the sum of a square and a cube, both greater than 1, in exactly 4 different ways.
#For example, 5229225 is a palindromic number ... |
982922076fd3ebac94e081475675e18922d1e1cf | TeonD/Python_Beginnings | /SuSu/DICE.py | 1,759 | 3.921875 | 4 |
import random
print("Lets play dice")
print("Hit enter to roll")
input()
leaveprogram = 0
while leaveprogram != "q":
number=random.randint(1,6)
if number == 1:
print("[-------------]")
print("[ ]")
print("[ O ]")
print("[ ]")
... |
dc0599621a01b12f83c3276d18cee00b71a80f33 | LeoHung/myleetcode | /Roman_to_Integer/solution.py | 1,334 | 3.53125 | 4 | class Solution:
# @return an integer
def romanToInt(self, s):
n1_num = ["", "I", "II","III", "IV", "V", "VI", "VII", "VIII", "IX"]
n2_num = ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"]
n3_num = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"]
n4_num =... |
49ba3435b679a809ee1310529ccecb55c54d107f | xlocux/Scripts | /favhash.py | 724 | 3.546875 | 4 | # favhash is a script to obtain a favicon hash.
# then search in shodan https://www.shodan.io/search?query=http.favicon.hash%3A-538460259&page=3
# or use qshodanscript to obtains IP addresses
import sys
import mmh3
import requests
import argparse
import base64
parser = argparse.ArgumentParser()
parser.add_argument(... |
abf3842405c2a21881a257124fb54b70c3643fe3 | decodingjourney/BeginnerToExpertInPython | /Functions/functions.py | 664 | 3.671875 | 4 | def python_food():
width = 80
text = "Spam and Eggs"
left_margin = (width - len(text)) // 2
print(" " * left_margin, text)
def center_text(*args):
text = ""
for arg in args:
text += str(arg) + " "
left_margin = (80 - len(text)) // 2
return " " * left_margin + text
# with open("... |
5ef599e74ed4cc0d9000434228e1696a0ecda224 | TinaCloud/leanleet | /380.py | 975 | 3.515625 | 4 | class RandomizedSet:
def __init__(self):
self.top_key = 0
self.value_dict = {}
self.key_dict = {}
def insert(self, val: int) -> bool:
if val not in self.value_dict:
self.value_dict[val] = self.top_key
self.key_dict[self.top_key] = val
... |
b45c47597afd831d1c0d7f665c451d397db3032c | lamoureux-sylvain/BlackJack | /hand.py | 2,355 | 3.59375 | 4 | from cards import Card
class Hand:
def __init__(self, dealer=False):
self.dealer = dealer
self.cards = []
self.value = 0
self.check_ace = False
def add_card(self, card):
self.cards.append(card)
def calculate_value(self):
self.value = 0
if self.deal... |
23cabdc141d14347accb29a4a33abc5fc3821e3b | deborabr21/mycode | /fact/looping_challenge2.py | 499 | 4.25 | 4 | #!/usr/bin/env python3
farms = [{"name": "NE Farm", "agriculture": ["sheep", "cows", "pigs", "chickens", "llamas", "cats"]},
{"name": "W Farm", "agriculture": ["pigs", "chickens", "llamas"]},
{"name": "SE Farm", "agriculture": ["chickens", "carrots", "celery"]}]
for dict in farms: #looping across ev... |
57a81e9a846cf95a344554fb7f3cd1c053641de9 | fergmack/efficient-python-code | /faster_loops.py | 1,934 | 3.890625 | 4 | # A list of integers that represents each Pokémon's generation has been loaded into your session called generations. You'd like to gather the counts of each generation and determine what percentage each generation accounts for out of the total count of integers.
from collections import Counter
generations = [4, 1, 3... |
8b9a38bf26dd9800a3a9f54ffb0e0614e2780f42 | ConnerSick/Python-Challenge | /PyBank/main.py | 1,690 | 3.734375 | 4 | import os
import csv
csvpath = os.path.join(".." , "budget_data.csv")
# define all variables
profit_sum = 0
months = 0
profit_change = 0
total_change = 0
largest_increase = 0
largest_decrease = 0
row_count = 0
profit = []
month_list = []
greatest_increase_month = 0
greatest_decrease_month = 0
with open(csvpath,newlin... |
836363ddcef982ad8acded5f168057bb7cce16ca | alpiges/emukit | /emukit/core/loop/user_function.py | 1,706 | 4.0625 | 4 | """
This file contains the "OuterFunction" base class and implementations
The outer function is the objective function in optimization, the integrand in quadrature or the function to be learnt
in experimental design.
"""
import abc
from typing import Callable, List
import numpy as np
from .user_function_result impo... |
d522bb5401656e47183258c925bb7edc02ff31a1 | Nine-Songs/Fundamentals_of_Python | /03/搜索最小值.py | 284 | 3.796875 | 4 | '''
Returns the index of the minimun item
O(n)
'''
def indexOfMin(lyst):
minIndex = 0 #the index of the minimum item is 0
currentIndex = 1
while currentIndex < len(lyst):
if lyst[minIndex] > lyst[currentIndex]:
minIndex = currentIndex
currentIndex += 1
return minIndex
|
5eecf3913d57b27075f8b3b6c4b673968de28361 | joaovicentesouto/INE5452 | /lists/seven/p10.py | 227 | 3.59375 | 4 | # -*- coding: utf-8 -*-
while True:
a, b, c, d = input().split()
a = int(a)
b = int(b)
c = int(c)
d = int(d)
if (a + b + c + d) == 0:
break
x = c * (a/2 + b) / d
print("%.5f" % x) |
910726d6542069c0891db12a29b8b9f0a6112b92 | OCCOHOCOREX/HuangXinren-Portfolio | /Weekly Tasks/Week1/HuangXinren-Week1-Task1.py | 525 | 4.125 | 4 | number_list=[1,2,3,4,5,6.5]
print("number list:" , number_list)
def the_numbers(number_list):
even_list=[]
for number in number_list:
if number % 2 == 0:
even_list.append(number)
return even_list
even_number = the_numbers(number_list)
print("even", even_number)
def the_numbers(number... |
08693ca174d12eff737cc6a467d1159652787a31 | astralblack/Calculator | /calc.py | 1,262 | 4.5 | 4 | # Astral's Calcultor
# Date: 9.27.18
# Menu
print("Hello welcome to my calculator!\n")
print("1: Addition")
print("2: Subtraction")
print("3: Multiplication")
print("4: Division\n")
# Functions
def addition():
num1 = int(input ("What is the first number?"))
num2 = int(input ("What is the second ... |
22b6b83b25fc6b96208d93e0e5ec4c8eb54b6bd4 | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/Lambda-Resource-Static-Assets/2-resources/BLOG/Data-Structures/1-Python/linkedlist/reverse.py | 746 | 4.09375 | 4 | """
Reverse a singly linked list. For example:
1 --> 2 --> 3 --> 4
After reverse:
4 --> 3 --> 2 --> 1
"""
#
# Iterative solution
# T(n)- O(n)
#
def reverse_list(head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head
prev = None
while head:
... |
92225469265c939c4bbbd1529346809d7aada2ae | samuelyusunwang/quant-econ | /myExercise/05_numPy/ex01_polyval.py | 311 | 3.59375 | 4 | # Use numPy to calculate polynomial value
import numpy as np
def p(x, coeff):
x_power = np.ones(len(coeff))
x_power[1:] = x
x_power = np.cumprod(x_power)
return np.sum((x_power) * np.array(coeff))
# Test code
coeff = [1, 2, 3, 4, 5]
x = [0, 1, 2, 3]
for xx in x:
print(p(xx,coeff))
|
f6806a16502a870fee8d794d8ccebe919c7483dd | VladKli/Lasoft | /9.py | 1,482 | 4.15625 | 4 | # З клавіатури вводиться ціле число в діапазоні від 0 до 1000000. Необхідно вивести його прописний стрічковий еквівалент
# The first option
# _____________________________________________________
# from num2words import num2words
# number = input('Print any number, please: ')
# print(num2words(0))
# ________________... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.