blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
faa2d019e854b1af74bc13bbfbb1a98400c5196f | mg-blvd/Kattis_Solutions | /EarlyWinter.py | 368 | 3.78125 | 4 | import sys
years, months = input().split()
years = int(years)
months = int(months)
past_years = input().split()
found = False
for i in range(len(past_years)):
if months >= int(past_years[i]):
print(f'It hadn\'t snowed this early in {i} years!')
found = True
break
if not found:... |
ae34c4677dc60af22e2cc55127cd986c1cc49f66 | Guluna/HackerRank-Practice | /Warm-Up Challenges/Repeated String/Hackerrank4.py | 938 | 3.5 | 4 | import math
import os
import random
import re
import sys
os.environ['OUTPUT_PATH'] = 'junk.txt'
# Complete the repeatedString function below.
def repeatedString(s, n):
str_len = len(s)
repetitions = n//str_len # finding out how many times is a string s repeated
remainder = n%str_len
total_a = 0
... |
2c02c483bc8c4c4b0e902304c1f76eb999e30fb1 | Guluna/HackerRank-Practice | /Palindrome.py | 883 | 4.09375 | 4 | # -*- coding: utf-8 -*-
def toChars(s):
"""
s: string that might include punctuation, spaces etc along with alphabets (both upper & lower case)
return: a string of lowercase characters
"""
s = s.lower()
new_s = ''
for i in s:
if i in 'abcdefghijklmnopqrstuvwxyz':
... |
5171062d25a471d40478cdc2f0b6400e7abff449 | arunachalamb/codebusters | /caesar.py | 1,621 | 3.75 | 4 | """
Encrypt and decrypt using caesar cipher for English alphabet
"""
import sys
import argparse
from nltk.corpus import wordnet
ap = argparse.ArgumentParser()
ap.add_argument("-e", "--e", help="enter string to be encrypted")
ap.add_argument("-d", "--d", help="enter string to be decrypted")
ap.add_argument("-k", "--k",... |
62fb32a032bfb606bf21f1d70a521cf541e19b81 | mtj57295/snakegame | /test.py | 2,070 | 3.65625 | 4 | import sys
sys.dont_write_bytecode = True
from CreateBoard import Board
from SolveBoard import Graph
from Graphics import Graphics
def initBoard():
value = int(raw_input('Enter number of rows and cols (5 min/ 30 max): '))
if value < 5:
print 'Below 5'
exit()
numObstacles = int(raw_input('En... |
1bbf31ea870a72ceaeaaa9b735f61c37cc4dfa76 | duilee/workspace | /Algorithms/dict_hashmap/ransome_note.py | 606 | 3.5625 | 4 | # Complete the checkMagazine function below.
# https://www.hackerrank.com/challenges/ctci-ransom-note/problem
def checkMagazine(magazine, note):
word_dict = {}
for a_word in magazine:
if a_word in word_dict:
word_dict[a_word] = word_dict[a_word] + 1
else:
word_dict[a_wor... |
8500624232cdb1b8b2a9defe661e618a81f7ad22 | duilee/workspace | /Algorithms/array/new_year_chaos_bubblesort.py | 1,384 | 3.609375 | 4 | # Complete the minimumBribes function below.
# https://www.hackerrank.com/challenges/new-year-chaos/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=arrays&h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen
def minimumBribes(q):
nPlus = 0
Chaos = False
Done = len(... |
f02dd19b9961096529cb58166741f2611a8148a9 | duilee/workspace | /Algorithms/sorting/largest_number.py | 318 | 3.84375 | 4 | # https://programmers.co.kr/learn/courses/30/lessons/42746
def solution(numbers):
numbers = list(map(str, numbers))
# use key to sort the numbers in string
numbers.sort(key= lambda x: x*3, reverse=True)
# convert to 0 for the cases when 0 is in front of the string
return str(int(''.join(numbers))) |
f2b94fba68690a16f7c27d9ada4a5038aaa8dd6a | duilee/workspace | /Courseworks/CS88_Computational_Structures/Hw/hw07/hw07.py | 3,687 | 3.5 | 4 | # Abstractions
full_roster = {
"Manny Machado" : "Dodgers",
"Yasiel Puig" : "Dodgers",
"Aaron Judge" : "Yankees",
"Clayton Kershaw" : "Dodgers",
"Giancarlo Stanton" : "Yankees"
}
full_stats = {
"Manny Machado": ["SO", "1B", "3B", "SO", "HR"],
"Yasiel Puig": ["3B", "3B", "1B", "1B", "SO"],... |
a47f23aa5e32efabf4d59bb6c0b35262bf8e0c1b | wendykan/python_algorithm | /running_median.py | 1,487 | 3.890625 | 4 |
import heapq
def get_median(input_list):
min_heap = [] # stores the upper half
max_heap = [] # stores the lower half
medians = []
heapq.heappush(max_heap, min(input_list[0], input_list[1]))
heapq.heappush(min_heap, max(input_list[0], input_list[1]))
for item in input_list[2:]:
if i... |
15d0e0b6a2b6f371c5811d3a54245b7d9d17a4b3 | uriybashkirov/CHALLENGE-ACCEPTED | /Labor2/Вариант 69.py | 1,124 | 3.9375 | 4 | import math
# -*- coding: utf-8 -*-
print ('Введите x = ')
x = int(input())
print ('Введите a = ' )
a = int(input())
print ('Введите: N = 1 для нахождения переменной G. N = 2 для нахождения переменной F. N = 3 для нахождения переменной Y.')
n = int(input())
if n == 1:
Y = ((9 *(7 *a * a + 39 * a * x + 20 * x... |
449a672fe4337af1a35dda8266f0709cd21569db | Miker69/Password_generation | /templates/generator/1.py | 130 | 3.609375 | 4 | import random
chars = list('abcdefghijklmnopqrstuvwxyz')
chars = ''.join(chars)
chars = chars + chars.upper()
print(list(chars))
|
2d7c3d1611934978090126b6fe7daa6b8f2bc116 | Aledutto23/Sistemi-e-Reti | /tartaruga.py | 1,258 | 3.765625 | 4 | from turtle import *
pen = Turtle()
window = Screen()
lung = 50
pen.home()
def controllo():
if (pen.ycor() + lung) > window.window_height()/2:
return 1
elif (pen.ycor() - lung) < -1 * window.window_height() / 2:
return 2
elif (pen.xcor() + lung) > window.window_width()/2:
... |
64a6b84542292bb661db33ff76c42f23f654b1f7 | Aledutto23/Sistemi-e-Reti | /es_liste_nuovo.py | 156 | 3.640625 | 4 | lista = [1,2,3,4,1,6,2,8]
for i, n in enumerate(lista):
for j, m in enumerate(lista):
if n == m and (i>j):
print("Doppione")
|
11a37e14aa3c929978a7e94babe9195c73e07795 | Ovsienko023/Tasks-from-Stepik-Coursera | /Test/1_task.py | 169 | 3.765625 | 4 | def division_by_zero(num):
try:
answer = num / 0
except ZeroDivisionError:
print("Делить на ноль нельзя!")
division_by_zero(7) |
f8b71a4c37354075b94555aa43d02ae8a3001af5 | Justinfan827/music-gif | /backend/lyricScraper.py | 1,045 | 3.625 | 4 | import urllib
import bs4
import os.path
def scrape_lyrics(song_filename):
song_title = os.path.splitext(song_filename)[0] # remove extension from filename to get song title
song_search = song_title + ' lyrics' # create the words to be searched in Bing
url = "https://www.bing.com/search?" + urllib.urlenc... |
4898602459ffebf367da2e4d3a45550eab6791f6 | lucaslinpeihuang/python_study | /basic/operator.py | 372 | 3.75 | 4 | # -*- coding: utf-8 -*-
sal = 300
comm = 20
total = sal + comm
print(total)
# 1. // 返回商的整数部分
# 2. % 返回余数
# 3. **幂运算
print(sal//comm)
print(sal%comm) #模,判断是不是能整除就靠它
print(comm**4)
if sal>comm:
print('ok')
if sal>comm or sal>2000:
print('good')
if not sal>2000:
print('hehe')
|
bca141a0fec6892d21c28fd92297ce83c7d721bf | SingularReza/ChanImageDownloader | /chanwalls.py | 980 | 3.578125 | 4 | import os
import requests
import urllib.request
from bs4 import BeautifulSoup
# takes the url for the thread you wanted to download the images from
# make sure that the url has the protocol thingy as the prefix
thread_url = input("Enter the url for the thread: ")
response = requests.get(thread_url)
soup =... |
122bc50827cd50b464163b6a66bbc9065884d458 | Rishi05051997/Python-Notes | /2-CHAPTER/02_operators.py | 765 | 4.375 | 4 | a = 3
b = 5
# Arithmatic Operators
print("The value of 3+5 is ", a+b)
print("The value of 3-5 is ", a-b)
print("The value of 3/5 is ", a/b)
print("The value of 3*5 is ", a*b)
# Assignment Operators
a = 34
a +=2
print("The value of a+=2 is ",a)
a *=2
print("The value of a*=2 is ",a)
a /=2
print("The value of a /=2 is ... |
810c6ef1aaac01ef6e9c087b43be152bb7be6f44 | Rishi05051997/Python-Notes | /7-CHAPTER/05_range_function.py | 304 | 3.8125 | 4 | list = [
{
"id":1,
"name":"Vrushabh DHatrak",
"email":"v@gmail.com"
},
{
"id":2,
"name":"Vrushabh DHatrak",
"email":"v@gmail.com"
},
{
"id":3,
"name":"Vrushabh DHatrak",
"email":"v@gmail.com"
},
]
for i in range(len(list)... |
ede4f60a84df80cda8efd48eb1fb43c987bf9573 | Rishi05051997/Python-Notes | /9-CHAPTER/1-files.py | 256 | 3.609375 | 4 | # Use open function to read the content of a file
file = open('D:\Python-Notes\Python-Notes\9-CHAPTER\\file.txt', 'r') # by default the mode is read
# data = file.read()
data = file.read(5) # reads first 5 characters from the file
print(data)
file.close()
|
b646e8cc65b7aa579d94e6f1c56ce7734eaaa22d | Rishi05051997/Python-Notes | /2-CHAPTER/Practice/06_square.py | 84 | 3.890625 | 4 | a = int(input('Enter a number'))
b = a * a
print('The square of a number is ', b) |
b401f0df3c8a2cca7ae9877cb1500f93a5e3180e | Rishi05051997/Python-Notes | /3-CHAPTER/Practice/02_letter.py | 580 | 4.5 | 4 | # a = input('Enter your name ')
# b = input("Enter date ")
# letter = f''' Dear {a}
# you are selected
# Date:{b}'''
# print(letter)
### Another Approach
letter = ''' Dear <|NAME|>
Greeting from ABC conding house. I am happy to tell you about your selcection
You ar... |
530a5ebf06e995e9bb102f5d951313d74dab6e05 | Rishi05051997/Python-Notes | /7-CHAPTER/PRACTICE/08-table-reverse.py | 176 | 4.125 | 4 | num = int(input("Enter a no to print table in reverse order: "))
table = []
for i in range(1, 11):
table.append(i*num)
table.reverse()
print(table)
# print(table.reverse()) |
47ff46368fc05dd5f3b8f8dcf189bd27295c913b | Rishi05051997/Python-Notes | /11-CHAPTER/5-super.py | 1,002 | 3.921875 | 4 | class Person:
country = "India"
def __init__(self):
print("Initializing Person .....\n")
def takeBreath(self):
print("Im breathing....")
class Employee(Person):
company = "Honda"
def __init__(self):
super().__init__()
print("Initializing Employee .....\n")
... |
db5af97058507210f8917a7ccdcea824f448a3b1 | Rishi05051997/Python-Notes | /8-CHAPTER/PRACTICE/8-strip.py | 247 | 3.890625 | 4 | this = " Vrushabh is a god "
print(this)
print(this.strip())
def removeSpaces(string, word):
newStr = string.replace(word, '')
return newStr.strip()
line1 = " hello hoe are you "
a = removeSpaces(line1, 'are')
print(a) |
180d0fff2b947a1c6944180003277c4b48eb2791 | Pythonista7/wtf_python_snippets | /walrus_pt1.py | 355 | 3.703125 | 4 | # Python version 3.8+
>>> a = 6, 9
>>> a
(6, 9)
>>> (a := 6, 9)
(6, 9)
>>> a
6
>>> a, b = 6, 9 # Typical unpacking
>>> a, b
(6, 9)
>>> (a, b = 16, 19) # Oops
File "<stdin>", line 1
(a, b = 6, 9)
^
SyntaxError: invalid syntax
>>> (a, b := 16, 19) # This prints out a weird 3-tuple
(6, 16, 19)
>>> a #... |
53b056344623bdf50ffe801db7ec904d359bfbc5 | endere/code-katas | /tribonacci/tribonacci.py | 667 | 4.40625 | 4 | """Kata: Tribonacci Sequence
kyu 6
#1 Best Practices Solution by Azuaron, Abhi_Scorp
def tribonacci(signature, n):
res = signature[:n]
for i in range(n - 3): res.append(sum(res[-3:]))
return res
"""
def tribonacci(signature, n):
"""This code takes an array of three numbers as the signature, and a number as n... |
f5d9cb7ce670c17eefbc6a9e457b46e34c851341 | endere/code-katas | /proper_parenthetics/parenthetics.py | 668 | 4.03125 | 4 | """A simple code implementing a queue to tell if a line of parentheses is open, closed, or balanced."""
from _que import Queue
def parenthetics(string):
"""Return 0 if balanced, 1 if open, -1 if closed. Function does not care about other characters in the string."""
Q = Queue(list(string))
open_count = 0
... |
6727e230800a4cf848cd7f4a72b589af23022b9f | PSJoshi/malware_inspector | /process_check/malware_inspector_config/sqlite3_class_script.py | 2,778 | 3.765625 | 4 | #!/usr/bin/python
import sqlite3, sys
class database:
"""Database sqlite3 class"""
def __init__(self, name):
self.name = name
self.create_database()
def create_database(self):
self.conn = sqlite3.connect(self.name)
self.c = self.conn.cursor()
def query(self, query):
... |
61a20dc2e6300773b35e50fca4f74736157e3093 | mdarshad1000/Python-Projects | /Age-Calculator.py | 578 | 4.46875 | 4 | def ageCalculator(year, month, day):
"""This function calculates the current age of the user"""
import datetime
# Computes the current date
today = datetime.datetime.now().date()
# User's date of birth
date_of_birth = datetime.date(year, month, day)
# Computes the age of user
age... |
db27434feb682458524ef3ab4df086f824c7a683 | zongjie233/my_first_game | /hard_way_learn_python/my_word_game.py | 1,968 | 3.5625 | 4 | from sys import exit
def start():
print("你是北凉城的一位世子,名为徐凤年,请选择你的人生志向")
print("a:大爷腰穿万贯,当然要享受荣华富贵 b:虽然家境显赫,但我钟爱文学 ")
print("c:志向远大的我要游历四方,钻研武学,做一名陆地神仙 d:碌碌无为,过着枯燥的生活")
choice = input(">")
if choice == "a":
rich()
elif choice == 'b':
Study()
elif choice == 'c':
Go()
... |
c07912ea4b796f6dae4042811e11b71b7ac617df | hallpaz/python07 | /samples/cripto.py | 1,582 | 3.890625 | 4 | import random
def encrypt(text, key = None):
"""Essa funcao criptografa um texto com cifra de Cesar"""
alphabet_size = ord('Z') - ord('A') + 1
if key is None:
print("Chave gerada automaticaente")
key = random.randint(1, alphabet_size)
cripto = ""
for char in text:
num... |
d9a54bbb469628b400256dd3ab552f0ec5934327 | hallpaz/python07 | /samples/cripto_example.py | 1,237 | 4.125 | 4 | import cripto as cp
import os
while(True):
print("Este programa criptografa textos\n")
print("Digite 1 para criptografar textos digitados no terminal")
print("Digite 2 para criptografar um arquivo")
print("Digite 3 para criptografar todos os arquivos de uma pasta")
print("Digite qualquer outra coi... |
003ce04460010f60deeaa0047f4fc75c44ca4a5d | AmrMKayid/KayAlgo | /leetcode/BinarySearch.py | 2,129 | 4.0625 | 4 | class BinarySearch():
'''
Read Google Blog about Binary Search BUG:
https://ai.googleblog.com/2006/06/extra-extra-read-all-about-it-nearly.html
The binary-search bug applies equally to mergesort, and to other divide-and-conquer algorithms.
-> mid value: it fails if the sum of low and high is greater... |
1719dc32fc6dc9e8da1ccd69cc650f0bdcc0cbb9 | AmrMKayid/KayAlgo | /grokking-algorithms/selection_sort.py | 1,396 | 3.875 | 4 | import random
import time
from typing import Any
from typing import List
def timeit(f):
def timed(*args, **kw):
ts = time.time()
result = f(*args, **kw)
te = time.time()
print(f'func:{f.__name__} args:[{args, kw}] took: {te - ts} sec')
return result
return timed
@timeit
def selection_sor... |
edc7c2c6b908fd55df2ccbbf1c137f2225a7665d | AmrMKayid/KayAlgo | /leetcode/98-validate-binary-search-tree.py | 745 | 3.953125 | 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 isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
... |
43cc73662b2a54abe5585dd70238b47b84ca8740 | AmrMKayid/KayAlgo | /hackerrank/30-days-of-code/day26-nested-logic.py | 438 | 3.796875 | 4 | actual_date = list(map(int, input().split(' ')))
expected_date = list(map(int, input().split(' ')))
# print(actual_date, expected_date)
if actual_date[2] < expected_date[2]:
print(0)
elif actual_date[2] > expected_date[2]:
print(10000)
elif actual_date[1] > expected_date[1]:
print(500 * (actual_date[1] - expected... |
e377c0388bb604366b048f294982bd57d357052f | jianzezhou272/LeetCode | /500.py | 573 | 3.546875 | 4 | class Solution(object):
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
out = []
dic = {}
for l1 in 'QWERTYUIOP':
dic[l1] = 1
for l1 in 'ASDFGHJKL':
dic[l1] = 2
for l1 in 'ZXCVBNM':
... |
9b72ec5c5d9da7cd2d1bc9f811a7dfdd2b220c4d | jianzezhou272/LeetCode | /671.py | 680 | 3.78125 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def findSecondMinimumValue(self, root):
"""
:type root: TreeNode
:rtype: int
"""
... |
4fe5d765b61ebe7a04b51e393493508adb58c906 | OlehPalka/First_semester_labs | /Lab work 5/caesar.py | 1,419 | 3.84375 | 4 | def caesar_decode(message, key):
"""
(str, int) -> str
This function decodes caesar code using key and massage.
>>> caesar_decode("ifmmp xpsme", 1)
'hello world'
>>> caesar_decode("jg zpv ibqqz boe zpv lopx ju dmbq zpvs iboe", 1)
'if you happy and you know it clap your hand'
"""
alf... |
5da459e85464fc6d63802e77652204fdcdf16c84 | OlehPalka/First_semester_labs | /Lab work 3/sum_7.py | 108 | 3.5 | 4 | x = int(input())
y = x // 7
sum_of_num = (y * (y + 1)) / 2
result = sum_of_num * 7
print(int(result))
|
9bc299a27999970ea0ff05263da7d1c29d9655c2 | OlehPalka/First_semester_labs | /Lab work 7/single_num_type_mode.py | 1,851 | 3.796875 | 4 | import random
from num_type_gen import *
def single_num_type_mode(difficulty, num_type, grid_size=10):
difficulty_ranges = {
1:(0,50),
2:(50,200),
3:(200,500)
}
valid_nums = num_type(*difficulty_ranges[difficulty]) #List of valid numbers based on difficulty
invalid_grid = True
... |
6eee628833eeb0850e03ee70824c00e5ac0e730a | OlehPalka/First_semester_labs | /Lab work 9/calculus.py | 4,938 | 3.984375 | 4 | """
This module makes operations with functions.
"""
def find_max_1(function, points):
"""
(function or str, list(number)) -> (number)
Find and return maximal value of function f in points.
>>> find_max_1('x ** 2 + x', [1, 2, 3, -1])
12
>>> find_max_1(lambda x: x ** 2 + x, [1, 2, 3, -1])
... |
4521cddbc4ade0f87f9a882014bc70bbc16aa6ab | OlehPalka/First_semester_labs | /Lab work 12/algorithms.py | 3,816 | 4.28125 | 4 | """
This module contains sorting and finding fucntions.
"""
import doctest
import math
def linear_search(list_of_values: list, value):
""" Return the index of the first occurrence of value in lst, or return
-1 if value is not in lst.
>>> linear_search([2, 5, 1, -3], 5)
1
>>> linear_search([2, 4, ... |
5b8571c913b9a3688f69d413c6649cffe822e74b | OlehPalka/First_semester_labs | /Lab work 3/ОП лабораторна 3 N6.py | 234 | 4 | 4 | x = int(input())
y = int(input())
if x == 1:
print("*")
else:
for i in range(1):
print(y * "*")
for i in range(x - 2):
print(("*{}*").format(" " * (y - 2)))
for i in range(1):
print(y * "*") |
16932b181a69e80c2161ee1e7177cae2f6f01f19 | OlehPalka/First_semester_labs | /Lab work 6/happy.py | 1,700 | 3.734375 | 4 | """
Finds lucky numbers and does some operations with them
"""
def happy_number(number: int) -> bool:
"""
This function rerturns True if summary of first 4 numbers in
number = summary of other four numbers.
If not, function returns False.
>>> happy_number(123)
False
>>> happy_number(4321123... |
87aedd6ace6e80591aac05bd910021de17697ed7 | risooonho/The-Forming | /ImageCache.py | 1,248 | 3.53125 | 4 | import glob
import pygame
class ImageCache:
def __init__(self, directory, img_type='png'):
self.cache = {}
self.directory = directory
self.img_type = img_type
self.add_dir(directory)
def add_dir(self, directory):
"""
Adds an entire directory of images to the... |
84e2b0a3ef6c9f4a86cec1420840fa1986956584 | risooonho/The-Forming | /Utility.py | 505 | 3.515625 | 4 | import time
import pygame
def take_screen_shot(screen):
"""
Takes a screenshot and saves it to the screenshot directory
:param screen: Screen to take screenshot of
"""
time_taken = time.asctime(time.localtime(time.time()))
time_taken = time_taken.replace(" ", "_")
time_taken = time_taken.... |
13cd6f02aefa355e2e164ec6cb213b66ebde998f | cpe202spring2019/lab1-jkim441 | /lab1.py | 1,210 | 3.875 | 4 |
def max_list_iter(int_list): # must use iteration not recursion
if int_list == None:
raise ValueError
elif len(int_list) == 0:
return None
elif len(int_list) > 0:
max_num = int_list[0]
if len(int_list) > 1:
for num in int_list[1:]:
if num > max_num:
... |
facd55a712d5394e2727b3f7c247f695146029f3 | Shotaro-Yoshinaga/Python-Practice | /range.py | 108 | 3.765625 | 4 | for i in range(10):
print(i)
for num in range(2,20):
print(num)
for j in range(-2,5):
print(j) |
4012230f305901b6a0f5bfc22614b40ff674f3b2 | margaretchan/Docket | /events.py | 3,021 | 4.25 | 4 | import datetime
"""
Task is an assignment or job which must be completed by a specific due date.
name : string
due : datetime.datetime
expected_duration : datetime.time - the total time it is expected to take to
complete this task
num_blocks : int - the amount of scheduled TaskBlocks this task ... |
d0cd3f577f0b0eae055027144151441f47ac31e8 | kareemgamalmahmoud/python-pi-calculator | /calcPi.py | 338 | 3.625 | 4 | # pi = sqrt(12)(1 - (1/3.3^1) + (1/5.3^2) - (1/7.3^3) + ...)
import math
pi = 0
for k in range(20):
pi += pow(-3 , -k) / (2*k + 1)
pi *= math.sqrt(12)
print('pi = ' , pi)
# to get Error rate
print('error = ' , abs(pi-math.pi))
# that mean when i increase the num of the range the erro... |
ebad3b23e8796e8bf2cb02e365193eae6dc636cb | mevinngugi/learningPython | /MITx6.00.1/problem_set_1/problem_1.py | 620 | 4.1875 | 4 | # Assume s is a string of lower case characters.
# Write a program that counts up the number of vowels contained in the string s.
# Valid vowels are: 'a', 'e', 'i', 'o', and 'u'.
# For example, if s = 'azcbobobegghakl', your program should print:
# Number of vowels: 5
def count_vowels(s):
vowels = ["a", "e", "i... |
7c67a8445c76e506b66629ade70c69a4cd8a8912 | iagotito/atal | /lista-3/q2.py | 641 | 3.6875 | 4 | def is_prime(n):
if n == 2 or n == 3: return True
if n < 2 or n%2 == 0: return False
if n < 9: return True
if n%3 == 0: return False
r = int(n**0.5)
f = 5
while f <= r:
if n % f == 0: return False
if n % (f+2) == 0: return False
f += 6
return True
def f(n):
n += 1
s = []
count ... |
f3e5eb4204e1b707e08e43b21c6660625ac1a87e | wfan0/local_repo_1 | /importTest.py | 470 | 3.515625 | 4 | import numpy
norm_array = [1,2,3,4,5]
numpy_array = numpy.array(norm_array)
print("normal" + " " + str(numpy_array))
greater_than_2 = numpy_array >2
print(greater_than_2)
c = norm_array.copy()
c [1] = "poop"
print(c)
print(norm_array)
#-------------------
num_array = numpy.array([1,2,3,4,5,numpy.NAN,7])
print(num_... |
61cf5adad3637e10ece48e5a4faeb7240b88b1d1 | hieast/bedrock | /bedrock/os_demo/multithreading_py2.py | 490 | 3.515625 | 4 | import threading
for thread in threading.enumerate():
print(thread)
def print_thread_info():
print(threading.active_count())
print(threading.current_thread())
import time
def add(x, y):
print("{} + {} = {}".format(x, y, x + y))
return x + y
def sleepy_add(x, y, sleep_time=5):
print('{} ... |
5fc871cdd05d6e27a9a47d44353de7b6adcaf502 | greenmapc/cryptopals-tasks | /homework_2/T40_RSA_broadcast_attack.py | 1,166 | 4 | 4 | from homework_2.T39_RSA import RSA, inversion_by_mod, int_to_bytes
def cube_sqrt(n):
# realization of cube sqrt for binary search
left = 0
right = n
while left < right:
mid = (left + right) // 2
if mid ** 3 < n:
left = mid + 1
else:
right = mid
ret... |
9361260cd8c5dc8644dfbab5c4f85af159d197e4 | sandeepchopra/Data_Science_from_Scratch | /linear_algebra.py | 5,022 | 3.796875 | 4 | from __future__ import division # want 3 / 2 == 1.5
import math
import matplotlib.pyplot as plt # pyplot
# %matplotlib inline
# -*- coding: cp1252 -*-
#***************************************************************************************************
# **********************Chapter 4. Linear Algebra******************... |
4ca5b48e03fd97d0507454a5ce3003bad75ae165 | sandeepchopra/Data_Science_from_Scratch | /hypothesis_and_inference.py | 7,791 | 4 | 4 | from __future__ import division
from probability import normal_cdf, inverse_normal_cdf
import math, random
import matplotlib.pyplot as plt
# %matplotlib inline
# -*- coding: cp1252 -*-
#***************************************************************************************************
#**********************Chapter 7.... |
f628c68d4bec193011467526efa21c253df52801 | Emmanuel-Cruz/War_Analysis | /war.py | 6,176 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 7 18:39:39 2018
@author: Emmanuel Cruz
"""
class Card:
def __init__(self, color, number, suit):
self.color = color
self.suit = suit
self.number = number
def get_color(self):
return self.color
def get_number(self)... |
fa1ac7e560ef5b08de4a76e5d4459b9b000a891c | andreyjkee/5_lang_frequency | /lang_frequency.py | 821 | 3.546875 | 4 | import argparse
from collections import Counter
import re
def load_data(filepath):
if not filepath:
raise Exception('Не указан путь к файлу')
with filepath as f:
return f.read()
def get_most_frequent_words(text, count=10):
word_list = re.findall(r'(\w+)', text)
return [pair[0] for pai... |
a41168ac090014c451e96848420d4ebf658a8328 | trevorKirkby/Billion-Word-Imputation | /convert.py | 1,915 | 3.609375 | 4 | #!/usr/bin/env python
"""
4m20
"""
import cPickle as pickle
import numpy as np
def sanitize(word):
if "://" in word:
return "URL"
if "" in word.split("-"):
if word.split("-").remove(""):
if len(word.split("-").remove("")) > 3: #more than three and it isn't a hyphenated word, it is a hyphenated sentence.
... |
d5a8cb945e6c8b6cf7bb9b88e4bd3128a3721eec | GlennRC/Algorithms | /Labs/HW3/main.py | 1,707 | 3.703125 | 4 | import random
import time
def preSortIntersection(a: list, b: list):
a.sort()
b.sort()
intersect = set(a) & set(b)
return intersect
def bruteForceIntersection(a, b):
intersection = set()
for i in range(len(a)):
for j in range(len(b)):
if a[i] == b[j]:
in... |
459d2349b73b9f62e579ca3ec9e1cea4dfb80815 | GlennRC/Algorithms | /Labs/Lab9/main.py | 906 | 3.828125 | 4 | class Node(object):
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def sumLeaves(root):
if not root.left and not root.right:
return 1
else:
return sumLeaves(root.left) + sumLeaves(root.right)
"""
M(n) = M(n/2) + 1
C(n) = C(n-1) + 1
"""... |
6d1dc656ba4a0ba61e74df1d55f2a1fde823f7fe | RomuloSouza/demo-engine | /phys/body.py | 3,068 | 3.6875 | 4 | import pyxel
import random
from math import sqrt
from .collision import Collision
from .vec2d import Vec2d
class Body:
"""
Representa uma partícula ou corpo rígido com velocidade e posição bem
definidas.
Cada sub-classe de Body representa um tipo diferente de caixa de contorno.
"""
# Propr... |
7dee19605bc8f902b9361a60c631293644d265b8 | zacharycope0/Distributed_Travel_Application | /Application/Travel_Client.py | 3,173 | 3.65625 | 4 | #
#UPDATE CODE BETWEEN <>
#
#Import packages
import xmlrpc.client
import sys
# TESTING AIRLINE SERVER
name = input("Enter your name to begin the reservation process:")
#Except blocks will cancel reservation there is a communication error with the server.
#
#ADD IP ADDRESS AND PORT NUMBER TO COMMUNICATE... |
8e88a9f2c3a66d7fbbbd71180faae2c1b5ce2068 | Philip-Green/Python | /Average1.py | 209 | 4.125 | 4 | # Philip Green
test1= int(input("Enter test1:"))
test2= int(input("Enter test2:"))
test3= int(input("Enter test3:"))
sum= test1+test2+test3
print("The sum = ", sum)
average= sum/3
print("The average =", average)
|
00d30ba9271cf242cefb7c23d05cfd98eba45c2a | alozar-si/ml-naloga-6 | /naloga-1_kmeans_implementation.py | 2,976 | 3.6875 | 4 | # Naloga 1: Implementacija k-means
# V tej skripti je prikazano delovanje k-means, na koncu pa se uporaba z razredom
#%%
import matplotlib.pyplot as plt
import numpy as np
from time import time
# %%
path_to_data = "C:/Users/andlo/data/psuf/ml-naloga-6/podatki1/"
data = np.load(path_to_data + "gauss.npy")
print("Data le... |
ea609af7b7079a5e05d55ae28ea57a2254659e67 | StanislavBubnov/Python | /Lesson7/Hometask_7.3.py | 877 | 3.953125 | 4 | class Cell:
def __init__(self, param_1):
self.param_1 = param_1
def __add__(self, other):
return self.param_1 + other.param_1
def __str__(self):
return str(self.param_1)
def __sub__(self, other):
return self.param_1 - other.param_1 if self.param_1 > other.param_1 else 'Ра... |
739d5dc6d10f948064519215845da02e051d828f | StanislavBubnov/Python | /Lesson1/Hometask 1.5.py | 1,623 | 3.703125 | 4 | #5) Запросите у пользователя значения выручки и издержек фирмы.
#Определите, с каким финансовым результатом работает фирма (прибыль — выручка больше издержек, или убыток — издержки больше выручки).
#Выведите соответствующее сообщение.
#Если фирма отработала с прибылью, вычислите рентабельность выручки (соотношение приб... |
a48486265fc10c1a6d858bb8d0c5526c4f7a98bb | StanislavBubnov/Python | /Lesson7/Hometask_7.2.py | 659 | 3.625 | 4 | class Clothes:
def __init__(self, param_1, param_2):
self.param_1 = param_1
self.param_2 = param_2
@property
def my_method(self):
my_coat = (self.param_1 / 6.5 + 0.5)
my_costume = round((2 * self.param_2 + 0.3)/100,2)
return f'Параметры, переданные в класс: \nРазмер:... |
9e97f70267430b96f5dd1255428594af85b51c36 | StanislavBubnov/Python | /Lesson5/Hometask_5.5.py | 698 | 3.90625 | 4 | # 5) Создать (программно) текстовый файл, записать в него программно набор чисел, разделенных пробелами.
# Программа должна подсчитывать сумму чисел в файле и выводить ее на экран.
with open('test_for_hometask_5.5.txt','w+') as my_text:
my_text.write(input('Введите Ваши числа через пробел: '))
with open... |
c2ca2cc29ef004c1e52d7c5d13e43ceea255f9a4 | jgera/ml-naivebayes | /gaussian.py | 978 | 3.546875 | 4 | import math
def mean(fv):
'''Calculate the mean of a feauture vector.'''
return float(sum(fv)) / len(fv)
def mvue(fv, mu=None):
'''Minimum variance unbiased estimation of a feature vector.'''
mu = mean(fv) if mu is None else float(mu)
return sum([math.pow(v - mu, 2) for v in fv]) / (len(fv) - 1)... |
0c32df9038961273b7ca68eacf1fbf511bc2eb81 | Nazanin1369/stockPredictor | /old_src/main.py | 5,853 | 3.671875 | 4 | import yahoo_finance as yahoo
import pandas as pd
import numpy as np
import StockPredictor
###### Entry Parameters #######
startDate = '2010-01-01'
endDate = '2013-08-19'
ticker = 'GOOG'
metric = 'Adj_Close'
queryDate = '2013-08-20'
#Used for re-running: stops querying the API if we already have the data
reloadData ... |
b8695de1ca65b9eae9c0026fa6caa9924c9b73a7 | bradleypick/mymlimp | /mymlimp/regression.py | 1,017 | 3.921875 | 4 | #! usr/bin/env python
import numpy as np
class linear_model():
def __init__(self):
self.w = None
def fit(self, X, y, reg=None, lam=0.001):
"""
External method for fitting linear model
Inputs:
- X: feature (design) matrix of dimension n x d
- y: reponse ... |
6ace4fdb4ad3a75220da0f8e475449184db814bf | lugovoyd/JackPot21 | /work.py | 643 | 3.578125 | 4 | koloda = [6,7,8,9,10,2,3,4,11] * 4
import random
#random.shuffle(koloda)
print('Lets play?')
count = 0
while True:
choice = input('One more? y/n\n')
if choice=='y':
current = koloda.pop()
print('You have %d' %current)
count += current
if count > 21:
p... |
13986ebc011c33fc79bebf5798237ec3a2c61af5 | bilalc3/CodeProjects | /Python-Projects/imdb_search/importmyown.py | 1,271 | 3.953125 | 4 | from cs50 import SQL
import csv
from sys import argv, exit
import sqlite3
open(f"students.db", "w").close()
db = SQL("sqlite:///students.db")
#db.execute =("Query")
#db.execute("CREATE TABLE shows (first TEXT, middle TEXT, last TEXT, house TEXT,birth NUMERIC)")
if (len(argv) != 2):
print ("Enter 1 csv file need... |
de8e995831f447862357928cb9707825266f5765 | sooraj948/Cyber_suite | /encrypt.py | 1,511 | 3.578125 | 4 | import sys
def ceasar(s,n):
t=""
s=s.lower()
for i in s:
if 97<=ord(i)<=122:
# print((ord(i)-97+n)%26)
t+=chr((ord(i)-97+n)%26+97)# this is actual encryption by rotation or movement
else:
t+=i
return t
def vignere(s,key):
n=len(key)... |
30cc11c84db0841598517044f544e460e8019f2b | jazysamurai/Geekbrains-python | /Lesson01/01.py | 306 | 3.84375 | 4 | print('Питон это язык с динамической типизацией')
x = 100
print('Был целочисленный тип данных: ')
print(type(x))
x = input('Введите новое значение переменной: ')
print('Стал строковый: ')
print(type(x))
|
70293aaef871144bc9f4223826daff0763f507d7 | kanbujiandefengjing/python | /python实例/圆的周长与面积.py | 594 | 4.03125 | 4 | '''
圆的周长与面积
题目内容:
给出一个圆的半径,求出圆的周长和面积
可以使用以下语句实现非负整数n的输入:
n=int(input())
使用 round(a,4) 函数保留4位小数,规定pi=3.14159
输入格式:
输入包含一个整数r,表示圆的半径
输出格式:
输出一行,包含2个数,分别是圆的周长、面积,用空格分隔开,数字保留小数点后4位
'''
r=int(input('请输入圆的半径:'))
pi=3.14159
C=round(2*pi*r,4)
S=round(pi*r**2,4)
print('圆的周长为{},面积为{}'.format(C,S))
|
66782f75b7168294d5b054d821cea9881591548c | kanbujiandefengjing/python | /python实例/斐波拉契数列.py | 618 | 3.828125 | 4 | '''
斐波拉契数列:这个数列从第三项开始,每一项都等于前两项之和。(10分)
题目内容:
已知斐波拉契数列的前两项都是1,我们定义求斐波拉契数列的第n项(n<=50)的函数为fbnq,程序主体如下:
n=int(input(""))
print(fbnq(n))
请补充完成对fbnq函数的定义。
输入格式:
共一行,为一个正整数。
输出格式:
共一行,为一个正整数。
'''
n=int(input("请输入一个正整数:"))
def fbnq(n):
f1=0
f2=1
for i in range(n):
f1,f2=f2,f1+f... |
0e4fece568ea8e96052776723bde6460aa0a51ba | kanbujiandefengjing/python | /python实例/sum.py | 253 | 3.796875 | 4 | #coding: utf-8
#用户输入数字
num1 = input("输入第一个数字:")
num2 = input("输入第二个数字:")
#求和
sum = float(num1) + float(num2)
#显示计算结果
print('数字{0}和{1}相加结果为:{2}'.format(num1,num2,sum))
|
077a28cb92f67bdd287336c9b8d095227c785955 | kanbujiandefengjing/python | /python实例/生成日历.py | 212 | 3.75 | 4 | #生成指定日期的日历
#引入日历模块
import calendar
#输入指定年月
yy = int(input("输入年份:"))
mm = int(input("输入月份:"))
#显示日历
print(calendar.month(yy,mm))
|
f7a8d8eadb4efdee1936729e9ecd8d3ebba5fd16 | kanbujiandefengjing/python | /python实例/简单计算器实现.py | 975 | 4.25 | 4 | #简单计算器实现
#定义函数
def add(x,y):
"""相加"""
return x + y
def subtract(x,y):
"""相减"""
return x - y
def multiply(x,y):
"""相乘"""
return x * y
def divide(x,y):
"""相除"""
return x/y
#用户输入
print("选择运算:")
print("1、相加")
print("2、相减")
print("3、相乘")
print("4、相除")
... |
020fd98e1e84b3a0c9887c2f3512e0bd9d191fd2 | kanbujiandefengjing/python | /python实例/约瑟夫环问题.py | 704 | 3.59375 | 4 | '''
约瑟夫环问题(10分)
题目内容:
已知n个人(以编号0,1,2,3...n-1分别表示)围坐在一张圆桌周围。从编号为0的人开始报数1,数到m的那个人出列;他的下一个人又从1开始报数,数到m的那个人又出列;依此规律重复下去,直到圆桌周围的人全部出列。
输入格式:
两个正整数n, m,其中3<=n<=100, 1<=m<=n
输出格式:
按照顺序出列的人的编号列表
'''
n=int(input("请输入介于3和100的正整数n:"))
m=int(input("请输入介于1和n的正整数m:"))
lst=list(range(n))
result=[]
k=0
while ls... |
8a155ed1daccc9a3f71aebfea780eae7f47b1f30 | kanbujiandefengjing/python | /python实例/字符串循环左移.py | 865 | 3.703125 | 4 | '''
字符串循环左移
给定一个字符串S,要求把S的前k个字符移动到S的尾部,如把字符串“abcdef”前面的2个字符‘a’、‘b’移动到字符串的尾部,得到新字符串“cdefab”,称作字符串循环左移k位。
输入一个字符串和一个非负整数N,要求将字符串循环左移N次。
可以使用以下语句实现字符串s的输入:
s=str(input())
可以使用以下语句实现非负整数n的输入:
n=int(input())
输入格式:
输入在第1行中给出一个不超过100个字符长度的、以回车结束的非空字符串;第2行给出非负整数N。
输出格式:
在一行中输出循环左移N次后的字符串。
'''
s=str(i... |
63eab28d93e691bdfa2920923e3803c1acb1e206 | MaxWong03/Think-Mathematically | /dozens/biggest_three_digit_4.py | 1,703 | 3.734375 | 4 | import sys
# Understand the problem
# Recongize a pattern to the solution
# Categorized the input
# Code the pattern into a function
# Strategy:
# Given A and B
# 1) if AB is divisible by 4, then return 9AB
# 2) if BA is divisible by 4, then return 9BA
# 3) if AB / BA is not divisible by 4
# 3a) if A > B, and B is eve... |
387433ef511380ac914a5e51407cfc481f86b6c9 | erikaipf/Python_HB_Exercises | /calculate_bill_class8_1.py | 1,651 | 4.09375 | 4 | # Course Intro to Programming - Hackbright Academy
# Ch. 8 Scope - Activity 1
# by Erika Freiha 03-May-2016
def calculate_tip(bill_amount,tip_percentage):
'''Calculate the amount of the Tip by some Percentage of a bill'''
return ((bill_amount * tip_percentage) / 100)
def calculate_total_bill(bill_amount,tip_amount... |
76c3801bdf400a3d4861a3addd240086d6d0d5a9 | erikaipf/Python_HB_Exercises | /greater_name.py | 266 | 4.21875 | 4 | my_name = raw_input("What is your name?")
my_partners_name = raw_input("What is your pair's name?")
if my_name > my_partners_name:
print 'My name is greater'
elif my_name < my_partners_name:
print 'Their name is greater'
else:
print 'our names are equal!' |
9a39dd52ae0cd4b9dff56fc3ab3b3b2ee97b7300 | huseyindalbudak/mathpy | /statistic/visualization/lineGraphs3D.py | 783 | 3.515625 | 4 | # dynamic line graph
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import mpl_toolkits.mplot3d.axes3d as p3
import time
fig = plt.figure()
ax1 = p3.Axes3D(fig)
#fig2 = plt.figure()
#ax1 = fig.add_subplot(1,1,1)
def animate(i):
pullData = open("av_Data.txt","r").read()
dataArray = p... |
4d438ab8177b34f7094e118f42e11e17b76ba9c5 | renamez4/project-1 | /lecture 2/EX3.py | 82 | 3.84375 | 4 | num = float(input("enter a number : "))
if score >= 90:
print('A ', score )
|
2fc49d465ad24ec261c0b88e7ba1ce82d3708146 | renamez4/project-1 | /lecture3/countloop.py | 94 | 3.59375 | 4 | print('I will display the number 1 through 5. ')
for num in [1,6,2,20,11]:
print(num)
|
16240f08986e27cc6faf1cb8c2354d7e7807f45e | renamez4/project-1 | /lecture5/Function.py | 294 | 3.71875 | 4 | #This program as two functions
#First we define the main function.
def main():
print('I have a message for you.')
message()
print('Goodbue!')
#Next we fefine the message function
def message():
print('I am anirach,')
print('I Love Python.')
# Call the main function.
main() |
5ca820ecdbacbe713600dd514d2873fa660cefee | renamez4/project-1 | /lecture3/while.py | 121 | 3.953125 | 4 | # python program to illustrate
# while loop
count = 0
while (count <3):
count = count +1
print("hello mind")
|
7118d1ba2a17e5cb83934c880f3e9feb6fb99fdd | emtiaz-ahmed/Coding_Practice | /Bit Manipulation/Magic_Number.py | 838 | 4.625 | 5 |
# Find nth Magic Number
# A magic number is defined as a number which can be expressed as a power of 5 or sum of unique powers of 5. First few magic numbers are 5, 25, 30(5 + 25), 125, 130(125 + 5), ….
# Write a function to find the nth Magic number.
# Input: n = 2
# Output: 25
# Input: n = 5
# Output: 130
# If w... |
c12c9f768db0625250972301d373f79c7864b87c | nuclearenergyant/PythonTestDemo | /demo01.py | 2,862 | 3.953125 | 4 | # 元组的测试
dimension = (1, 2)
print( dimension[0] )
# 修改元组元素——》软件会提醒不能修改
# 条件语句测试
my_name = 'Tom'
print( my_name == 'tom' )
num = 17
if num != 18:
print( 'you are a young boy' )
else:
print( 'you are a man' )
# 查看特定值是否在列表中
names = ['Tom', 'jon', 'killy']
print( 'Tom' in names )
# 检查特定值是否不包含在列表总
print( 'dell' no... |
14909baeaaffa26a2366cc9d8468733f00bddbc1 | RobinDeHerdt/HackerRank | /Python/Basic-data-types/find-second-maximum-number-in-a-list.py | 589 | 4.0625 | 4 | # https://www.hackerrank.com/challenges/find-second-maximum-number-in-a-list/problem
from Testing import assertions
def find_second_maximum_number_in_list(arr):
# Convert the map to a set; only unique values will remain.
unique_arr_values = set(arr)
# Convert the set to a list, so we can sort it.
un... |
fbabb4a6f41118bc3e697bf18769fbaf29cf54d1 | RobinDeHerdt/HackerRank | /Python/Strings/designer-door-mat.py | 696 | 3.703125 | 4 | # https://www.hackerrank.com/challenges/designer-door-mat
if __name__ == '__main__':
import math
def draw(n, m):
middle = math.floor(n / 2)
middle_text = "WELCOME"
for index, value in enumerate(range(middle, 0, -1)):
print("---" * value + ".|" + (index * 2 * "..|") + "." +... |
9bc80b3ceb2affb434cfb1f2edb071ef20b7e454 | RobinDeHerdt/HackerRank | /Algorithms/Warmup/mini-max.py | 354 | 3.890625 | 4 | #!/bin/python3
import os
import sys
def miniMaxSum(arr):
arr.sort()
min_result = 0
for i in arr[:len(arr) - 1]:
min_result += i
max_result = 0
for i in arr[1:]:
max_result += i
print(min_result, max_result)
if __name__ == '__main__':
arr = list(map(int, input().rstrip... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.