blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
67778ee78138bda862c5cc7f0943dc8eea07d489 | chili512/PythonStuff | /learning/database.py | 1,552 | 3.859375 | 4 | import sqlite3
def create_database():
conn = sqlite3.connect(":memory:")
print("Opened database successfully");
conn.execute('''CREATE TABLE COMPANY
(ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
... |
13ad522c05b8c78e5a567f5b4c8f29852c006aa9 | tanmaysahay94/Algorithm | /PY/0784_pdig.py | 170 | 3.65625 | 4 | def pow2sum(exp):
pow = list(str(2**exp))
return sum([int(i) for i in pow])
t = int(raw_input())
for i in range(t):
n = int(raw_input())
print pow2sum(n)
|
99ad524b94099f2c5e273edcd2d7c1bd42f48ed4 | Joeliqq/PythonSpider | /spider3_header.py | 546 | 3.5 | 4 | #coding:utf-8
import urllib
import urllib2
url = 'http://ip.chinaz.com/'
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' # 模拟(伪装)
header = {'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'}
values = {'name' : 'XXX',
'location' : 'neu',
... |
d996d2eb2ebee86f476e65920778f60e615f2bbb | dan9731/another-repo | /i_like_to_eat.py | 108 | 3.53125 | 4 | flavors = ['apple', 'cherry', 'pumpkin', ]
for flavor in flavors:
print("I like to eat ", flavor, "pie!")
|
78f72aeae7d8afc54299ed9787d169f7fd35479d | Fuhoward0513/Hash_RB-and-LL | /src/drawer/ratioLLandRBTree.py | 2,066 | 3.53125 | 4 | from .poissonDraw import drawDistribution
import matplotlib.pyplot as plt
'''
In drawRatioLLandRBTree, we want to know how LF, TT affect the numbers of LL and RBTree.
Note that both LF and nodeNum can affect lambda(you can see it as "average length of bin".), so here we fix LF.
Besides, the numbers of LL and RBTree ar... |
9db88c9f990d856d9248ee06fe0ca7d118ff94c1 | dbusteed/random-stuff | /statistics/monty_hall.py | 1,024 | 4 | 4 | #
# illustrating the Monty Hall problem
#
from random import randint
import matplotlib.pyplot as plt
N_ROUND = 1000
stay_wins, switch_wins = 0, 0
stay_record, switch_record = [], []
for n in range(1, N_ROUND+1):
prize = randint(1, 3)
choice = randint(1, 3)
# simulate Monty opening the door by selecti... |
4498ebf1604d337d1075ad7b2bda81f4978e122d | dbusteed/random-stuff | /programming/other/paran_check.py | 507 | 4.46875 | 4 | #
# programming challenge question. function
# takes a string of some math/programming
# expression and indicates whether it's
# a valid use of paranthesis
#
def paran_check(s):
count = 0
for char in s:
if char == '(':
count += 1
elif char == ')':
count -= 1
... |
1f981ed1580619705eaa7e547c00f1fe710efac1 | dbusteed/random-stuff | /statistics/random_matrix.py | 443 | 3.796875 | 4 | #
# generates a random covariance matrix
# given the dimensions
#
from random import random, choice
def random_cov_matrix(n):
mat = []
for _ in range(n):
mat.append( [1 for _ in range(n)] )
vals = [round(random() * choice((-1, 1)), 2) for _ in range(n)]
for i in range(n):
for j ... |
24645cb14b9591fe9a04989ecd7155fe4e37de0b | chajk811/TIL | /알고리즘/원형큐.py | 635 | 3.921875 | 4 | def isEmpty():
return front == rear
def isFull():
return (rear+1) % len(cQ) == front
def enQueue(item): # 원형 큐의 삽입 연산
global rear
if isFull():
print('Queue_Full')
else:
rear = (rear + 1) % len(cQ)
cQ[rear] = item
def deQueue(): # 원형 큐의 삭제 연산
global front
if isEmpty... |
08c461ce33ba9ecb5e6fe34b45312d923cd24fb0 | chajk811/TIL | /알고리즘/4873.py | 386 | 3.515625 | 4 | import sys
sys.stdin = open('4873_input.txt')
T = int(input())
def change(words):
for i in range(len(words)-1):
if words[i] == words[i+1]:
words.pop(i)
words.pop(i)
break
else:
return len(words)
return change(words)
for case in range(1, T+1):
words ... |
4f6605313157f4e5d5de791682a5c231c9a0a429 | chajk811/TIL | /알고리즘/역테전까지/피보나치연습.py | 683 | 3.671875 | 4 | # 재귀
def fibo(n):
global cnt
cnt += 1
if n < 2:
return n
else:
return fibo(n-1) + fibo(n-2)
# 메모이제이션
def fibo_memo(n):
global cnt_memo
cnt_memo += 1
if n >= 2 and memo[n] == -1:
memo[n] = fibo_memo(n-1) + fibo_memo(n-2)
return memo[n]
# 또 다른 DP 방법
def fibo_dp(... |
d13f752198a6f020a954acfc77207ff94f67e22b | BjornLJohnson/machinelearningmodels | /example/Convolutional/conv_net.py | 11,362 | 4.375 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Convolutional Neural Networks: Application
#
# Welcome to Course 4's second assignment! In this notebook, you will:
#
# - Implement helper functions that you will use when implementing a TensorFlow model
# - Implement a fully functioning ConvNet using TensorFlow
#
# **Afte... |
dcf8e73876425cb9956123a434bbd8dcc5a63600 | plammens/python-introduction | /Fundamentals I/Overview of built-in types/None/main.py | 230 | 3.71875 | 4 | # -- None (special value indicating the absence of value) --
None # this is how you write None
print(None)
var = None
# `var` is now a valid variable, but it doesn't contain any "meaningful" object
print(var)
print(var is None)
|
e8e2386de344371a8410db0a93e23cc63adb5e24 | plammens/python-introduction | /Fundamentals II/Loops/For loop/main.py | 2,283 | 4.65625 | 5 | # common for loop recipes
# Repetition
# for when you just want to repeat something a number of times
for _ in range(5):
# convention: _ is used to indicate that you don't care about the value
print("Doing something")
# Range iteration
# doing something for every integer in a range
for x in range(1, 10, 2):... |
411a2edc112e9b2dab39224d14df19a9aa8b32ba | plammens/python-introduction | /Preliminaries/The print function/Hello, Python here/main.py | 328 | 4.25 | 4 | # sample use of the print function
print("Hello, world!")
print('My name is Jeff')
print(7 + 3*5)
var = "spam"
print(var)
print(var + 'eggs')
print(list)
print(print)
# If we want to output something when running a Python program
# we *must* use the print function
"This won't be printed!"
print("This will be pri... |
67049bac7c1bc55867124e63e71b86a800bf238e | plammens/python-introduction | /Fundamentals I/Elements of Python syntax/Comments/main.py | 432 | 3.875 | 4 | """
About comments in Python
"""
# to insert one-line comment, use the hash character: #
# everything after # up to the end of the line will be considered a comment:
str(123 + 4.7) + " something something" # this is a one-line comment
# one-line comments can start anywhere in the line, but they always end at the en... |
2371e19df9bda60f0dcbfff3febe0c66e05582ef | rduvalwa5/Examples | /RegularExpressions/StringBeginsWith.py | 431 | 3.765625 | 4 | '''
Created on Jan 18, 2019
^
(Caret.) Matches the start of the string, and in MULTILINE mode also matches immediately after
each newline.
'''
import re
testString = "The quick brown fox \
jumped over the \
lazy fox hound."
print(testString)
print(re.match(r'^>The',testString))
# re.compile(r'^>([^\n\r]+)[\n\r]([A... |
64ad42a4da95774de89b78b3743661fc34be2852 | rduvalwa5/Examples | /Python_UnitTest/src/pyArchive.py | 743 | 3.921875 | 4 | '''
Created on Nov 3, 2012
this program takes as a parameter a directory path for archiving
it then archives only the files in that directory
pyArchive(String directory path)
returns the archive
@author: rduvalwa2
'''
import os, glob, zipfile
def pyArchive(directoryPath):
currentPath = os.getcwd()
fixPath = os... |
f90da22a8334e016a700c430161625cecfd05c09 | rduvalwa5/Examples | /PythonExamples/src/sentence_splitter.py | 421 | 3.796875 | 4 | '''
Created on Mar 8, 2013
@author: rduvalwa2
'''
#!/usr/local/bin/python3
""" better_sentence_splitter.py
Simpler program to list words of a string"""
s = input("Enter a string: ")
print(s)
words = s.strip().split()
""" strip(s[, chars]) Return a copy of the string with leading and trailing characters removed.
If... |
7b7985debae82559f5e721de8efa82c074489b18 | dvisockas/is | /2_antras/data.py | 515 | 3.515625 | 4 | from math import sin, pi
def linspace(start, end, granularity):
multiplier = int(1 / granularity)
expanded_start = int(start * multiplier)
expanded_end = int(end * multiplier + 1)
expanded_range = range(expanded_start, expanded_end)
return [x / multiplier for x in list(expanded_range)]
class Data(object):
... |
cc4741aed6bf9df3aabfb58fc434caec3044f39c | PythonZero/CodeSnippets | /DataClasses.py | 432 | 3.875 | 4 | from dataclasses import dataclass
@dataclass
class DataSoldier:
name: str
attack: int
defence: int
hp: int
class Soldier:
def __init__(self, name, attack, defence, hp):
self.name = name
self.attack = attack
self.defence = defence
self.hp = hp
# Both are the same... |
15d87bd6b6252339f5115d5b0d2e2c50070b71c7 | PythonZero/CodeSnippets | /Metrics/DelayedCounter_and_tests.py | 8,528 | 3.59375 | 4 | """Code relating to Monitoring (i.e. Prometheus)"""
from multiprocessing import Manager
from multiprocessing.managers import SyncManager
from typing import Dict, List
from prometheus_client import Counter
class DelayedCounter:
_shared_list: List[Dict[str, str]] # the pending calls
_manager: SyncManager
... |
b420fb0145655d107dadb9bce3fab33f15e90330 | hasilrahman/assignment2 | /a16.py | 342 | 4.15625 | 4 |
def find_len(list1):
length = len(list1)
list1.sort()
print("Largest element is:", list1[length-1])
print("Smallest element is:", list1[0])
print("Second Largest element is:", list1[length-2])
print("Second Smallest element is:", list1[1])
list1=[12, 45, 2, 41, 31, 10, 8, 6, 4]
Larg... |
e081607f85b471dad46a82f9bf425ea7b42307b8 | DingChiLin/DataAnalystNanodegree | /project_6/test/test.py | 227 | 3.609375 | 4 | import pandas as pd
import numpy as np
df1 = pd.DataFrame([[0,1],[2,3],[4,5]])
df1.columns = ['Col', None]
print(df1)
df2 = pd.DataFrame([[0,7],[2,8],[4,9]])
df2.columns = ['Col', None]
print(df2)
df1['D'] = df2
print(df1)
|
f4ebd8ea3035c48a3e499869dd7f730e20c0ec0b | IvanValBozhanin/Polygon_Area_Calculator | /src/shape_calculator.py | 1,333 | 3.78125 | 4 | class Rectangle:
width = 0
height = 0
def __init__(self, w, h):
self.width = w
self.height = h
def set_width(self, width):
self.width = width
def set_height(self, height):
self.height = height
def get_area(self):
return self.height * self.width
de... |
5d0320bb6da2abf18d2180012d8c0d2150362422 | El20082/KeenKiz-Hack | /Week 1/scam_book.py | 444 | 3.890625 | 4 | def get_ints_from_string(str):
int_list = []
for c in str:
c_int = int(c)
int_list.append(c_int)
return int_list
list = get_ints_from_string(input("yes "))
sum = 0
for i in range (0,len(list)) :
if i % 2 == 0:
sum += list[i]*1
elif i%2 == 1:
sum += list[i]*3
else :
print... |
97d91648b97171c2679599eb3e1a9bbcf74e1965 | jacobmischka/adventofcode-2015 | /2.py | 670 | 3.65625 | 4 | #!/usr/bin/env python3
'''
Day 2
http://adventofcode.com/2015/day/2
'''
from itertools import combinations
from utils import get_input_filename
from functools import reduce
DAY_NUM = 2
# This does not feel very good
def part1():
wrapping_paper = 0
with open(get_input_filename(DAY_NUM)) as f:
... |
3bdb22f62075cc1ac7800bead192a77d8b58c894 | AdrianoCompadre/Homework | /Task 4.py | 190 | 4.09375 | 4 | num = int(input('Enter a positive integer: '))
m = num % 10
num = num // 10
while num > 0:
if num % 10 > m:
m = num % 10
num = num // 10
print('Largest number is',m)
|
83ecf164289579d702311b960b4d187d78d72852 | Madhu2244/Leetcode-ProgrammingPrep | /36. Valid Sudoku/solution.py | 1,438 | 3.6875 | 4 | class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
seen_row_numbers = [set() for i in range(9)]
seen_column_numbers = [set() for i in range(9)]
for sector in range (3):
for quadrant in range (3):
seen_numbers = set()
for row i... |
1ba2ba61bbf09503a94f61b599444f7bd27ca48c | shenhuipeng/Two-Nested-Spirals | /activeFunction.py | 1,032 | 3.921875 | 4 | # -*- coding : utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
def sigmoid(Z):
"""
:param Z: a numpy array with any shape
:return A: sigmoid(Z) the size of A is same as Z
"""
A = 1/(1+np.exp(-Z))
tmp = Z
return A, tmp
def relu(Z):
"""
:param Z: a numpy array wi... |
4546d6b8c0b1b52c5f6fe23b95637737b2d154a9 | blackbelt238/TangoAdventure | /adventure/adventurer.py | 2,608 | 3.734375 | 4 | from character import Character
class Adventurer(Character):
''' Adventurer represents a player character. It can do things such as level up and hold items '''
def __init__(self, name, class_name):
Character.__init__(self, 0, 1, 0, 1, name)
self.backpack = [] # items the character is h... |
bfb738a4ee6935a1b9f5a9357b527999d1585788 | blackbelt238/TangoAdventure | /adventure/adventure.py | 9,083 | 3.6875 | 4 | import die
import item
from adventurer import Adventurer
from map import Map
class Adventure:
# changes to a 'current' location to go a specific direction
NORTH = [0, -1]
EAST = [1, 0]
SOUTH = [0, 1]
WEST = [-1, 0]
def __init__(self, map_file_name, class_name):
self.player = Adventurer... |
99d3a05addfe956a691066b528d0367b82c9f95d | bibhuWork/git_github_demo | /demo_Scripts/namespaceScope.py | 2,113 | 3.859375 | 4 | #!/home/myfamily/anaconda3/bin/python
myStr1='Hi I am Global'
def myFunction1():
myStr1='Inside myFunction1'
print('Inside Function1 and after assigning value : %s' % myStr1)
def myFunction1_1():
myStr1='Inside myFunction1_1'
print('Inside Function1_1 and after assigning value : %s' % myStr1)
return
myFunct... |
0f84cb01a39e426b655a2c5203f0e826abc1c287 | Connor-Knabe/Coding-Challenges | /Python/List-1/rotate_left.py | 167 | 3.625 | 4 | def rotate_left3(nums):
temp0 = nums[0]
temp1 = nums[1]
temp2 = nums[2]
nums[0] = temp1
nums[1] = temp2
nums[2] = temp0
return nums
|
fc3e8b38b76c0ca027563b7aad7fafe8f4bd53c5 | Connor-Knabe/Coding-Challenges | /Python/Warmup-2/string_splosion.py | 733 | 3.875 | 4 |
#finalString += string[:1]
#finalString += string[:1]
#finalString += string[1:2]
#finalString += string[:1]
#finalString += string[1:2]
#finalString += string[2:3]
#finalString += string[0:len(string)]
#for i in range (0,len(string)):
# print i
# if i < 1:
# finalString += string[:1]
# finalString += string[:1]
#... |
9348a3fa989ff2fc59359c38087848282102afdf | Connor-Knabe/Coding-Challenges | /Python/Warmup-2/string_splosion2.py | 453 | 3.703125 | 4 | def string_splosion(str):
finalString = ""
for i in range (len(str)):
if i == 0 and len(str) == 1:
return str
if i == 0 and len(str) > 0:
finalString += str[0]
finalString += str[0]
elif i == 1:
finalString += str[1]
elif i == 2:
finalString += str[0:3]
elif... |
694e64ee38f254fa5b8752244ef10506bd65a7eb | johncmk/cloud9 | /mergeSort_rec.py | 1,087 | 3.96875 | 4 |
def mergeSort(li):
if len(li) <= 1:
return
_mergeSort(li,0,len(li)-1)
def _mergeSort(li,low,high):
if low < high:
mid = low + (high-low)/2
_mergeSort(li,low,mid)
_mergeSort(li,mid+1,high)
merge(li,low,mid,high)
def merge(li,low,mid,high):
n1 = mid-... |
adda6bb2f0135b9be266991c0169301473211b64 | johncmk/cloud9 | /factory.py | 490 | 3.671875 | 4 | '''factory pattern'''
class Dog:
def __init__(self, name):
self._name = name
def speak(self):
return 'woof'
class Cat:
def __init__(self, name):
self._name = name
def speak(self):
return 'meow'
def get_pet(pet='dog'):
... |
456c44c29197f6b79b506c44c6c9a9fe8058881d | johncmk/cloud9 | /medians_optmized.py | 2,009 | 3.890625 | 4 | import heapq
'''
Median rule when both heap sizes are equivalent
a) get the mean of two selected elements
b) get always the lower one
c) get always the higher one
d) randomly choose between two
default) select option 'a' from above
'''
import random
def mid_rule(max_h,min_h,rule='a'):
#python switch statement
... |
e36b35531c6c9cd1d48867b7c0a3847cc19bd112 | yhyoscar/codingpractice | /python/di_robot.py | 2,081 | 3.6875 | 4 |
class Robot:
def __init__(self, x, y, direction):
self.x = x
self.y = y
self.direction = direction
def move(self, grid):
ny = len(grid); nx = len(grid[0])
if self.direction == 0:
if self.x >= nx-1: return False
if grid[self.y][self.x+1] != 1: s... |
2e2bfbdb04fc2b8d226ccfb25ff679cec99b6c2d | yhyoscar/codingpractice | /python/lc490_maze_bfs.py | 1,278 | 3.875 | 4 |
def maze_bfs(array, start, target):
nx = len(array[0]); ny = len(array)
directions = [[1,0], [0,1], [-1, 0], [0, -1]]
queue = [start]
current = start
while len(queue) > 0 and not (current[0] == target[0] and current[1] == target[1]):
current = queue.pop(0)
array[current[1]][current[... |
37c6a76119307592a40a17a6ec66df80c3d57063 | yhyoscar/codingpractice | /python/gfg_FAQ1.9_digitsum.py | 1,491 | 3.90625 | 4 | #Given two numbers represented by two lists, write a function that returns sum list. The sum list is list representation of addition of two input numbers.
#Input:
# First List: 5->6->3 // represents number 365
# Second List: 8->4->2 // represents number 248
# Output
# Resultant list: 3->1... |
91415f73d11c8e1a47b00b9123e34e50e355b990 | yhyoscar/codingpractice | /python/di_string_onebyone.py | 709 | 3.609375 | 4 |
from collections import defaultdict
def findtop(freq, clist):
top = 0; c = ''
for x in clist:
if freq[x] > top:
c = x
top = freq[x]
return c, top
def reorder(string):
freq = defaultdict(lambda: 0)
for c in string:
freq[c] += 1
ctop, ftop = findtop(freq,... |
e2936d6a35cbd6a891003c77e52049e698672aa0 | yhyoscar/codingpractice | /python/cci_1.8_rotation.py | 679 | 4.28125 | 4 | # Assume you have a method isSubstring which checks if one word is
# a substring of another. Given two strings, s1 and s2, write code
# to check if s2 is a rotation of s1 using only one call to isSubstring
# (i.e., “waterbottle” is a rotation of “erbottlewat”).
def issubstring(s1, s2):
if s1 in s2: return T... |
c9ba556fceabebb29ee9e22ab1a4cf1ca22843b3 | yhyoscar/codingpractice | /python/cci_string.py | 472 | 3.828125 | 4 |
def remove_duplicate(string):
if string is None: return None
if len(string) < 2: return string
slist = list(string)
exist = [False for i in range(256)]
exist[ord(string[0])] = True
for i in range(1, len(string)):
if exist[ord(string[i])]:
slist[i] = ''
else:
... |
0546fdb7c15779712ebcfdf6a0fd720df81c52df | yhyoscar/codingpractice | /python/cci_2.5_circularlist.py | 825 | 4.25 | 4 | # Given a circular linked list, implement an algorithm which returns node at the beginning of the loop.
# DEFINITION
# Circular linked list: A (corrupt) linked list in which a node’s next pointer points to an earlier node,
# so as to make a loop in the linked list.
# EXAMPLE
# input: A -> B -> C -> D -> E -> C [the sa... |
589bf145fed911c42a3268499c394df2a4ec4ae1 | Shiro7940/Text-To-DTMF-Encryption | /Text-to-DTMF-Encryption.py | 3,927 | 3.734375 | 4 | '''
Text-to-DTMF-Encryption
A simple Python script utilizing opentone to encode/decode DTMF wave file
(pip install opentone) https://github.com/HelloChatterbox/OpenTone
Considering the speed and reliability, the default duration and pause
is 100ms and 10ms respectively.
Tip:
If you change the "ascii" at line 41 ... |
7c773f426085053fa4711f56a1449731acd03443 | timvan/reddit-daily-programming-challenges | /consecutive_distance_rating.py | 1,846 | 4.21875 | 4 | """
[2017-10-09] Challenge #335 [Easy] Consecutive Distance Rating
https://www.reddit.com/r/dailyprogrammer/comments/759fha/20171009_challenge_335_easy_consecutive_distance/
Description
We'll call the consecutive distance rating of an integer sequence the sum of the distances between consecutive integers.
Consider the... |
aebae9e041954f72c7939b94e347a6d7ca50640b | timvan/reddit-daily-programming-challenges | /talking_clock.py | 1,761 | 4.28125 | 4 | """
[2017-06-27] Challenge #321 [Easy] Talking Clock
https://www.reddit.com/r/dailyprogrammer/comments/6jr76h/20170627_challenge_321_easy_talking_clock/
Description:
No more hiding from your alarm clock! You've decided you want your computer to keep you updated on the time so you're never late again. A talking clock... |
397f8dc8fea64bd44cb65cc6d484a05d948b5291 | tfarnecim/Exercicio-Pilha | /maximo de elementos.py | 427 | 3.765625 | 4 | def tira(lista):
return lista.pop()
#maximo de elementos 5
def coloca(lista,v):
if(len(lista) < 5):
lista.append(v)
return "FOI POSSIVEL COLOCAR"
else:
return "NAO FOI POSSIVEL COLOCAR"
def topo(lista):
return lista[len(lista)-1]
def Vazia(lista):
if(len(... |
30c7bd7941b20729947cd82aa21579b5f699d427 | Steven-Reeves/Rocksat-C_DMS | /Python code/Archive/Connection_test.py | 1,010 | 3.53125 | 4 | # Author: Steven Reeves
# Co-author: Andy Horn
# Last Modified: 4/4/18
#
# Testing connection between Arduino and Raspberry Pi using GPIO pins and Serial data transmission
import serial
import RPi.GPIO as GPIO # Only installable ON the Pi, will not run on Windows.
from DataThread import DataThread
import time
# Add... |
53e4f9ca375f28dcd4006836fe84b5db3501f079 | darloboyko/py_courses | /homeworks/home_work_14/oddOrEven_02.py | 528 | 4.4375 | 4 | #Task:
#Given a list of integers, determine whether the sum of its elements is odd or even.
#Give your answer as a string matching "odd" or "even".
#If the input array is empty consider it as: [0] (array with a zero).
#Examples:
#Input: [0]
#Output: "even"
#Input: [0, 1, 4]
#Output: "odd"
#Input: [0, -1, -5]
#Output: "... |
85822d019209a4f501772da9c5a1a82e071171b6 | darloboyko/py_courses | /codewars/kata_8/task_04.py | 705 | 4.1875 | 4 | #Your task is to make a program takes in a sentence (without puncuation), adds all words to a
# list and returns the sentence as a string which is the positions of the word in the list.
# Casing should not matter too.
##Example
# "Ask not what your COUNTRY can do for you ASK WHAT YOU CAN DO FOR YOUR country"
# become... |
02658ef2fcac0f6924de8a2dacc71ec8f8ad92cd | darloboyko/py_courses | /homeworks/home_work_9/UniqueNumber.py | 426 | 3.921875 | 4 | #3. Написать программу, которая на вход принимает список чисел и проверяет,
#все ли числа в этой последовательности уникальны
import random
i = 10
lst_1 = []
while i > 0:
lst_1.append(random.randint(0, 100))
i -= 1
print(lst_1)
print("True") if len(set(lst_1)) == len(lst_1) else print("False")
... |
22860b03e33f35e8416a7e1dbd011e43fca416b7 | darloboyko/py_courses | /homeworks/home_work_10/DifAge.py | 692 | 3.671875 | 4 | #1 Посчитать разницу в возрасте между самым старым и самым молодым членом семьи
#Вводные условия:
#Словарь может отличаться наличием или отсутствием ключей.
#Так что лучше не привязываться к определенным ключам
family = {
'grandpa': ('Alex', 76),
'grandma': ('Nona', 74),
'dad': ('Greg', 48),
'mom': ('July', 4... |
6ec1971543d149e72a76b92df6789684debba80f | darloboyko/py_courses | /homeworks/home_work_7/PseudoBinaryString.py | 853 | 3.96875 | 4 | #4. Написать программу, которая построит псевдо бинарную строку.
#Будет дана строка, которая состоит только из цифр (сделать соответствующую проверку)
#Нужно заменить все числа, которые меньше 5 на 0, остальные, которые равны 5 и больше на 1
#Ответом будет одна строка
#Начальную строку ввести с клавиатуры
#Пример: 4756... |
565ca9b7b989aa90f7da6c3ef1307673a3d97ffa | darloboyko/py_courses | /homeworks/home_work_3/task_03.py | 480 | 4.53125 | 5 | #Написать программу, которая будет запрашивать число в десятичной форме и
#будет выводить значение числа в двоичной, восьмеричной и шестнадцатеричный системе
#(использовать встроенные функции)
n = int(input("Enter n in decimal scale of notation: "))
a = bin(n)
print(a)
b = oct(n)
print(b)
c = hex(n)
print(c)
|
e55b9adb7e2ca850422afe7660e08a6dd7664daa | darloboyko/py_courses | /homeworks/home_work_2/part_1/triangle.py | 224 | 4.09375 | 4 | print("Calculating the area of a triangle")
leg_k1 = float(input ("Enter leg_k1 (mm): "))
leg_k2 = float(input ("Enter leg_k2 (mm): "))
area_triangle = 0.5*leg_k1*leg_k2
print("Area of a triangle =", area_triangle, "mm2") |
31102a03a2e414ac07465ebf487817ae9c6b13c9 | darloboyko/py_courses | /lectures/lectures_03/converter_9.py | 170 | 3.859375 | 4 | a = int(input ("Enter a "))
b = int(input ("Enter b "))
print(a, b)
c = a
a = b
b = c
print(a, b)
a = a + b
b = a - b
a = a - b
print(a, b)
a, b = b, a
print(a, b)
|
180e80ce14dd91723deb65a835f570132b3ad351 | darloboyko/py_courses | /homeworks/home_work_13/dataDay.py | 738 | 3.625 | 4 | from datetime import date, datetime
import os
def read_file(src_relative):
return open(src_relative, 'r')
def data_convert_to_dict(str_from_file):
dict = {}
for line in str_from_file:
date = line.strip().split(',')
dict[date[0]]=date[1]
return dict
def return_count_days(dict):... |
d27a378998e9132df62cf23011b881509ff2d757 | darloboyko/py_courses | /homeworks/home_work_15/paginationHelper.py | 2,017 | 3.890625 | 4 | # TODO: complete this class
class PaginationHelper:
# The constructor takes in an array of items and a integer indicating
# how many items fit within a single page
def __init__(self, collection, items_per_page):
self.collection_len = len(collection)
self.items_per_page = items_per_page
# r... |
cd3a5254bac78ea0bf4f33a6c358c1c760934253 | darloboyko/py_courses | /codewars/kata_7/matrixExpansion_06.py | 976 | 4.34375 | 4 | #Expansion is performed for a given 2x2 matrix.
#
#[
# [1,2],
# [5,3]
#]
#After expansion:
#[
# [1,2,a],
# [5,3,b],
# [c,d,e]
#]
#a = 1 + 2 = 3
#b = 5 + 3 = 8
#c = 5 + 1 = 6
#d = 3 + 2 = 5
#e = 1 + 3 = 4
#Final result:
#[
# [1,2,3],
# [5,3,8],
# [6,5,4]
#]
#TASK
#Let expansion be a function which takes two arg... |
b0e0bdac9bba5eb9ae9fd1e5064bd5795f56509b | darloboyko/py_courses | /homeworks/home_work_14/sumOfABeach_05_14.py | 776 | 4.1875 | 4 | #Beaches are filled with sand, water, fish, and sun. Given a string, calculate how many times
#the words "Sand", "Water", "Fish", and "Sun" appear without overlapping (regardless of the case).
#Examples
#sum_of_a_beach("WAtErSlIde") ==> 1
#sum_of_a_beach("GolDeNSanDyWateRyBeaChSuNN") ==> 3
#sum... |
b445e9d82121f8f5cd29ee0916ee5434b3ffa595 | darloboyko/py_courses | /homeworks/home_work_5/SumList.py | 446 | 4.1875 | 4 | #3. Написать программу, которая посчитает сумму всех элементов в списке
#Список задать в самой программе в виде: list = [1, 5, 68, 0]
#В нем может быть сколько угодоно элементов
lst = [23, 45, 65, 4, 2, 87, 95]
sum_numbers = 0
for i in lst:
sum_numbers += i
print(f"Sum of all numbers in the list: {sum_numbers}") |
6ac96418f9ecce77968630e9671b04d2961ce870 | darloboyko/py_courses | /homeworks/home_work_11/diffArray_1.py | 739 | 3.859375 | 4 | #Your goal in this kata is to implement a difference function, which subtracts one
# list from another and returns the result.
#It should remove all values from list a, which are present in list b keeping their order.
##array_diff([1,2],[1]) == [2]
#If a value is present in b, all of its occurrences must be removed fr... |
fbf0bb2f2b8c8321c7866976110f39817329cf07 | darloboyko/py_courses | /lectures/lectures_04/condition.py | 342 | 4.28125 | 4 | print("Let's calculate BMI")
weight = float(input("Enter weight: "))
height = float(input("Enter height: "))
bmi = round(weight / (height*height), 1)
print("BMI =", bmi)
if bmi <= 20:
print("Underweight")
elif 20 < bmi <= 30:
print("Normal")
elif 30 < bmi <= 40:
print("Extra")
elif bmi > 40:
pri... |
8853ec6dbc9aa3911de9062bde6647eb35086adc | darloboyko/py_courses | /homeworks/home_work_2/part_2/number_10.py | 117 | 3.84375 | 4 | from math import*
x = float(input("Enter x: "))
print(round((1/3)*(sqrt(abs(sin(x))))*(pow(exp(0.12*x), 1/3)), 3)) |
29f8197b0b6633b74c8d8d79474a302c7c5022f7 | jonathaw/PyCharm_Projects | /untitled/enumeratingKmersLexicographically.py | 272 | 3.8125 | 4 | list_ch = ['V', 'H', 'T', 'A', 'G', 'E', 'O', 'L', 'R']
n = 2
def theLoop( list, i, n, message):
for l in list:
if i < n:
theLoop(list, i+1, n, message+l)
elif i == n:
print message+l
theLoop( list_ch, 1, n, '')
print list_ch |
808fc40043d8796a83efa75ae189ac0538204f9d | afshinrahimi/textylon | /textylon/tokenizer/tokenizers.py | 3,447 | 3.78125 | 4 | '''
Created on Mar 14, 2014
@author: af
'''
import re
class AbstractTokenizer(object):
'''
this is an abstract class for tokenizers
'''
tokens = []
__text = None
def setText(self, text):
'''
This function sets the text of this tokenizer and clears the token list. This functi... |
f9749ac53837d57fc419099ab3765dc012bb06f4 | ChrisY0910/Python-Proj-by-Hackermans | /guessing_game.py | 1,731 | 4.21875 | 4 | # Guessing Number Game
import random
import math
print("Welcome to the Guessing Number game!")
print("You will be chosen an option for the diffculty of the game.")
print("Try guessing the correct number, it will either tell you the number is too high or too low.")
print("Once you got it, you will be displayed the amou... |
8840b0ec134524d97abbd298b5849a8771af12c9 | SaranSundar/Leetcode | /ArrayAndStrings/max_area.py | 643 | 3.765625 | 4 | from typing import List
"""
Time complexity : O(n). Single pass.
Space complexity : O(1). Constant space is used.
"""
def maxArea(self, height: List[int]) -> int:
start = 0
area = 0
end = len(height) - 1
while start < end:
current_area = min(height[start], height[end]) * (end - start)
... |
5384a20a3612cbb80d7277e605c7e277d4478f07 | SaranSundar/Leetcode | /Mock/relativeSortArray.py | 474 | 3.625 | 4 | from typing import List
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
map = {}
for i in range(len(arr2)):
map[arr2[i]] = i
def custom_key(key):
if key in map:
return map[key]
else:
return (len(arr2)) + key
# Returns the or... |
1ea2772d18ae5db5c280312be8294b86f7530329 | SaranSundar/Leetcode | /Trees/PopulatingNextRightPointersToEachNode.py | 875 | 3.765625 | 4 | class Node:
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
self.val = val
self.left = left
self.right = right
self.next = next
class Solution:
""""""
# https: // leetcode.com / problems / populating - next - right - pointe... |
1c3a4fce229adc7bf19084e66ef1701289b27e53 | SaranSundar/Leetcode | /Recursions/wordSearch.py | 1,487 | 3.734375 | 4 | from typing import List
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
for r in range(len(board)):
for c in range(len(board[r])):
if board[r][c] == word[0]:
if board[r][c] == word or self.helper_dfs(board, r, c, word):
... |
bc54490651e1ed07877bcbc0b9fb4e8cf7334a28 | SaranSundar/Leetcode | /BFS/MinimumKnightMoves.py | 792 | 3.578125 | 4 | import heapq
from collections import deque
def get_knight_neighbors(cell):
directions = [(1, 2), (-1, 2), (2, 1), (-2, 1), (1, -2), (-1, -2), (2, -1), (-2, -1)]
neighbors = []
for direction in directions:
neighbors.append((cell[0] + direction[0], cell[1] + direction[1]))
return neighbors
de... |
66aa01db5d9da67ced07681c78cdaef5233e5659 | SaranSundar/Leetcode | /ArrayAndStrings/romanToInt.py | 1,157 | 4.0625 | 4 | values = {
"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000,
"IV": 4,
"IX": 9,
"XL": 40,
"XC": 90,
"CD": 400,
"CM": 900
}
def romanToInt(self, input_str: str) -> int:
"""
Time complexity : O(1).
This is a problem limitation, normally its ... |
4c19315fbda626712daed5c36719cdaed77fcb9f | rodrigogazevedo/treinamento_cesar | /ListaDeQuestões/Questao2.py | 317 | 4 | 4 | name = input("Informe seu nome: ")
password = input("Informe sua senha: ")
while (name == password):
print("Nome e senha não podem ser iguais!")
print("Informe as informações novamente")
name = input("Informe seu nome: ")
password = input("Informe sua senha: ")
print(f"Acesso autorizado, {name}")
|
21c6169639187e765ded43390386a6db8f5209c9 | icodecamp/module5_banking | /banking.py | 2,179 | 3.75 | 4 | friends_account = {
'Ross': {'Name': 'Ross', 'ID': 1234567890, 'Checking': 4009.98, 'Savings': 2334.90},
'Chandler': {'Name': 'Chandler', 'ID': 1223456789, 'Checking': 5678.98, 'Savings': 87.90},
'Joey': {'Name': 'Joey', 'ID': 1029384756, 'Checking': .98, 'Savings': 599.87},
'Monica': {'Name': 'Monica', 'ID': 111... |
d18e87c8df473652d65d206e926535d5e4c66f1c | sersavn/practice-codesignal | /Arcade/Intro/StringsRearrangement.py | 1,228 | 3.78125 | 4 | '''
Given an array of equal-length strings, check if it is possible to rearrange the strings in such a way
that after the rearrangement the strings at consecutive positions would differ by exactly one character.
Example
For inputArray = ["aba", "bbb", "bab"], the output should be
stringsRearrangement(inputArray) = fa... |
20742f8f2d03369768c27b77d22b0047062344f3 | sersavn/practice-codesignal | /PVP/03012018.py | 620 | 3.78125 | 4 | import re
def caseUnification(inputString):
changesToMakeUppercase = len(re.findall('[a-z]', inputString))
changesToMakeLowercase = len(re.findall('[A-Z]', inputString))
if (changesToMakeUppercase == 0
or changesToMakeLowercase == 0
or changesToMakeUppercase < changesToMakeLowercase):
... |
5d6cd29bd7c07f5ff89a3cce7bb6ebaa3b245b8e | sersavn/practice-codesignal | /onlydigit.py | 259 | 3.828125 | 4 | #Input:
#inputString: "var_1__Int"
#Output:
#"1"
#Expected Output:
#"1"
#Console Output:
#Empty
import re
a = str(input("INPUT!", ))
def firstDigit(inputString):
return re.search('[0-9]', inputString).group(0) #what is group?
print(firstDigit(a))
|
db00214d9f4c6abe494bc0e3d006be82cda83b0f | sersavn/practice-codesignal | /Arcade/Core/ArrayPacking.py | 411 | 3.65625 | 4 | '''
Example
For a = [24, 85, 0], the output should be
arrayPacking(a) = 21784.
An array [24, 85, 0] looks like [00011000, 01010101, 00000000] in binary.
'''
def arrayPacking(a):
bin_num = []
for i in a:
bin_right = str(format(i,'b'))
bin_right = (8-len(bin_right)) * '0' + bin_right
bi... |
6408b4e6340a5dd01da7b47412759aadb924b308 | efimenka/GB_Python | /lesson_1.py | 4,213 | 4.25 | 4 | #1. Поработайте с переменными, создайте несколько, выведите на экран, запросите у пользователя несколько чисел и строк и сохраните в переменные, выведите на экран.
a = int(input("Введите первое число:"))
b = int(input("Введите второе число:"))
print("Сумма =", a + b)
print("Разность =", a - b)
print("Произве... |
92b05b028d3ccf377f72cf1f5a1127a44874ab1d | AnkurGel/Backup | /pe17_nisargs_py.py | 1,246 | 3.84375 | 4 | words={0:'',1:'one',2:'two',3:'three',4:'four',5:'five',6:'six',7:'seven',8:'eight',9:'nine',10:'ten',11:'eleven',12:'twelve',13:'thirteen',14:'fourteen',15:'fifteen',16:'sixteen',17:'seventeen',18:'eighteen',19:'nineteen',20:'twenty',30:'thirty',40:'forty',50:'fifty',60:'sixty',70:'seventy',80:'eighty',90:'ninety',100... |
241da4f24b9a306c81cea10d60a52dd78bf6e58e | SigmaQuan/BOOK-CODE-Learning.Python.The.Hard.Way | /lesson_17.py | 1,618 | 4.25 | 4 | """
Exercise 17: More Files
Now let's do a few more thing with files. We'll write a Python to copy
one file to another. It'll be very short bu will give you ideas about
other things you can do with files.
"""
from sys import argv
from os.path import exists
script, from_file, to_file = argv
print "Copying... |
8a95f9363d8cfce24cc5be4fbae6af5467416a7f | SigmaQuan/BOOK-CODE-Learning.Python.The.Hard.Way | /lesson_49.py | 8,423 | 4.375 | 4 | """
Exercise 49: Making Sentences
What we should be able to get from our little game lexicon scanner is a
list that looks like this:
# >>> from ex48 import lexicon
# >>> lexicon.scan("go north")
# [('verb', 'go'), ('direction', 'north')]
# >>> lexicon.scan("kill the princess")
# [('verb', 'kill'), ('stop', 'the'), ('... |
5b0d924dc3f8f8206201cf99a58b3c62f712ed14 | SigmaQuan/BOOK-CODE-Learning.Python.The.Hard.Way | /lesson_10.py | 1,742 | 4.28125 | 4 | """
Exercise 10: What Was That?
"""
tabby_cat = "\tI'm tabbed in."
persian_cat = "I'm split\non a lie."
backslash_cat = "I'm \\ a \\ cat."
fat_cat = """
I'll do a list:
\t* Cat food
\t* Fishies
\t* Catnip\n\t* Grass
"""
print tabby_cat
print persian_cat
print backslash_cat
print fat_cat
"""
Escape Sequences
Th... |
1e7df1e9884bc7761c533e6a706e3be83932f73c | SigmaQuan/BOOK-CODE-Learning.Python.The.Hard.Way | /lesson_16.py | 1,566 | 4.71875 | 5 | """
Exercise 16: Reading and Writing Files
If you did the Study Drills from the last exercise you should have seen
all sorts of commands (methods/functions) you can give to files. Here's
the list of commands I want you to remember:
close()-- Closes the file. Like File->Save.. in your editor.
... |
a9870e9235c4800f9ff69951d53e03d038b2bb89 | SigmaQuan/BOOK-CODE-Learning.Python.The.Hard.Way | /lesson_28.py | 1,629 | 4.3125 | 4 | """
Exercise 28: Boolean Practice
The logic combinations you learned from the last exercise are called
"boolean" logic expressions. Boolean logic is used everywhere in
programming. It is an essential fundamental parts of computation and
knowing them very well is akin to knowing your scales in music.
... |
7d01527a93d4d90efa140be6dd41e47210c6d3b3 | tmcook23/NICAR-2016 | /intro-to-python/part1/2_workingwstrings_inclass.py | 3,169 | 4.875 | 5 | # #STRINGS
# At its most basic, a string is just text - it can be displayed like this
print "Hello, world!"
print "Welcome to Denver, NICARians!"
# Let's create a variable assigned to a string instead.
# In Python, you don't have to declare a variable before you assign a value to it.
# Just give it a name and assi... |
aa37f77a656abcc10ff6dfe85cc7d5d5b349942b | SilversMind/Battleship | /Ship.py | 3,012 | 3.734375 | 4 | #! /usr/bin/python
# -*- coding: utf-8 -*-
# Author: Samy Sidhoum
"""[application description here]"""
import random
from tkinter import Label, NW
from PIL import Image, ImageTk
# Affect pictures according to the ship sizes
size_to_ship = {1: 'battleships_img/submarine.gif',
2: 'battleships_img/torpedo... |
2d906b752ca732b7f0b67774d379f62d52a34ced | jpsryan/Python | /SGE_Main.py | 10,100 | 3.546875 | 4 | '''
============================== SGE_Main =========================================
Collection of methods for a single game of poker
=================================================================================
'''
import random
import RankingsSystem
# =======================================... |
fb5201e9104a65c0f145c6f13c75aa894217c63f | MishaLatyshev/IndividualWork2 | /3.py | 131 | 4.15625 | 4 | radius = float(input("Введите радиус круга:"))
area = 3.14*(radius**2)
print("The area of this circle is:",area)
|
d872bcd8841c4c79cb798631700289ef893ab232 | iFun/Project-Euler | /14.Longest Collatz sequence.py | 218 | 3.609375 | 4 | def collatz(n): return n // 2 if n%2 == 0 else 3*n + 1
def distance(n, cache={1:1}):
if n not in cache: cache[n] = distance(collatz(n)) + 1
return cache[n]
print(max(range(1,1000000), key=distance)) |
a2bd10469f04c8e6da0815ce4bbaf88d15cea496 | RShef/Brute-Force--Common-Password-Hacker | /pass_hacker.py | 2,690 | 3.6875 | 4 | import sys
import socket
from string import ascii_letters, digits
from itertools import product
import itertools
def send_pass(client_socket, password):
"""
Checks if a given password (input) is the correct password.
:param client_socket: The connection to the server.
:param password: The password to ... |
623839b1fea1aaad62cfebf21777bf7e3ea29cae | Elvin-Arrow/Python-101 | /Functions Lab Task 3.py | 222 | 3.96875 | 4 | def listsum(num):
n_sum = 0
for i in num:
n_sum += i
return n_sum
num = []
for i in range(5):
num.append(int(input("Enter a number: ")))
print(listsum(num))
|
748818c30c3888fcbedb6449787b79e4d5b008b0 | CoderBryGuy/BreakContinue | /BreakContinue.py | 275 | 3.6875 | 4 | _author_ = 'dev'
# Modify this loop to stop when i is exactly divisible by 11
# for i in range(0, 100, 7):
# print(i)
# if i != 0 and i % 11 ==0:
# break
#
for i in range(1,20):
if i % 3 == 0 or i % 5 == 0:
continue
else:
print(i)
|
b184a4397cbe36b376920bb44eecbe3284eec9e8 | jammaligad/IT-310C---Django-Web-Development | /Activity 1/Maligad_Activity01.py | 319 | 3.734375 | 4 | # Maligad, Juan Alphonso D.
# 11/07/2018
# Activity 1
import random
words = ["warts n straw", "radar", "Racecar", "python"]
txt = random.choice(words)
print("The word is: %s" % (txt))
a = txt.lower()
b = reversed(a)
def palindrome(x):
y = list(x) == list(b) and "True" or "False"
print(y)
palin... |
fea0aa8ef5f6739120245a97a99ac0ecace9ea43 | stabbysaur/reinforcement | /tabular_q.py | 2,426 | 3.515625 | 4 | """
2018-10-04
Exercise from Arthur Juliani's RL tutorial (adapted for Pytorch)
Part 0: Q-Learning with Tables and Neural Networks
Update rule (Bellman):
Q(s, a) = r + gamma * (max(Q(s', a')))
The expected long-term reward for a given action = immediate reward +
discounted future reward of the best future ... |
0b4a72d8c6e6064a013cac7e0020aea6f236ec0c | anouard24/problem-solving | /hackerrank/equal.py | 431 | 3.546875 | 4 | # https://www.hackerrank.com/challenges/equal/problem
def getn(x):
s = x // 5
x %= 5
s += x // 2
x %= 2
s += x
return s
def equal(arr):
arr.sort()
s = 0
for i in arr:
s += getn(i - arr[0])
return s
if __name__ == "__main__":
t = int(input())
for _ in range(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.