blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
1683cfe20acc2fdc633b4d5cdb92295c2793fa0a | codewithgauri/HacktoberFest | /python/Leetcode_1371_Find_the_Longest_Substring_Containing_Vowels_in_Even_Counts.py | 1,687 | 4.0625 | 4 | '''
Given the string s, return the size of the longest substring containing each vowel an even number of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times.
Example 1:
Input: s = "eleetminicoworoep"
Output: 13
Explanation: The longest substring is "leetminicowor" which contains two each of... |
f51ad176266865429620db22dae1090011bafe66 | codewithgauri/HacktoberFest | /python/Learning Files/31-Object Oriented Programming-Class method and Static Method.py | 2,069 | 4.09375 | 4 | # class Account(object):
# count = 0
# # Class Variable
# def __init__(self,cust_id,name,initial_balance=0):
# self.__customer_id=cust_id
# self.__name=name
# self.__balance=initial_balance
# Account.count+=1
# def get_balance(self):
# return self.__balance
# def get_id(self):
# return self.__custome... |
453eb80f8c7d3c8353c7288f4beea8e3f7e0c1c5 | codewithgauri/HacktoberFest | /python/Cryptography/Prime Numbers/naive_primality_test.py | 576 | 4.21875 | 4 | ##Make sure to run with Python3 . Python2 will show issues
from math import sqrt
from math import floor
def is_prime(num):
#numbers smaller than 2 can not be primes
if num<=2: return False
#even numbers can not be primes
if num%2==0: return False
#we have already checked numbers < 3
#finding primes up to N we... |
51d1cb5a523fa102734d50143a3b9eab17faf2cb | codewithgauri/HacktoberFest | /python/Learning Files/13-Dictionary Data Types , Storing and Accessing the data in dictionary , Closer look at python data types.py.py | 1,580 | 4.3125 | 4 | # dict:
# 1. mutable
# 2.unordered= no indexing and slicing
# 3.key must be unque
# 4.keys should be immutable
# 5. the only allowed data type for key is int , string , tuple
# reason mutable data type is not allowed
# for example
# d={"emp_id":101 , [10,20,30]:100,[10,20]:200}
# if we add an element into [10,20] of 30... |
875a5fb9806d97f9aa2fb602246ba5ddd7b03e4d | codewithgauri/HacktoberFest | /python/interpolation_search.py | 1,423 | 4.09375 | 4 | """
Implementation of Interpolation Search
"""
def interpolation_search(sample_input, lowest, highest, item):
"""
function to search the item in a give list of item
:param sample_input: list of number
:param lowest: the lowest element on our list
:param highest: the highest element on our list
... |
31051c6c2ab1c3de61a06f386ec75978486f1e0f | codewithgauri/HacktoberFest | /python/Algorithms/Implementation/Modified Kaprekar Numbers.py | 412 | 3.65625 | 4 | import math
def kaprekarNumbers(p, q):
# c = list(str(int(math.pow(p,2))))
# print("Yes" if int(c[0])+int(c[1])==p else "NO")
for i in range(p,q+1):
c = list(str(int(math.pow(i,2))))
# print(c)
if len(c)>1:
if int(c[0]) + int(c[1]) == i:
print(i)
if __... |
e6f197c0cf5d3c02698c8f82449cb2a50c21d34a | codewithgauri/HacktoberFest | /python/Cryptography/Ceasar's Cipher/Ceasar_crack_Brute_force.py | 549 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat May 11 11:57:28 2019
@author: jmat
"""
ALPHABET=" ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def ceasar_crack(cipher_text):
for key in range(len(ALPHABET)):
plain_text=""
for c in cipher_text:
index=ALPHABET.find(c)
index=(index-key)%l... |
767c1781d90744b7945f59904a953844ffcba9fa | emaquino44/Graphs | /projects/graph/src/graph.py | 2,485 | 3.75 | 4 | """
Simple graph implementation compatible with BokehGraph class.
"""
class Graph:
"""Represent a graph as a dictionary of vertices mapping labels to edges."""
def __init__(self):
self.vertices = {}
self.groups = []
def add_vertex(self, vertex):
if vertex in self.vertices:
... |
6ecd3e7ab69721bc7e0183560f7610176e0dd941 | madskinner/bibterm2dict | /bibterm2dict/myclasses/multi_column_listbox.py | 5,651 | 3.625 | 4 | # -*- coding: utf-8 -*-
'''
Here the TreeView widget is configured as a multi-column listbox
with adjustable column width and column-header-click sorting in Python3.
'''
from tkinter.ttk import Treeview, Scrollbar, Label, Frame
from tkinter.font import Font
from tkinter import messagebox
class MultiColumnListbox(obje... |
a232e1136f5e328525317a30c0d8a24dacb3d175 | Art83/python_bioinformatics | /patternMatch.py | 708 | 3.5625 | 4 | # Finding all occurences of a ppatern in a string
def PatternMatching(Pattern, Genome):
positions = [] # output variable
i = -1
while True:
i = Genome.find(Pattern, i+1)
if i != -1:
positions.append(i)
else:
break
return positions
#Alternative way
'''... |
aad7e7286442ee3f7bb46bee869f0f89a80f1369 | bdngo/math-algs | /python/fizzbuzz.py | 368 | 3.78125 | 4 | def fizzbuzz(n: int) -> None:
"""Solves the FizzBuzz problem.
>>> fizzbuzz(10)
1
2
fizz
4
buzz
6
7
8
fizz
buzz
"""
for i in range(1, n + 1):
s = ''
if i % 3 == 0:
s += 'fizz'
if i % 5 == 0:
s += 'fuzz'
if s ... |
2725b85849ce224e97685919f148cc9807e60d83 | bdngo/math-algs | /python/checksum.py | 1,155 | 4.21875 | 4 | from typing import List
def digit_root(n: int, base: int=10) -> int:
"""Returns the digital root for an integer N."""
assert type(n) == 'int'
total = 0
while n:
total += n % base
n //= base
return digit_root(total) if total >= base else total
def int_to_list(n: int, base: int=10) ... |
67fa4b28d9bc8d0df0f2f784d94a0ba6eb9dd889 | anatoliis/ProjectEuler | /problems/Problem50.py | 387 | 3.6875 | 4 | #!/usr/bin/env python2
from primes import primes_list, prime
def find():
primes = primes_list(10**4)
for length in xrange(1000, 0, -1):
first = 0
while True:
summ = sum(primes[first:first+length])
# print summ
if summ >= 10**6: break
if prime(summ... |
154ee4f1f1ba4c3c2575c65d20419fe4af2b50f5 | jingruhou/Python-2 | /python100/day02/variable3.py | 727 | 3.96875 | 4 | #coding=utf-8
#使用type()检查变量的类型
a = 100
b = 12.345
c = 1 + 5j
d = 'hello, world'
e = True
print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(e))
# 在对变量类型进行转换时可以使用Python的内置函数(准确的说下面列出的并不是真正意义上的函数,而是后面我们要讲到的创建对象的构造方法)
# int():将一个数值或字符串转换成整数,可以指定进制
# float():将一个字符串转换成浮点数
# str():将指定的对象转换成字符串形式,可以指定... |
e59e8ab7f5309cb1f0b20db374f2e8850619c765 | JasonTGuerrero/UCLA-PIC-16A | /hw3.py | 2,686 | 3.828125 | 4 | import copy
class Node:
def __init__(self, data):
self.data = data
self.next = None
def __str__(self):
return str(self.data)
def __repr__(self):
return repr(self.data)
# class LinkedList:
# def __init__(self, data):
# self.node = Node(data)
# s... |
e64687b9baaa75ae481ea65ed9e2cd26a203e41a | kimoror/python-practice | /practice1_extra/main.py | 2,722 | 4.25 | 4 | # Ответы на теоретические вопросы находятся в файле AnswersOnQuestions.md
"""
Попробуйте составить код для решения следующих задач. Из арифметических операций можно использовать только явно
указанные и в указанном количестве. Входным аргументом является переменная x.
"""
def no_multiply(x):
if x == 12:
r... |
b7b944e5d5dd1cd1b41952c55bc13c348f905024 | Oyekunle-Mark/Graphs | /projects/ancestor/ancestor.py | 1,360 | 3.671875 | 4 | from graph import Graph
from util import Stack
def earliest_ancestor(ancestors, starting_node):
# FIRST REPRESENT THE INPUT ANCESTORS AS A GRAPH
# create a graph instance
graph = Graph()
# loop through ancestors and add every number as a vertex
for parent, child in ancestors:
# add the pa... |
613b5d072a397ca353476abcac2d66495e96b4d9 | CrazyPants9527/py-tasks | /guessnumber/GuessNum.py | 2,273 | 3.671875 | 4 | import random
# 返回一个元素0-9,随机且不重复,长度为4的list
def random_number():
numbers = []
temp_list = []
while True:
temp_list.append(random.randint(0,9))
numbers = list(set(temp_list))
if len(numbers) == 4:
return numbers
# 不改变原来list元素顺序情况下去除重复元素
def unlike(before_list):
if is... |
3e0c85bb6321ca933c71fb484ef0a520e3ad2f87 | chinski99/minilogia | /2008/etap 2/gwiazdki2007.py | 582 | 3.59375 | 4 | from turtle import *
from math import sqrt
def gwiazdki():
l=50
shape(l)
for _ in range(5):
x=pos()
y=heading()
fd(l)
lt(18)
fd(l)
lt(18)
shape(l)
setpos(x)
setheading(y)
rt(72)
def triangle(a):
fd(a)
lt(135)
fd(a*... |
3659c9dd6a3993115d9b610d6d6b9c5e0b93c6fa | chinski99/minilogia | /2014/etap 3/plecionka.py | 735 | 3.515625 | 4 |
from turtle import *
def simple(a,col):
pendown()
fillcolor(col)
begin_fill()
lt(30)
fd(3*a)
lt(120)
fd(a)
lt(60)
fd(2*a)
rt(60)
fd(2*a)
lt(60)
fd(a)
lt(120)
fd(3*a)
end_fill()
lt(30)
penup()
def compo(a):
c=["brown","orange","yellow"]
... |
f183bcf992758994b4e6f873fbde493e0b5529c5 | chinski99/minilogia | /2012/etap 3/dywan.py | 528 | 3.53125 | 4 | from turtle import *
def element(level, k):
fillcolor("red")
begin_fill()
for _ in range(4):
fd(k)
lt(90)
end_fill()
if level>1:
for _ in range(3):
fd(k)
rt(90)
element(level - 1, k/2)
lt(180)
fd(k)
lt(90)
de... |
5cde8d9cd2ad809629b64393c33d2935f8db6c2c | chinski99/minilogia | /2015/etap 2/reg.py | 1,142 | 3.59375 | 4 | __author__ = 'apple'
from turtle import *
from random import randint
K = 20
def reg(szer, n): # szerokość regału, liczba półek
start_position(szer, n)
regal(szer, n)
fd(K)
for _ in range(n):
polka(szer // K - 2)
up(7)
def polka(k):
rect(k * K, 6*K, "white")
pendown()
f... |
65069818b7113570eaa349f69cb5336c6005745a | carolinesalves/projeto-simples | /Exercicio_Python/Exerc11.py | 385 | 4.09375 | 4 | N1 = int(input("Digite o primeiro número inteiro: "))
N2 = int(input("Digite o segundo número inteiro: "))
R = float(input("Digite um número real: "))
produto = (2 * N1) * (N2/2)
print("O produto entre os números é: ", round(produto,1))
soma = (3*N1) + R
print("A soma dos números é: ", round(soma,1))
potencia = R**3... |
c9454251b1907aa3ea2d92a02dc891fe862e7e63 | Seth-R/WEB_STANFORD | /CURSO_08_FLASK/app3.py | 780 | 3.734375 | 4 | #CODIGO PARA MULTIPLES ROUTES EN FLASK PERSONALIZADAS SEGUN RUTA INGRESADA
#Nota: flask NO viene en librerias por defecto, debemos instalarla adicionalmente (pip install flask)
from flask import Flask
#Creamos web application llamada "app" (basada en Flask), con nombre del archivo actual (__name__)
app = Flask(__name... |
0f812ca5e58d16447763e00bb60c6b34e025d5c1 | jancoufal/pyshards | /overloaded-operators.py | 1,085 | 3.734375 | 4 | class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return '[%.2f;%.2f]' % (self.x, self.y)
def __neg__(self):
return Point(-self.x, -self.y)
def __add__(self, point):
return Point(self.x + point.x, self.y + point.y)
def __sub__(self, point):
return Point(self.x ... |
a215bb43b5e7e913c09874141bc6381e7048a69e | prihoda/bgc-pipeline | /bgc_detection/evaluation/lco_split.py | 10,110 | 3.5625 | 4 | #!/usr/bin/env python
# David Prihoda
# Create Leave-Class-Out splits from set of negative and positive samples
# Produces a folder with (train, test) files for each class.
import merge_split_samples
import argparse
import numpy as np
import pandas as pd
import os
from sklearn.model_selection import KFold, ShuffleSpli... |
0dab75e2db748b4934d10038634d4d7f438ad02b | prihoda/bgc-pipeline | /bgc_detection/evaluation/merge_split_samples.py | 2,431 | 3.640625 | 4 | #!/usr/bin/env python
# David Prihoda
# Functions for shuffling and merging sequence samples (DataFrames) into a long sequence
# Used for fake genome generation from positive and negative BGC samples
import pandas as pd
import numpy as np
from sklearn.model_selection import KFold
def merge_samples(samples_series, idx... |
d29ead2b058d80104f5a2912cf49efa0b572fd1b | OniDaito/PythonCourse | /bomberman/part3/level.py | 666 | 3.9375 | 4 | import pyglet
from square import *
class Level():
''' A class that represents a typical level '''
grid = [] # This defines a list
block_size = 30
grid_width = 20
grid_height = 20
def __init__(self):
# First thing we do is create a basic looking level of blanks
''' F... |
56e828677722595a316d4711f683aba86f02b0bf | sianmck/price_comparison | /02_no_numbers.py | 244 | 3.765625 | 4 | name=input("Product Name:")
error="This cannot have numbers"
has_errors=""
for letter in name:
if letter.isdigit()==True:
print(error)
has_errors="yes"
break
if has_errors!="yes":
print("Continue")
|
04ea9ee089582a05a37c7bf5aa39312e17970016 | paprockiw/lookup_tools | /revised_lookup.py | 5,646 | 3.828125 | 4 | import csv
class LookupBase(object):
def __init__(self):
self.key_fields = []
self.mapped = {}
def _comparable(self, other):
'''Helper function for building comparision methods in this class. It
checks to see if the object that is to be compared to the base object
is ... |
66dd5532e8b4d3d17b240455b0d69ab11d5f1e3d | miea/bravo | /bravo/utilities/automatic.py | 1,013 | 3.609375 | 4 | from itertools import product
def naive_scan(automaton, chunk):
"""
Utility function which can be used to implement a naive, slow, but
thorough chunk scan for automatons.
This method is designed to be directly useable on automaton classes to
provide the `scan()` interface.
"""
for i, bloc... |
e4b5deaf617944350733bb7c11a4da31eb2843a5 | sandeepjrs/python-prac | /__lt__.py | 501 | 3.90625 | 4 | class Saving_account():
'''this is the saving account PIN and balance'''
def __init__(self, name, pin, balance = 0.0):
self._name= name;
self._pin = pin
self._balance = balance
def __lt__(self, other):
return self._name < other._name
def __eq__(self, other):
re... |
0c28b3bf79060065060af91d7de1316b80c39ce8 | eksalkeld/data-scientist-exercise02 | /analytics/modeling_fns.py | 4,486 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Functions to train a logistic regression model
Created on Sun Sep 6 15:57:19 2020
@author: eksalkeld
"""
from constants import *
from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV
from sklearn.linear_model import LogisticRegression
from s... |
db73ba125994c18470008cb985d63f6204e854d5 | leaferickson/Journalism_NLP | /data_collection/tweet_gatherer.py | 2,144 | 3.6875 | 4 | # -*- coding: utf-8 -*-
import pandas as pd
import tweepy
###Below funtion based on code from Yanofksy at https://gist.github.com/yanofsky/5436496
def get_all_tweets(screen_name, number_to_grab = 50):
"""Gather a user's last 3240 tweets (the most that twitter will allow).
To switch to a different number of ... |
f08e0ffcbe3ce6168714de18e8a936ecf935c761 | dword0/Python_projects | /Password_generator.py | 455 | 4 | 4 | #PASSWORD GENERATOR
import random
print("PASSWORD GENERATOR")
print("==================")
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()_.,?0123456789'
number = int(input("Number of passwords to be generated : "))
length = int(input("Password Length : "))
print("Here are your passwords : ")
f... |
17c45e7f86ead12c1f87669be88f0eb456dd145b | DistantThunder/learn-python | /ex5.py | 988 | 4.0625 | 4 | my_name = 'Darkeox'
my_age = 35 # is it?
my_height = 185 # centimeters
my_weight = 75 # kilos
my_eyes = 'Dark Brown'
my_teeth = 'White'
my_hair = 'Black'
print("Let's talk about %s." % my_name)
print("He's %d centimeters tall." % my_height)
print("He's %d kilos heavy." % my_weight)
print("Actually, that's not too h... |
52c44bf0aa15ba0bfcc1abda81fffefba6be075c | DistantThunder/learn-python | /ex33.py | 450 | 4.125 | 4 | numbers = []
# while i < 6:
# print("At the top i is {}".format(i))
# numbers.append(i)
#
# i = i + 1
# print("Numbers now: ", numbers)
# print("At the bottom i is {}\n{}".format(i, '-'))
def count_numbers(count):
count += 1
for i in range(0, count):
numbers.append(i)
return 0... |
bf2a57052391e74eb1a01c6350cbd8a89a64ff54 | ralphtatt-IW/BrIW | /src/classes.py | 4,246 | 3.578125 | 4 | class Person:
# name
def __init__(self, person_id, first_name, second_name, team, preference):
self.person_id = person_id
self.first_name = first_name
self.second_name = second_name
self.full_name = first_name + " " + second_name
self.preference = preference
self.... |
05e1c4a7d673effc7d67b5c62674aae381ebf97b | saylorstarks/madlib-generator | /madlib generator.py | 1,677 | 3.96875 | 4 | import random
#User input
verbs = input('Number of verbs: ')
adverbs = input('Number of adverbs: ')
nouns = input('Number of nouns: ')
adjk = input('Number of adjectives: ')
f = open("adj.txt", "r") #opens word list
m = f.readlines() #reads amount of lines in file
l = []
n = []
for x in range(int(adjk)): #how man... |
601a03ddfc39a516ca623b9f75323f7e00676019 | ghostghost664/CP3-Chinnawat-Pitisuwannarat | /Excercise73_Chinnawat_P.py | 628 | 3.9375 | 4 | menu1={"ข้าวไข่ข้น":35,"ข้าวไก่ย่างเทอริยากิ":45,"ยากิโซบะ":65,"ซาชิมิ":89}
menuList = []
print(menu1)
while True :
menuName = input("please Enter to Menu")
if(menuName.lower() == "exit"):
break
else:
menuList.append([menuName,menu1[menuName]])
def showBill():
print("------... |
826f00c9d48592bc7403b597ef7f5eda59b611ec | AidysM/Skillfactory-learning-mongush | /B2/pythonProject1/format.py | 190 | 3.8125 | 4 | day = 14
month = 2
year = 2012
print("%d.%02d.%d" % (day, month, year))
# 14.02.2012
print("%d-%02d-%d" % (year, month, day))
# 2012-02-14
print("%d/%d/%d" % (year, day, month))
# 2012/14/2 |
1fe48d3656b9437f43b79afa4ba5d9f2ffe13c2f | adamfitzhugh/python | /kirk-byers/Scripts/Week 1/exercise3.py | 942 | 4.375 | 4 | #!/usr/bin/env python
"""Create three different variables: the first variable should use all lower case characters with
underscore ( _ ) as the word separator. The second variable should use all upper case characters
with underscore as the word separator. The third variable should use numbers, letters, and
undersco... |
d925d4b637199ad159b36b33dcb0438ccca0f95a | adamfitzhugh/python | /kirk-byers/Scripts/Week 5/exercise3.py | 1,788 | 4.15625 | 4 | """
Similar to lesson3, exercise4 write a function that normalizes a MAC address to the following
format:
01:23:45:67:89:AB
This function should handle the lower-case to upper-case conversion.
It should also handle converting from '0000.aaaa.bbbb' and from '00-00-aa-aa-bb-bb' formats.
The function should have one... |
d6c95ea4b6f65152328bf1b0e70846fbc9a38e07 | adamfitzhugh/python | /kirk-byers/Scripts/Week 4/week_4_lab.py | 7,463 | 3.65625 | 4 | Exercises
Reference code for these exercises is posted on GitHub at:
https://github.com/ktbyers/pynet/tree/master/learning_python/lesson4
1. Create a dictionary representing a network device. The dictionary should have key-value pairs representing the 'ip_addr', 'vendor', 'username', and 'password' fields.... |
2c9a6858ef76026d57e96ce85724e7c062e657d5 | nileshmahale03/Python | /Python/PythonProject/5 Dictionary.py | 1,487 | 4.21875 | 4 |
"""
Dictionary:
1. Normal variable holds 1 value; dictionary holds collection of key-value pairs; all keys must be distinct but values may be repeated
2. {} - curly bracket
3. Unordered
4. Mutable
5. uses Hashing internally
6. Functions:
1. dict[] : returns value at specified index
2. len() ... |
51f13de4475c9679caadaf953d2ff8f5401b2996 | Aitous/CS229 | /ps2/ps2/src/stability/stability_modified.py | 3,463 | 4.03125 | 4 | # Important note: you do not have to modify this file for your homework.
import util
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def calc_grad(X, Y, theta):
"""Compute the gradient of the loss with respect to theta."""
count, _ = X.shape
probs = 1. / (1 + n... |
1c3d6f236781497b59ec7c71caa09c4fd0041b0c | Dextro1597/Caesar-Cipher | /caeser.py | 709 | 4.0625 | 4 | #code by Ahad Patel
plaintext = input('Enter the plain text:-')
alphabets = 'abcdefghijklmnopqrstuvwxyz'
alphabetc = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
cipher = ''
dicipher = ''
key = input('Enter the key Size:-')
for c in plaintext:
if c in alphabets:
cipher += alphabets[(alphabets.index(c)+int(key))%(len(alphabets))]
... |
bf0707a538786f1cb851b7033e84375253eb7149 | Miguel-Evans-Yikes/Python-projects | /treinamento_aleatório_python/DATABASE_MANAGER/database_manager.py | 960 | 3.671875 | 4 | import sqlite3
from sqlite3 import Error
import os
path = os.path.dirname(__file__)
sql_insert_query = """INSERT INTO users(NOME,SENHA,IDADE,ENDEREÇO,ESTATUS,CONTRATAÇÃO) VALUES (?,?,?,?,?,?)"""
sql_read_query = """SELECT * FROM users WHERE NOME==? AND SENHA==?"""
def sql_update_query():
return """ ""... |
09b9dc627bd61e2fce91e204fcdbc2dd572479c8 | tedrickzhu/Algrithm_test | /jianzhioffer/testMovingCount.py | 1,443 | 3.5625 | 4 | #encoding=utf-8
#author:Tedrick
#software:Pycharm
#file:testMovingCount.py
#time:2019/3/21 下午8:37
# -*- coding:utf-8 -*-
class Solution:
def movingCount(self, threshold, rows, cols):
# write code here深度优先遍历
if threshold<0:
return 0
i = 0
j = 0
visited = [(0, 0)]
... |
ed1f3aa858237333a0cb6315d3ef34eed3996a60 | tedrickzhu/Algrithm_test | /SortAlgrithm/ChooseSort.py | 1,066 | 3.828125 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 18-8-22
# @Author : zhengyi
# @File : ChooseSort.py
# @Software: PyCharm
'''
算法描述
n个记录的直接选择排序可经过n-1趟直接选择排序得到有序结果。具体算法描述如下:
初始状态:无序区为R[1..n],有序区为空;
第i趟排序(i=1,2,3…n-1)开始时,当前有序区和无序区分别为R[1..i-1]和R(i..n)。
该趟排序从当前无序区中-选出关键字最小的记录 R[k],将它与无序区的第1个记录R交换,
使R[1..i]和R[i+1... |
b37fac91f3f75eaaa6cb47eb988686623d35f041 | ilyxych96/Python-basics-and-applications | /3_2.py | 963 | 3.828125 | 4 | '''
3.2.1 Вашей программе на вход подаются три строки s, a, b, состоящие из строчных латинских букв.
За одну операцию вы можете заменить все вхождения строки a в строку s на строку b.
'''
s = input()
a = input()
b = input()
i = 0
while s.count(a) != 0:
if i < 1000:
s = s.replace(a,b)
i ... |
8cac3e2dcad66b5914692ec582dc22b9654fc560 | dylanhudson/notes | /hashid.py | 19,231 | 3.53125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 18 21:46:49 2019
@author: dylan
"""
# -*- coding: utf-8 -*-
"""
extract-hashes.py: Extracts hashes from a text file.
Version 0.3 - Nov/2014
Author: Daniel Marques (@0xc0da)
daniel _at_ codalabs _dot_ net - http://codalabs.net
Modified by Dylan in N... |
061dc408953410b0152b5fb0baa11132a8ba240d | Hinks/beaver_coffee_manager_app | /src/cru/stock.py | 5,262 | 3.59375 | 4 | from datetime import datetime
from toolz.dicttoolz import assoc
def read(db, shop_id):
shop = fetch_shop(db, shop_id)
if shop:
return shop.get('stock_quantities')
else:
return 'error, no shop with that id exists.'
def update(db, shop_id):
date_input_str = input('Enter the date of tod... |
eb70cb40c86d3e85d4b6ef57db6d9678daa5645a | AjithKalarikal/EXERCISM | /pangram.py | 154 | 3.5625 | 4 | def is_pangram(sentence):
a = 'abcdefghijklmnopqrstuvwxys'
if len(set(a)-set(sentence.lower())) == 0:
return True
else:
return False
|
e3f5d349f45c8d01cd939727a9bbd644ddaa0bdd | changjunxia/auto_test_example1 | /test1.py | 228 | 4.125 | 4 | def is_plalindrome(string):
string = list(string)
length = len(string)
left = 0
right = length - 1
while left < right:
if string[left] != string[right]:
return False
left += 1
right -= 1
return True |
a1a7e5faad35847f22301b117952e223857d951a | nestorsgarzonc/leetcode_problems | /6.zigzag_convertion.py | 1,459 | 4.375 | 4 | """
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conve... |
26a980f33d77005abdc68ba2b089b6bfa95b722e | ajboloor/python-simple | /simple-weather/simple-weather.py | 1,478 | 3.765625 | 4 |
def get_weather(location_name):
internet_status = 0
try:
import httplib
except:
import http.client as httplib
conn = httplib.HTTPConnection("www.google.com", timeout=5)
try:
conn.request("HEAD", "/")
conn.close()
internet_status = 1
except:
conn.c... |
a555b29adc4683036d4b5858cd12dd3b87f29f57 | llNeeleshll/Python | /section_4/if_statement.py | 170 | 4.0625 | 4 | name = input("What is your name?")
age = int(input(f"How old are you, {name}"))
if age >= 18:
print("You can vote")
else:
print(f"Come back in {18 - age} years") |
e2349b63116bb7f3e83aa436c41175efda4a8d9d | llNeeleshll/Python | /section_3/string_play.py | 290 | 4.15625 | 4 | text = "This is awesome."
# Getting the substring
print(text[8:])
print(text[0:4])
# text[start:end:step]
print(text[0:14:2])
print(text[0::2])
# Reversing the string
print(text[::-1])
# Print a word 10 times?
print("Hello " * 10)
print("Hello " * 10 + "World!")
print("awe" in text) |
013d498ccae9199fd92b4dd4b3c45a01f6808f19 | DuncanHu/Machine-learning-practice-notes | /MachineLearning_notes/KNN/kNN.py | 1,514 | 3.5625 | 4 | '''
机器学习实战——KNN基础代码实现
'''
from numpy import *
import numpy as np
import operator
def createDataSet():
group = array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]]) # 特征矩阵
labels = ['A', 'A', 'B', 'B'] # label向量
return group, labels
# 参数:inX:测试数据 dataSet:特征矩阵 labels:label向量 k:k个近邻
def classify0(inX, dataSet, labels... |
b0f6c27a6fa3c99c5612d321f34b67ba5201a22b | Jamie-Matthews-AU/MILPE | /interpreter_brainfuck/Brainfuck_Classes.py | 6,748 | 3.5 | 4 | import io
import queue
class Brainfuck:
def __init__(self, instructions, tape=None, tape_pointer=0, behavior=None, instruction_pointer=0):
"""
:type tape: list[int]
the tape of the program
:type instructions: list["str"]
queue of instructions, left to right
... |
21f46522996d73fbe2665ee02ad39ddae390cebb | omeinsotelo/holbertonschool-higher_level_programming | /0x0A-python-inheritance/4-inherits_from.py | 221 | 3.625 | 4 | #!/usr/bin/python3
def inherits_from(obj, a_class):
""" Function that returns True if the object is an instance
of a class that inherited
"""
return not (type(obj) == a_class) and isinstance(obj, a_class)
|
45af3c549687103a8990f13431304a62dbd1e2e4 | omeinsotelo/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/tests/6-max_integer_test.py | 1,079 | 3.78125 | 4 | #!/usr/bin/python3
"""Unittest for max_integer([..])
"""
import unittest
max_integer = __import__('6-max_integer').max_integer
class TestMaxInteger(unittest.TestCase):
def testing_max_integer(self):
"""
testing with assetEquals the max_integer function
self: object
"""
self... |
8d2a90308ce64f945bf74ae562a32596722b4fb1 | omeinsotelo/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/8-uppercase.py | 229 | 3.953125 | 4 | #!/usr/bin/python3
def uppercase(str):
for i in range(0, len(str)):
upp = ord(str[i])
print("{:c}".format(upp - 32 if upp > 95 else upp), end="")
print("{:s}".format("\n"), end="")
|
4a2238f4157019e743a17d11394c038650ac306e | ragona/cryptopals_python3 | /c36.py | 3,174 | 3.5 | 4 | from pals.srp import SRPClient, SRPServer, SRPSession
I = 'me@here.com'
P = 'p@$$W0RD'
#create client and server
server = SRPServer()
client = SRPClient(I, P)
#create a user on the server
server.add_user(I, P)
#create a session
session = SRPSession(client, server)
#do the initial handshake
session.handshake()
#valid... |
2ed5d0bd93ebf60d5eb1944a5b5a777865370fa3 | ragona/cryptopals_python3 | /c40.py | 2,530 | 3.8125 | 4 | '''
why in god's name does this work
I gotta go back to math class
what is a modular inverse even
I need to go redo c39 and focus on egcd + invmod
edit 6/12:
Oh, this works because with an exponent of 3 RSA
is just encryption is just cubing a number mod
the public encryption modulus:
c = m ** 3 % n
... and th... |
db9ba254ca8d1f467239ce834c65fc6e5f31946d | vigneshsadasivam/player | /83.py | 117 | 3.671875 | 4 | n=int(input("enter n"))
a=[]
for i in range(0,n):
b=int(input())
a.append(b)
s=a[0]
for i in a:
s=s|i
print(s)
|
20c1c6d822336fab9a8b7c36f326ecbbd8b7d016 | vigneshsadasivam/player | /74.py | 104 | 3.796875 | 4 |
n=input("Enter the n:")
for i in n:
if(n.count(i)>1):
print("yes")
break
else:
print("no")
|
9f084c12bb463631ecdf20e2a97a4ec33595ea82 | Vadim91200/BlackJack | /ISN - Black Jack.py | 5,234 | 3.59375 | 4 | # -*- coding: utf-8 -*-
from random import *
jeu = [11, 11, 11, 11]
#Création de la liste jeu
def ajout_carte(main):
a = choice(jeu) #On sélectionne aléatoirement une carte dans la liste 'jeu'
main.append(a) #On ajoute cette carte a la liste 'main'
jeu.remove(a) #On retire cette carte de la liste 'je... |
a90b95f96d4da05f81a5277941dcfcebfc006bdf | GooseHuang/Udacity-Data-Structures-Algorithms-Nanodegree-Program | /P2 Problems vs. Algorithms/problem_6.py | 894 | 4.03125 | 4 | def get_min_max(ints):
"""
Return a tuple(min, max) out of list of unsorted integers.
Args:
ints(list): list of integers containing one or more integers
"""
if not ints:
return (None,None)
min_number = ints[0]
max_number = ints[0]
for x in ints[1:]:
if x > max_num... |
6dd2295e2778737e6139619527dc0135893b880b | alinadjar/SparkRepo | /Chapter-9/Chapter-9.py | 5,822 | 4.125 | 4 | # Code for Chapter 9
# Example 9-5
from pyspark.sql import SparkSession
spark = SparkSession \
.builder \
.appName("Python Spark SQL basic example") \
.config("spark.some.config.option", "some-value") \
.getOrCreate()
# Example 9-8
from pyspark.sql import Row, SQLContext
config = ... |
2690856645451099474cbed49d688a0fecd653f4 | KaviyaMadheswaran/laser | /infytq prev question.py | 408 | 4.15625 | 4 | Ex 20)
1:special string reverse
Input Format:
b@rd
output Format:
d@rb
Explanation:
We should reverse the alphabets of the string by
keeping the special characters in the same position
s=input()
alp=[]
#index of char
ind=[]
for i in range(0,len(s)):
if(s[i].isalpha()):
alp.append(s[i])
else:
ind.append(i)
rev=alp... |
50e3bc5493956708bf1897a74600cd9639777bf8 | KaviyaMadheswaran/laser | /w3 resource.py | 403 | 4.1875 | 4 | Write a Python program to split a given list into two parts where the length of the first part of the list is given. Go to the editor
Original list:
[1, 1, 2, 3, 4, 4, 5, 1]
Length of the first part of the list: 3
Splited the said list into two parts:
([1, 1, 2], [3, 4, 4, 5, 1])
n=int(input())
l=list(map(int,input().s... |
fbcf1c36b34a8565e0153b403fbcb185782890ba | KaviyaMadheswaran/laser | /w3 resource6.py | 392 | 4.15625 | 4 | Write a Python program to flatten a given nested list structure. Go to the editor
Original list: [0, 10, [20, 30], 40, 50, [60, 70, 80], [90, 100, 110, 120]]
Flatten list:
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120]
l=[0, 10, [20, 30], 40, 50, [60, 70, 80], [90, 100, 110, 120]]
l1=[]
for i in l:
if(isinstan... |
5539d4170fa7ecc1a9a97ba4aa3ed2f23650bd1a | KaviyaMadheswaran/laser | /Birthday Cake candle(Hackerrank).py | 490 | 4.125 | 4 | Output Format
Return the number of candles that can be blown out on a new line.
Sample Input 0
4
3 2 1 3
Sample Output 0
2
Explanation 0
We have one candle of height 1, one candle of height 2, and two candles of height 3. Your niece only blows out the tallest candles,
meaning the candles where height = 3. ... |
5f8af1379485f30152ed43f8c180373a4e9982c5 | KaviyaMadheswaran/laser | /Fibonacci.py | 92 | 3.78125 | 4 | n=int(input("enter num"))
a=0
b=1
for i in range(1,n+1):
print(a)
s=a+b
a=b
b=s
|
f21306c8b839de0d69c1e259b37b8026bfc79e8c | andreagibb93/MSc | /python/LibrarySystems/library_member.py | 1,901 | 3.765625 | 4 | class LibraryMember:
def __init__(self, name, user_id, messages):
self.name = name
self.user_id = user_id
self.borrowed = []
self.messages = messages
# This class represents a library member
def get_name(self):
return self.name
# Returns the library member name
... |
229f0b4c27d60e5e4ef6f542f449d82a2f0062a2 | andreagibb93/MSc | /python/pairsTask.py | 1,199 | 3.765625 | 4 | class Assignment:
def _init_(self, assignment1, assignment2):
self.assignment = assignment1
self.assignment = assignment2
class Module:
def __init__(self, module1, module2, module3):
self.module1 = module1
self.module2 = module2
self.module3 = module3
class Student:
... |
81d89825a99c76cf2fc1e2d6a2c29846a8081e55 | andreagibb93/MSc | /python/LibrarySystems/book.py | 1,755 | 4.03125 | 4 | class Book:
def __init__(self, isbn, library_member, book_damages, title, author):
self.isbn = isbn
self.library_member = library_member
self.book_damages = book_damages
self.title = title
self.author = author
# This class represents a book
def get_isbn(self):
... |
ff8506ea8c03e47441af4d47771104d1b9ddf850 | adrianyi/FacialFilter | /util.py | 6,990 | 3.890625 | 4 | import numpy as np
import cv2 # OpenCV 3
#from PIL import Image
def load_image(image_path):
'''
Load image from file
Load image file from file_dir, returns color_image and gray_image
Args:
image_path: A string of a path to an image
(i.e. '/example_images/test_image_1.jpg')
Re... |
d2e92863159f613bf175485cfb7a9f624f8962ff | ClauMaj/pyHomework | /printSquare1and2.py | 117 | 3.859375 | 4 | # Ex. 9
i = 1
while (i <=5):
print("*****")
i +=1
# Ex. 10
i = int(input("How big is the square? "))
|
6c37d6800d0df00d5c38e1c319a462f810628a74 | ClauMaj/pyHomework | /coins.py | 172 | 4.0625 | 4 |
n = 0
print(f"You have {n} coins")
answer = "yes"
while answer == "yes":
n += 1
print(f"You have {n} coins")
answer = input("Do you want another (yes/no)? ")
|
84341edeb49283cc802b891920ba2fa76a8a264c | ClauMaj/pyHomework | /celToFahr.py | 218 | 3.9375 | 4 |
# week 1 Tuesday Homework
# Ex. 6
temp = float(input('Temperature in C? '))
cel = temp * 9 / 5 + 32
if cel == int(cel):
print(f'Temperature in F is: {cel}')
else:
print(f'Temperature in F is: {int(cel)}')
|
ddfc5bca9db935f7efff39b4597726dd9de208ec | ClauMaj/pyHomework | /Fibonacci.py | 591 | 4.03125 | 4 |
# 1. Fibonacci recursive
# def recur_fibo(n):
# if n <= 0:
# print("Please enter a number > 0")
# exit()
# elif n == 1:
# return 0
# elif n == 2:
# return 1
# else:
# return(recur_fibo(n-1) + recur_fibo(n-2))
# print(recur_fibo(10))
# 2. Fibonacci if
def fi... |
3898fed3bff0899f6e6354470a5dd6ff967546db | bradleybossard/python-computer-vision | /pcv_1_3_invert_image.py | 290 | 3.765625 | 4 | """
Example for inverting an image. PCV 1.3, Graylevel transforms.
"""
from PIL import Image
from numpy import *
# Read image into numpy array
im = array(Image.open('empire.jpg').convert('L'))
im2 = 255 - im #invert image
pil_im = Image.fromarray(im2)
pil_im.save('empire_inverted.jpg')
|
a5ed73ac78f673fa965b551bef169860cd38a658 | timclaussen/Python-Examples | /OOPexample.py | 441 | 4.25 | 4 | #OOP Example
#From the simple critter example, but with dogs
class Dog(object):
"""A virtual Dog"""
total = 0
def _init_(self, name):
print("A new floof approaches!")
Dog.total += 1 #each new instance adds 1 to the class att' total
self.name = name #sets the constructor inp... |
bcf588a8a3e17d73390dd4e637c91780df1f0ff8 | simonet85/Python-training | /LCM/pgcd.py | 131 | 3.5 | 4 | # Algorithme d'Euclide pour le pgcd
def pgcd(a,b) :
while a%b != 0 :
a, b = b, a%b
return b
print(pgcd( 120, 36)) |
6a41079dfde72348c4db89b1ab7270d3b5509b30 | gkotian/easy-countdown | /easy-countdown/easy-countdown.py | 5,205 | 4 | 4 | #!/usr/bin/env python
################################################################################
#
# Description:
# ------------
# A simple yet flexible countdown timer for the Linux command line.
#
# Usage:
# ------
# $> easy-countdown <time/time-duration>
#
#################################... |
3919094c9ab53a108ed200729d9baabf00282ff0 | rengokantai/orintmpyprogpj1 | /longestpalin.py | 183 | 3.859375 | 4 | __author__ = 'Hernan Y.Ke'
import scrabble
longest=""
for word in scrabble.wordlist:
if list(word) == list(word[::-1]) and len(word) > len(longest):
longest=word
print(longest) |
58157c920d37f6ea9a66702030b3dc56b116361d | aswin191993/python_think | /dictionary/homophone.py | 467 | 3.578125 | 4 | def homophone(filename):
wlist=open(filename).read().split()
d=pronounce.read_dictionary('c06d')
for word in wlist:
if len(word) == 5 and word in d:
mword=modify(word,0)
if mword in d and d[mword] == d[word]:
mword=modify(word,1)
if mword in d and d[mword] == d[word]:
print word
def modify(wor... |
ba138b4f7e98e96adf4ab635d3999b07c6ad29f1 | aswin191993/python_think | /string/ex4.py | 113 | 3.625 | 4 | name='banana'
def fnctn(name):
count=0
for n in name:
if 'a' in n:
count += 1
print count
fnctn(name)
|
0ec961356ccb99cebe36f3cc97e06a1c484409a6 | aswin191993/python_think | /cls_methods/3.py | 215 | 4.03125 | 4 | class Point(object):
""" representation of a point in 2D space """
def __init__(self,x=0,y=0):
self.x=x
self.y=y
def __str__(self):
return '(%d,%d)'%(self.x,self.y)
p=Point()
print p
q=Point(2)
print q
|
967cf0fe121fb19daf257eab1587929b3230d74a | aswin191993/python_think | /list/remove_dup.py | 207 | 3.84375 | 4 | a='aswin','ravi','appu','arun','aswin','ravi'
def remove_dup(a):
s=list(a)
l=len(s)-1
r=range(l)
p=[]
for i in r:
if s[i] not in p:
p.append(s[i])
print "orginal list:",a
print p
remove_dup(a)
|
b98b7599e5ceaa89394233ee6b18cefa1af37770 | owenyi/Algorithm | /mergeSort.py | 1,812 | 3.859375 | 4 | def mergeSort(a, l, r):
if r > l:
m = int((r+l)/2)
mergeSort(a, l, m)
mergeSort(a, m + 1, r)
merge(a, l, m, r)
def merge(a, l, m, r):
i, j, k = l, m + 1, l
while i <= m and j <= r:
if a[i] < a[j]:
b[k] = a[i]
k += 1
i += 1
... |
2ba56012cdfecea7cd1776477948628ec75b87e2 | owenyi/Algorithm | /radixSort.py | 1,159 | 3.828125 | 4 | def radixSort(a, n, m, Q):
for k in range(1, m + 1):
for i in range(1, n + 1):
kd = digit(a[i], k)
enqueue(Q[kd], a[i])
p = 0
for i in range(10):
while Q[i] != []:
p += 1
a[p] = dequeue(Q[i])
def digit(data, k):
l = 1
... |
c36c2c55eb41eb988a49b183578ba550a9dba4ac | jsacoba/pai789_finalproject | /script5_analyze/5.1 analysis_data/analysis_data.py | 1,159 | 3.734375 | 4 | # 1. Import 'pandas' module.
import pandas as pd
# 2. Read input file.
analyze = pd.read_csv('combined_clean.csv')
# ***A. Extracting countries with the same Risk Exposure Index.***
# 3. Create column 'dup' in 'analyze' to select duplicates in 'Exposure' column.
analyze['dup'] = analyze.Exposure.duplicated(keep=F... |
165d874a6d06feecf910d718f91eb77ef9501884 | snyderks/advent-solutions | /Day6.py | 909 | 3.953125 | 4 | # Day 6: http://adventofcode.com/2016/day/6
# Problem: Given many lines of the same length, determine the message
# by finding the most frequent letter in each column.
from collections import Counter
f = open("inputs/Day6.txt", "r")
columns = []
for line in f:
if len(columns) is 0:
for char in line:
... |
b8f1b4efb1ccf1b41ebb087b207acae1663ac4d4 | snyderks/advent-solutions | /Day18.py | 1,506 | 3.5 | 4 | from collections import Counter
startRow = ".^.^..^......^^^^^...^^^...^...^....^^.^...^.^^^^....^...^^.^^^...^^^^.^^.^.^^..^.^^^..^^^^^^.^^^..^"
rowLength = len(startRow)
trap = "^"
safe = "."
def check(left, center, right):
if center is trap:
if left is trap and right is safe:
return trap
... |
479c6b3b45c6ef1abac43a25ae74616a9708b807 | snyderks/advent-solutions | /Day16.py | 711 | 3.828125 | 4 | import copy
def swap(char):
if char is "1":
return "0"
else:
return "1"
def dragon(data, length):
a = data
while len(a) < length:
b = a
b = b[::-1]
b = "".join(map(lambda c: swap(c), b))
a = a + "0" + b
return a
def check(data):
result = ""
... |
5f705c652f90bf17c55d1958b5760213e99cc3a6 | nikkisquared/OpenMPT-Music-Maker | /config.py | 1,450 | 3.75 | 4 | #!/usr/bin/env python
from __future__ import print_function
"""Handles parsing and correction of config file for the program"""
import ConfigParser
def check_boolean(section, variable, value, default=False):
"""Check that a config variable is a proper boolean"""
if value in (0, 1, "True", "False"):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.