blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
1f3888a1032344825cbbbe98d29265499d3e5c74 | careynation/python_class | /Chapter2/exercise2.py | 370 | 4.03125 | 4 | # @author Carey Nation
# @title Chapter 2, Exercise 2
# @description Calculate profit
PROFIT_MARGIN = 0.23
total_sales_s = input("Please enter your total sales: ")
try:
total_sales = float(total_sales_s)
profit = total_sales * PROFIT_MARGIN
print("Your profit is: %2.2f" % profit)
except:
print(total_sales_s + " is not a valid number, please try again.") |
211f1e368438f0ed837b4ffa0651de54e920f697 | rich-s-d/Python-Tutorial | /AdventOfCode/day4_part1.py | 1,140 | 3.578125 | 4 |
# My overcomplicated answer for part 1.
# Looked for a better example for part 2 from the the megathread.
# I was relying too much on conditional if statements. Better to use key validation.
def group_passports(txt_file):
# Groups passports based on a single blank line of seperation in text file.
contents = txt_file.read()
groups = [[line.split(" ") for line in group.split(
"\n")] for group in contents.split("\n\n")]
return groups
with open(passport_file, 'r') as f:
groups = group_passports(f)
flattened = []
for group in groups:
new_group = []
for sublist in group:
for item in sublist:
new_group.append(item)
flattened.append(new_group)
password_valid = 0
password_7fields_but_invalid = 0
password_invalid = 0
for group in flattened:
count = 0
condition = 'cid'
if len(group) >= 7:
for item in group:
if item[0:3] != condition:
count += 1
if count == 7:
password_valid += 1
print(password_valid)
|
b07e2afc7b72fc7c3307ac6f9fc55fa1c5a85b41 | Ran4/dd1331-public | /ex01/grupdat/ran_sekunder.py | 620 | 3.546875 | 4 | #!/usr/bin/env python3
"""
2. Pythonkramaren, uppgift 24: Skriv ett program som frågar efter ett antal
sekunder och skriver ut hur många dagar, timmar, minuter och sekunder det är.
Lösning: [sekunder.py](sekunder.py).
"""
totalt_antal_sekunder = int(input("Hur många sekunder? "))
rest_sekunder = totalt_antal_sekunder % 60
rest_minuter = (totalt_antal_sekunder // 60) % 60
rest_timmar = (totalt_antal_sekunder // (60*60)) % 24
rest_dagar = (totalt_antal_sekunder // (60*60*24))
print("Det blir {} dagar, {} timmar, {} minuter och {} sekunder".format(
rest_dagar, rest_timmar, rest_minuter, rest_sekunder))
|
9752da14fa61d78d4b7a98aca798dabb151f8b98 | OmkarThawakar/Turtle-Programs | /turtle6.py | 335 | 3.84375 | 4 | import turtle
def forward(distance):
while distance > 0:
if (turtle.xcor() > 100
or turtle.xcor() < -100
or turtle.ycor() > 100
or turtle.ycor() < -100):
turtle.setheading(turtle.towards(0,0))
turtle.forward(1)
distance = distance - 1
forward(500) |
69dbbd8239a57a9560ef3707af6f388f852445d9 | thormeier-fhnw-repos/ip619bb-i4ds02-audio-text-alignment | /lib/src/model/Interval.py | 2,694 | 4.1875 | 4 | from typing import Any
class Interval:
"""
Defines and interval with a start and an end
"""
def __init__(self, start: Any, end: Any):
"""
Constructor
:param start: float or character
:param end: float or character
"""
self.start = start
self.end = end
def get_intersection(self, other: "Interval") -> float:
"""
Returns the relative intersection area of this pair with another.
:param other: Interval
:return: float
"""
if not isinstance(self.start, float) \
or not isinstance(self.end, float) \
or not isinstance(other.start, float) \
or not isinstance(other.end, float):
return 0.0
start = self.start if self.start >= other.start else other.start
end = self.end if self.end <= other.end else other.end
area = end - start
return end - start if area >= 0 else 0
def get_union(self, other: "Interval") -> float:
"""
Returns the total area of this pair with another.
:param other: Interval
:return: float
"""
if not isinstance(self.start, float) \
or not isinstance(self.end, float) \
or not isinstance(other.start, float) \
or not isinstance(other.end, float):
return 0.0
start = self.start if self.start <= other.start else other.start
end = self.end if self.end >= other.end else other.end
return end - start
def get_length(self) -> float:
"""
Calculates the length of a this interval
:return: Length, or near-0 or 0 if not appearing at all
"""
if isinstance(self.start, float) and isinstance(self.end, float):
return self.end - self.start
return 0.0
def get_deviation(self, other: "Interval"):
"""
Calculates the deviation of this interval with some other interval
:param other: The other interval
:return: Amount of seconds of deviation
"""
return abs(self.start - other.start) + abs(self.end - other.end)
def to_formatted(self) -> str:
"""
Formats this interval to later fit into audacity label format
:return: Formatted version
"""
start = self.start
end = self.end
if isinstance(self.start, float):
start = "%.15f" % (self.start if self.start is not None else 0.0)
if isinstance(self.end, float):
end = "%.15f" % (self.end if self.end is not None else 0.0)
return str(start) + "\t" + str(end)
|
e8436985781595079d7ca2cd2d0b7a8a0fb28d84 | praveenRI007/Basics-of-python-programming | /basics of python programming in 1hour/python basics #6_loops.py | 814 | 3.875 | 4 |
nums = [1,2,3,4,5]
for num in nums:
if num==3:
print('found')
break #comes out of loop
print(num)
print('\n')
for num in nums:
if num==3:
print('found')
continue #goes for next iteration of loop
print(num)
print('\n')
for num in nums:
for letter in'abc':
print(num,letter)
print('\n')
for i in range(1,11):
print(i)
print('\n')
x=0
while x<10 :
if x==5:
break
print(x)
x+=1
#while True:
# print('1') //prints infinite ones press cntrl + C to interrrupt the process
'''
OUTPUTS
1
2
found
1
2
found
4
5
1 a
1 b
1 c
2 a
2 b
2 c
3 a
3 b
3 c
4 a
4 b
4 c
5 a
5 b
5 c
1
2
3
4
5
6
7
8
9
10
0
1
2
3
4
'''
|
7196e03d735b1a571ea41ae7d850b7aad509d10b | Indra2311/BasicPythonProgram | /sumThree_0.py | 1,064 | 4.15625 | 4 | """
* Author - Indrajeet
* Date - 03-06-2021
* Time - 6:02 PM
* Title - Read in N integers and counts the number of triples that sum to exactly 0.
"""
def find_triples(arr, n):
"""
:param arr: containing all the elements
:param n: number of elements
:return:
"""
found = True
count = 0
for i in range(0, n - 2):
for j in range(i + 1, n - 1):
for k in range(j + 1, n):
if arr[i] + arr[j] + arr[k] == 0:
print(arr[i], arr[j], arr[k])
found = True
count = count + 1
print("The number of triples is: ", count)
# If no triplet with 0 sum found in array
if not found:
print(" not exist ")
while True:
try:
array = []
length = int(input("Enter length of array: "))
for i in range(length):
temp = int(input("Enter numbers: "))
array.append(temp)
find_triples(array, length)
break
except ValueError:
print("Check the input")
|
05aeb626bd3f91cbb09b425ccbf719b34910d5bd | embisi-github/gjslib | /tests/primes.py | 2,105 | 3.8125 | 4 | #!/usr/bin/env python
def calculate_x_n_mod_p( x, p, x_n_mod_p=None, n=1 ):
"""
Calculate x^n mod p, returning result. Requires x<p.
A cache of results is kept in x_n_mod_p (dictionary of n => x^n mod p)
If n=0 then x^n mod p =1
If n in x_n_mod_p.keys() then =x_n_mod_p[n]
Else split n into (a,b) = (n/2),(n-n/2) (where n/2 is integer division)
Then x^n = x^(a+b) = x^a . x^b (all mod p)
Get x_a and x_b (recursively) mod p
Multiply x_a by x_b, and find r = remainder after division by p
Set x_n_mod_p[n] = r
Return r
"""
if x_n_mod_p is None: x_n_mod_p={}
if n==0: return 1
if n==1: return x
if n in x_n_mod_p: return x_n_mod_p[n]
a = n/2
b = n-n/2
x_a = calculate_x_n_mod_p( x,p,x_n_mod_p, a )
x_b = calculate_x_n_mod_p( x,p,x_n_mod_p, b )
r = (x_a * x_b) % p
x_n_mod_p[n] = r
return r
def test_is_not_prime( p, xes=(2,3,5), verbose=False ):
for x in xes:
if (x>=p): continue
x_n_mod_p = {}
x_p_mod_p = calculate_x_n_mod_p( x,p,x_n_mod_p, p )
if verbose: print "%d^%d = %d (mod %d)"%(x,p,x_p_mod_p,p)
if x_p_mod_p!=x: return True
pass
if verbose:
print p,"may be prime - tried",xes
pass
return False
#print test_is_not_prime( 11 )
#print test_is_not_prime( 39 )
#print test_is_not_prime( 65537 )
#print test_is_not_prime( 1238561239631, xes=(2,3,5,7,11,13,17,19) )
print test_is_not_prime( 561, xes=range(3,559,2), verbose=True )
print calculate_x_n_mod_p( 2,561,n=(561-1)/2 )
#xes = (2,3) # Works for 100 primes
xes = (2,3,5,7,11,13,17,19,23,29,31,37,41,43,47)
max_p = 542 # 100th prime is 541
xes = (2,3)
max_p = 580
#max_p = 7920 # 1000th prime is 7919
primes = []
for i in range(max_p):
if i<2: continue
if not test_is_not_prime( i, xes ):
primes.append(i)
pass
pass
num_primes = len(primes)
for j in range((num_primes+9)/10):
l = ""
for i in range(10):
if i+j*10 >= num_primes: continue
l += "%5d "%primes[i+j*10]
pass
print l
print len(primes)
print primes
|
7e3ab40de3cad70871aaf36b4b2af7ae5ebb54d9 | emilkloeden/Project-Euler-Solutions | /Python Scripts/12.py | 998 | 3.546875 | 4 | # The sequence of triangle numbers is generated by adding the natural numbers.
# So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28.
# The first ten terms would be:
# 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
# Let us list the factors of the first seven triangle numbers:
# 1: 1
# 3: 1,3
# 6: 1,2,3,6
# 10: 1,2,5,10
# 15: 1,3,5,15
# 21: 1,3,7,21
# 28: 1,2,4,7,14,28
# We can see that 28 is the first triangle number to have over five divisors.
# What is the value of the first triangle number to have over five hundred divisors?
# Answer: 76576500
# 76576500
# Elapsed time: 4.7376 seconds
from timer import timer
from euler import get_factors
@timer
def main():
i = 1
next_triangle_number = 0
divisors = []
NUMBER_OF_DIVISORS = 500
while len(divisors) <= NUMBER_OF_DIVISORS:
next_triangle_number += i
divisors = get_factors(next_triangle_number)
i += 1
return next_triangle_number
if __name__ == '__main__':
main() |
c77b5cef3f3eaf5c710d2438942e4ec860565a1a | BigEggStudy/LeetCode-Py | /LeetCode.Test/TestHelper.py | 980 | 3.640625 | 4 | import sys, queue
sys.path.append('LeetCode')
from ListNode import ListNode
from TreeNode import TreeNode
def generateLinkList(nums: []) -> ListNode:
if nums is None or len(nums) == 0:
return None
head = ListNode(-1)
current = head
for num in nums:
current.next = ListNode(num)
current = current.next
return head.next
def generateTree(nums: []) -> TreeNode:
if nums is None or len(nums) == 0:
return None
index = 0
root = TreeNode(nums[index])
index += 1
q = queue.Queue()
q.put(root)
while not q.empty():
current = q.get()
if index < len(nums) and nums[index] is not None:
node = TreeNode(nums[index])
current.left = node
q.put(node)
if index + 1 < len(nums) and nums[index + 1] is not None:
node = TreeNode(nums[index + 1])
current.right = node
q.put(node)
index += 2
return root
|
a75135952395f51c1d5719c22c90dce6a2c96d75 | Sheep-coder/practice2 | /Python00/chap07list0715.py | 737 | 3.984375 | 4 | # 行列の和を求める(行数/列数/値を読み込む)
print('行列の和を求めます。')
height = int(input('行数:'))
width = int(input('列数:'))
a = [None]*height
for i in range(height):
a[i] = [None]*width
for j in range(width):
a[i][j] = int(input('a[{}][{}] : '.format(i,j)))
b = [None]*height
for i in range(height):
b[i] =[None]*width
for j in range(width):
b[i][j] = int(input('b[{}][{}] : '.format(i,j)))
c = [None]*height
for i in range(height):
c[i] = [None]*width
for j in range(width):
c[i][j] = a[i][j] + b[i][j]
for i in range(height):
for j in range(width):
print('c[{}][{}] = {}'.format(i,j,c[i][j]))
|
8ee75cfac184610c357a7d39f67a19d9c1e93da0 | vfcrawler/TEST190805 | /22.py | 286 | 3.9375 | 4 | def get_missing_letter(str_input):
#方法1 手输a-z字符串
s1 = set('abcdefghijklmnopqrstuvwxyz')
s2 = set(str_input.lower())
# 排序字符串
ret = ''.join(sorted(s1-s2))
return ret
if __name__ == '__main__':
print(get_missing_letter("python"))
|
8f5ba4185a47002a4638172807cce68352a5202a | fainaszar/pythonPrograms | /multithreading/listIdioms.py | 266 | 3.71875 | 4 |
a_list = ['a','b','c','d','e']
print(a_list)
(first,second,*rest) = a_list
print(first)
print(second)
print(rest)
(first,*middle,last) = a_list
print(first)
print(middle)
print(last)
(*head,penultimate,last) = a_list
print(head)
print(penultimate)
print(last) |
9f854bceb4ee2a6fa5dd6354c423c0a55134bab1 | jay3272/python_tutorial | /control/function.py | 415 | 3.546875 | 4 | def ask_ok(prompt,retries=5,reminder='Please try again'):
while True:
ok=input(prompt)
if ok in ('yes'):
return True
if ok in ('no'):
retries=retries-1
if retries<0:
raise ValueError('invalid user response')
print(reminder)
ask_ok('離開按yes或no:')
ask_ok('ok',2)
ask_ok('ok',2,'請再試一次')
|
6cba118aa6688920ff839d2e74a0db88e30eff60 | harkaranbrar7/30-Day-LeetCoding-Challenge | /Week 2/backspace_String_Compare.py | 1,951 | 4.15625 | 4 | '''
Backspace String Compare
Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character.
Example 1:
Input: S = "ab#c", T = "ad#c"
Output: true
Explanation: Both S and T become "ac".
Example 2:
Input: S = "ab##", T = "c#d#"
Output: true
Explanation: Both S and T become "".
Example 3:
Input: S = "a##c", T = "#a#c"
Output: true
Explanation: Both S and T become "c".
Example 4:
Input: S = "a#c", T = "b"
Output: false
Explanation: S becomes "c" while T becomes "b".
Note:
1 <= S.length <= 200
1 <= T.length <= 200
S and T only contain lowercase letters and '#' characters.
Follow up:
Can you solve it in O(N) time and O(1) space?
'''
class Solution1:
def backspaceCompare(self, S: str, T: str) -> bool:
def sim(S):
ans = ''
for c in S:
if c == '#':
if len(ans) > 0: ans = ans[:-1]
else:
ans += c
return ans
return sim(S) == sim(T)
class Solution2:
def backspaceCompare(self, S: str, T: str) -> bool:
stackS, stackT = [], []
for s in S:
if s != "#":
stackS.append(s)
elif stackS:
stackS.pop()
for t in T:
if t != "#":
stackT.append(t)
elif stackT:
stackT.pop()
return stackS == stackT
class Solution3:
def backspaceCompare(self, S: str, T: str) -> bool:
ans_S = ""
ans_T = ""
for s in S:
if s == '#':
if ans_S:
ans_S = ans_S[:-1]
else:
ans_S += s
for t in T:
if t == '#':
if ans_T:
ans_T = ans_T[:-1]
else:
ans_T += t
return ans_S == ans_T
test = Solution3()
print(test.backspaceCompare("a##c","#a#c")) |
7c1f01702ce00efed4b5224d3882a6afa37a7149 | svaccaro/codeeval | /simple_sort.py | 183 | 3.640625 | 4 | #!/usr/bin/env python
from sys import argv
input = open(argv[1])
for line in input:
line = line.rstrip()
nums = sorted(line.split(' '), key=float)
print ' '.join(nums)
|
380378e9c0c7bccc9ebba297f846a1890841adcd | Rhongo15/amazon_scrapper | /amazon_scrapper.py | 1,395 | 3.640625 | 4 | from selectorlib import Extractor
import requests
import json
#getting input from user and appending it to the url
item = input()
item = list(item.split(' '))
item = '+'.join(item)
url = 'https://www.amazon.com/s?k=' + item
#yml file containing the selectors needed to extract data
e = Extractor.from_yaml_file('search_results.yml')
#function to scrape the required data
def data_extractor(url):
headers = {
'dnt': '1',
'upgrade-insecure-requests': '1',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36',
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
'sec-fetch-site': 'same-origin',
'sec-fetch-mode': 'navigate',
'sec-fetch-user': '?1',
'sec-fetch-dest': 'document',
'referer': 'https://www.amazon.com/',
'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8',
}
print("Scraping Data...")
r = requests.get(url, headers=headers)
return e.extract(r.text)
#calling above function
data = data_extractor(url)
#printing results in JSON structure
for product in data['products']:
r = json.dumps(product)
loaded_r = json.loads(r)
print(json.dumps(loaded_r, indent=1))
|
c23aa3913578bc9835c438218be9459fd21e72a1 | DaHuO/Supergraph | /codes/CodeJamCrawler/16_0_3/noahingham/C.py | 1,136 | 3.53125 | 4 | import math
def primes_sieve(limit):
limitn = limit+1
not_prime = set()
primes = []
for i in range(2, limitn):
if i in not_prime:
continue
for f in range(i*2, limitn, i):
not_prime.add(f)
primes.append(i)
return primes
primes = primes_sieve(10000)
def check(s):
global primes
facts=[]
for b in range(2,11):
nb = int(s,b)
good = False
for prime in primes:
if(nb%prime==0 and prime<nb):
facts+=[prime]
good = True
# print(s+", "+str(b)+", "+str(nb)+", "+str(prime))
break
if not good:
return False
print(str(s)+" "+' '.join(map(str,facts)))
return True
def solve(n,j):
count=0
i=0
while(count<j):
s = "1"+('{:0'+str(n-2)+'b}').format(i)+"1"
if(check(s)):
count+=1
i+=1
return ""
if __name__ == "__main__":
testcases = input()
for caseNr in xrange(1, testcases+1):
inp = list(map(int, raw_input().split(" ")))
print("Case #1:")
solve(inp[0], inp[1])
|
d05a3c2f6f1023540917ef410ed54fa1fa19507e | Mohamed711/Intermediate-python-nanodegree | /Lessons Exercises/T9 Predictive Text/gold.py | 1,791 | 3.5625 | 4 | """Reference solutions to each of the pieces of the T9 exercise.
Sure, these are some solutions. They're right here, if you reall need to see them.
"""
import collections
import functools
import operator
from helper import keymap
def parse_content(content):
"""Parse the content of a file into a dictionary mapping words to word"""
words = {}
for line in content.split('\n'):
word, frequency = line.split()
words[word] = int(frequency)
return words
def make_tree(words):
trie = {}
for word, frequency in words.items():
node = trie
for ch in word:
if ch not in node:
node[ch] = {}
node = node[ch]
node[f'${word}'] = frequency
return trie
# def node():
# return collections.defaultdict(node)
# def make_tree(words):
# trie = node()
# for word, frequency in words.items():
# functools.reduce(collections.defaultdict.__getitem__, word, trie)['$'] = (word, frequency)
# return trie
def predict(tree, numbers):
leaves = [tree]
for number in numbers:
letters = keymap[number]
leaves = [leaf.get(letter, None) for letter in letters for leaf in leaves]
while True:
try:
leaves.remove(None)
except ValueError:
break
words = {}
for node in leaves:
while node:
letter, child = node.popitem()
if not isinstance(child, dict): # We have a word!
word, frequency = letter[1:], child
words[word] = frequency
continue
leaves.append(child)
return sorted(words.items(), key=operator.itemgetter(1), reverse=True)
|
1f7a924740b1780834049bf235705239111f17bf | Mrinanka/Bank-Account-by-Python | /Tick tack Toe Game By me.py | 4,832 | 4.09375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[40]:
from IPython.display import clear_output
def display_board(board):
print(" "+'|' +" "+'|'+" ")
print(' '+board[1]+' | '+board[2]+' | '+board[3])
print("______"+'|'+"______"+'|'+"______")
print(" "+'|' +" "+'|'+" ")
print(' '+board[4]+' | '+board[5]+' | '+board[6])
print("______"+'|'+"______"+'|'+"______")
print(" "+'|' +" "+'|'+" ")
print(' '+board[7]+' | '+board[8]+' | '+board[9])
print(" "+'|' +" "+'|'+" ")
# In[41]:
def player_input():
marker='A'
while marker not in ['X','O']:
marker=input("Choose What Do You Want To Be! ('X' or 'O') :\n")
marker=marker.upper()
clear_output()
if marker not in ['X','O']:
print("'Ops!' You did not choose it right.\n Try again")
if marker=='X':
return ['X','O']
else:
return ['O','X']
# In[42]:
def place_marker(board, marker, position):
board[position]=marker
return board
# In[43]:
def win_check(board, mark):
return ((board[7] == mark and board[8] == mark and board[9] == mark) or # across the top
(board[4] == mark and board[5] == mark and board[6] == mark) or # across the middle
(board[1] == mark and board[2] == mark and board[3] == mark) or # across the bottom
(board[7] == mark and board[4] == mark and board[1] == mark) or # down the middle
(board[8] == mark and board[5] == mark and board[2] == mark) or # down the middle
(board[9] == mark and board[6] == mark and board[3] == mark) or # down the right side
(board[7] == mark and board[5] == mark and board[3] == mark) or # diagonal
(board[9] == mark and board[5] == mark and board[1] == mark)) # diagonal
# In[44]:
import random
def choose_first():
x=random.randint(1,2)
if x==1:
return ['Player 1','Player 2']
else:
return ['Player 2','Player 1']
# In[45]:
def space_check(board, position):
return board[position]==' '
# In[46]:
def full_board_check(board):
space=False
for i in range(1,10):
if ' ' in board :
return False
else:
return True
# In[47]:
def player_choice(board):
pos=11
while pos not in range(1,10) or not space_check(board, pos):
pos=input("enter a position of your choice : 1-9 \n")
pos=int(pos)
clear_output()
if pos not in range(1,10):
print("'Ops!' Try a valid number.\n Try again")
if not space_check(board, pos):
print("Opz! That place is already filled \n Try another")
return pos
# In[48]:
def replay():
want='A'
while want not in ['Y','N']:
want=input("Do u want to play again? Y or N")
want=want.upper()
clear_output()
if want not in ['Y','N']:
print("Hey thats not what i asked")
if want=='Y':
return True
else:
return False
# In[ ]:
print('Welcome to Tic Tac Toe!')
while True:
theboard=[' ']*10
display_board(theboard)
mark=player_input()
player=choose_first()
print("You are randomly chosen to be " + player[0] + " And you have choosen "+ mark[0]+ " Good luck!")
game_on=True
while game_on:
print(" Now put your "+mark[0])
pos=player_choice(theboard)
theboard=place_marker(theboard, mark[0], pos)
clear_output()
display_board(theboard)
worn=win_check(theboard, mark[0])
if worn:
print("Congratulations "+player[0]+ "! \n You have defeated " +player[1])
break
else:
pass
space=full_board_check(theboard)
if space:
print('This is a Tie')
break
else:
pass
# Player2's turn.
print(player[1]+"'s Turn, put your "+mark[1])
pos=player_choice(theboard)
theboard=place_marker(theboard, mark[1], pos)
clear_output()
display_board(theboard)
worn=win_check(theboard, mark[1])
if worn:
print("Congratulations "+player[1]+ "! \n You have defeated " +player[0])
break
else:
pass
space=full_board_check(theboard)
if space:
print('This is a Tie')
break
else:
pass
if not replay():
break
# In[ ]:
# In[ ]:
# In[ ]:
|
caf9ea987205d9710b671d75eaa986d4b9214d15 | meyerjo/python-spielereien | /addierer.py | 240 | 3.578125 | 4 | print ("Hallo ich bin der Addi, bitte 2 ZAhlen...")
def start():
a = input ("Zahl 1")
b = input ("Zahl 2")
a = float (a)
b = float (b)
print ("Ergebnis: ")
print (a + b)
x = input()
start()
|
81284e4934c1327195137ccdb40fb4f669a165c8 | susanpray/python | /while.py | 100 | 3.71875 | 4 | counter = 1
while counter <= 5:
print "Type in the", counter, "number"
counter = counter +1 |
def5d3978c2eae8782af06dae41683f14832e0f5 | BenjzB/GUI-Projects | /tKinterTest.py | 627 | 3.8125 | 4 | from tkinter import *
top = Tk()
playList = []
def results():
print(playList)
def addToList():
newItem = E1.get()
playList.append(newItem)
E1.delete(0, END)
#This is a Label widget
L1 = Label(top, text = "Playlist Maker")
L1.grid(column = 0, row = 1)
#This is an Entry widget
E1 = Entry(top, bd = 5)
E1.grid(column = 0, row = 2)
#This is a Button widget
B1 = Button(text = " Print Playlist ", bg = "#c6edee", command = results)
B1.grid(column = 0, row = 3)
B2 = Button(text = "+", bg = "#feebe5", command = addToList)
B2.grid(column = 1, row = 3)
top.mainloop()
|
2e78bf5f820700d4126f5e0e06148b7792c6a933 | ddindi/xyz | /fetch/download_json.py | 491 | 3.546875 | 4 |
import urllib2
import json
def download_json(query = 'https://api.github.com/search/repositories?q=language:python&sort=stars&order=desc',
max_repos = 5):
response = urllib2.urlopen(query)
json_string = response.read()
data = json.loads(json_string)
for i, item in enumerate(data['items']):
if i == max_repos:
break
yield item['name'], item['clone_url']
def main():
for name, clone_url in download_json():
print name, clone_url
if __name__ == '__main__':
main() |
4d15a9cf76205a55ddbff3890596365d43fb826d | SanchitaChavan/Space_Invader | /Game.py | 1,772 | 3.734375 | 4 | import pygame
import random
# Initialize the pygame
pygame.init()
# Create the screen
screen = pygame.display.set_mode((800, 600))
# Title and Icon
pygame.display.set_caption("Space Invaders")
icon = pygame.image.load('si.png')
pygame.display.set_icon(icon)
# Player
playerImg = pygame.image.load('sii.png')
playerX = 370
playerY = 480
playerX_change=0
playerY_change=0
# Enemy
EnemyImg = pygame.image.load('ali.png')
EnemyX = random.randint(0, 800)
EnemyY = random.randint(50, 150)
EnemyX_change = 0.3
EnemyY_change = 100
def player(x, y):
screen.blit(playerImg, (x, y))
# blit means draw
def Enemy(x, y):
screen.blit(EnemyImg, (x, y))
# Game loop ie a window is displayed which closes when close button is pressed
running = True
while running:
# RGB
screen.fill((0, 0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# if key is pressed check right or left
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -0.3
if event.key == pygame.K_RIGHT:
playerX_change = 0.3
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change=0
playerX += playerX_change
if playerX <= 0:
playerX = 0
elif playerX >= 736:
playerX = 736
EnemyX += EnemyX_change
if EnemyX <= 0:
EnemyX_change = 0.3
EnemyY += EnemyY_change
elif EnemyX >= 736:
EnemyX_change = -0.3
EnemyY += EnemyY_change
player(playerX, playerY)
Enemy(EnemyX, EnemyY)
pygame.display.update()
|
2ddee7fad720e8c9b8b797fab6501d180f928d38 | zackmdavis/dotfiles | /bin/fake_italics | 1,111 | 4.0625 | 4 | #!/usr/bin/env python3
"""
Given a text file with Markdown-like underscore-emphases, replace it with one
where the emphases are given as Unicode "mathematical" pseudo-italics
"""
import argparse
import unicodedata
def pseudo_italic(char):
try:
codepoint_name = "MATHEMATICAL ITALIC SMALL {}".format(char.upper())
return unicodedata.lookup(codepoint_name)
except KeyError:
return char
if __name__ == "__main__":
arg_parser = argparse.ArgumentParser(description=__doc__)
arg_parser.add_argument('filename', help="path to file to convert")
args = arg_parser.parse_args()
with open(args.filename, 'r') as in_file:
content_in = in_file.read()
emphasizing = False
transformed = []
for char in content_in:
if char == '_':
emphasizing = not emphasizing
continue
if emphasizing:
transformed.append(pseudo_italic(char))
else:
transformed.append(char)
content_out = ''.join(transformed)
with open(args.filename, 'w') as out_file:
out_file.write(content_out)
|
63d0b325095c80db39284098f683b2585c06b59c | abbindustrigymnasium/python-kompendium-abbkevkla | /Kompendiet/Kompendium_uppgifter_6.2.py | 2,296 | 3.5 | 4 | import requests
#6.1
# siffra = int(input("välj ett heltal annars blir jag arg :) "))
# url = "http://77.238.56.27/examples/numinfo/?integer="+str(siffra)
# r = requests.get(url) #vi sätter värdena vi får i en variabel
# response_dictionary = r.json() #vi använder .json för att göra om innehållet till ett läsbart format
# #print(response_dictionary)
# jämt = response_dictionary["even"]
# if jämt == False:
# a = "inte"
# elif jämt == True:
# a = ""
# primtal = response_dictionary["prime"]
# if primtal == False:
# b = "inte"
# elif primtal == True:
# b = ""
# faktorer = response_dictionary["factors"]
# faktorer2 = ','.join( str(a) for a in faktorer)
# print(str(siffra)+" är "+a+" ett jämt tal. Numret är "+b+" ett primtal. Numrets faktorer är "+faktorer2+".")
#6.2
# print("Stockholm eller Uppsala")
# stad = input("välj en av städerna: ")
# stad = stad.lower()
# url = "https://54qhf521ze.execute-api.eu-north-1.amazonaws.com/weather/"+stad
# r = requests.get(url) #vi sätter värdena vi får i en variabel
# response_dictionary = r.json() #vi använder .json för att göra om innehållet till ett läsbart format
# print("Forecast For "+stad)
# print("*"*75)
# for forecast in response_dictionary["forecasts"]:
# print(forecast["date"]+" "+forecast["forecast"])
# print("*"*75)
#6.3
url = "https://5hyqtreww2.execute-api.eu-north-1.amazonaws.com/artists/"
r = requests.get(url) #vi sätter värdena vi får i en variabel
response_dictionary = r.json() #vi använder .json för att göra om innehållet till ett läsbart format
for artists in response_dictionary["artists"]: #går igenom alla artister och skriver ut dem
print(artists["name"])
pick = input("Pick one of the above: ") #låter användaren välja en artist
for artists in response_dictionary["artists"]: #går igenom alla artister igen
if artists["name"] == pick: #om en namn key stämmer överens med det vi matat in så hämtar vi artistens id
url = url + artists["id"] #vi lägger till id till url
t = requests.get(url) #ny request
response2 = t.json()
for facts in response2["artist"]: #vi går igenom faktan i API'n
print(facts+": " + str(response2["artist"][facts])) #vi skriver ut faktans titel och dess innehåll
|
bcf9384a3ba2dc993e7a171a9f57a487a8e6dd9e | ipa-srd-kd/udacity-python | /debugging/lesson2/time.py | 1,206 | 3.859375 | 4 | class Time:
def __init__(self, h = 0, m = 0, s = 0):
assert 0 <= int(h) <= 23
assert 0 <= int(m) <= 59
assert 0 <= int(s) <= 60
self._hours = int(h)
self._minutes = int(m)
self._seconds = int(s)
def invariant_check(self):
assert 0 <= self.hours() <= 23
assert 0 <= self.minutes() <= 59
assert 0 <= self.seconds() <= 60
def hours(self):
return self._hours
def minutes(self):
return self._minutes
def seconds(self):
return self._seconds
def __repr__(self):
return "{:02d}:{:02d}:{:02d}".format(self.hours(), self.minutes(),
self.seconds())
def seconds_since_midnight(self):
return self.hours() * 3600 + self.minutes() * 60 + self.seconds()
def advance(self, s):
self.invariant_check()
old_seconds = self.seconds_since_midnight()
# some complex code
self.invariant_check()
assert(self.seconds_since_midnight() )
#t = Time(-1, -2, -3)
#print t
#t = Time("two minutes past midnight")
# accepted inputs #
###################
time_vect=[Time(13, 0, 0),
Time(3.14, 0, 0)]
for time_obj in time_vect:
print time_obj
|
5304e5a277ecfd7b3c6f5b29fccc22a8a76fd9f6 | chrislevn/vnlearntocode | /30_Day_Leetcode_Challenge/Week 3/Day15_ProductOfArrayExceptSelf.py | 703 | 3.890625 | 4 | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
"""Calculate the product of other elements of the array, except itself.
Args:
nums: the input array.
Returns:
An array output such that output[i] is equal to
the product of all the elements of nums except nums[i].
"""
result = [1]
current = 1
for i in range(len(nums)-1):
current *= nums[i]
result.append(current)
current = 1
for i in range(len(nums)-1, -1, -1):
result[i] *= current
current *= nums[i]
return result |
49189da9498a3591c9b9d1a65268792acb6d8eee | ekomissarov/edu | /py-basics/uneex_homework/19.py | 1,942 | 3.609375 | 4 | '''
Ввести строку, содержащую произвольные символы (кроме символа «@»).
Затем ввести строку-шаблон, которая может содержать символы @.
Проверить, содержится ли в исходной строке подстрока,
совпадающая со строкой-шаблоном везде, кроме символов @;
на месте @ в исходной строке должен стоять ровно один произвольный символ.
Вывести позицию в строке,
с которой начинается эта подстрока или -1, если её там нет.
Input:
исходной строке подстрока, совпадающая со строкой
ст@ок@
Output:
9
'''
#srch = input("Введите строку: ")
#needle = input("Введите шаблон @: ")
srch = "исходной стXроке подстрока, совпадающая со строкой"
needle = "ст@@ок@"
'''
pointer = absposition = 0
needle = needle.split("@")
notfound = True
while notfound:
notfound = False
p = srch[absposition:].find(needle[0])
if p == -1:
print(-1)
exit(0)
else:
absposition += p
result = absposition
for i in needle:
pointer = srch[absposition:].find(i)
if pointer:
notfound = True
break
absposition += pointer + len(i) + 1
print(result)
'''
patt = []
n = 0
for w in needle.split("@"):
if w:
patt.append((n, w))
n += len(w)
n += 1
for i in range(len(srch) -len(needle)):
for k, w in patt:
if srch[i+k:i+k+len(w)] != w:
break
else:
print(i)
break
else:
if patt or len(srch)>len(needle):
print(-1)
else:
print(0) |
b887d25aa31e2bafc1ed7d6220e747821745f787 | sujaykadam/prac_examples | /Python pracs/L2/pr5.py | 147 | 3.515625 | 4 | #exchange number w/o 3rd var
n1=int(input("Enter first number "))
n2=int(input("Enter second nukmber "))
n1=n1+n2
n2=n1-n2
n1=n1-n2
print(n1,n2)
|
4b4dc99de9dfb95c39636472787862d91d70ca94 | beautyseeker/N-back-task | /Pseudorandom_seq.py | 3,984 | 3.640625 | 4 | import random
import time
class Pseudorandom:
"""基于当前数,n步长后的数一致的概率维持在0.3-0.5间"""
def __init__(self, step=2, interval=1.8, trials=30):
self.step = step # N back中的步长N
self.interval = interval # 数字刷新间隔,单位为秒
self.trials = trials # 数字刷新次数
self.dictate_count = 0 # 报数计数
self.hit = 0 # 命中计数
self.miss = 0 # 丢失计数
self.mistake = 0 # 错误计数
self.consistent = 0 # 一致计数
self.current_num = None # 当前显示数字
self.current_seq = [] # 历史最新序列,序列长度等于步长step
self.current_read = None # 最近读数时间,用于反应时长计算
self.current_click = None # 最新点击时间,用于反应时长计算
self.react_time = [] # 多次点击下的反应时长列表
self.cal_allow = True # 统计允许位,防止单个报数间隔内重复统计计数
@staticmethod
def partial_choice(partial_num):
"""伪随机选择,输入0-9的数,返回一个概率偏向partial_num的0-9随机数"""
partial_prob = 0.3 # 偏向概率为0.3
num_seq = list(range(10))
if random.uniform(0, 1) > partial_prob:
num_seq.remove(partial_num) # 排除偏向数
return random.choice(num_seq)
else:
return partial_num
def dictate(self):
"""如果报数次数少于等于n,则产生0~9的随机数;若报数次数大于n,则产生伪随机数"""
if self.dictate_count < self.step:
# N步长内的数字完全随机
number = random.randint(0, 9)
self.current_seq.append(number)
elif self.dictate_count == self.step:
number = self.partial_choice(self.current_seq[0])
self.current_seq.append(number) # 当前数字入队保持更新但为保证队列长度不出队
else:
# N步长外的数字基于N步前数字偏向选择
number = self.partial_choice(self.current_seq[1])
self.current_seq.append(number) # 当前数字入队保持更新
self.current_seq.pop(0) # 近期数字出队保持更新
self.current_num = number # 更新当前数字
self.dictate_count += 1
self.current_read = time.time() # 读数完后刷新近期读数时间并允许点击统计
self.cal_allow = True
return number
def check_hit_mistake(self):
"""按键时的命中和误操作检查"""
# 这种检查必定在n步报数后进行
self.current_click = time.time()
duration = self.current_click - self.current_read
# print('click:{} read:{} duration:{}'.format(self.current_click, self.current_read, duration))
if self.cal_allow:
"""一个间隔时间内只允许统计一次hit或mistake数,间隔时间外的点击无效"""
if self.current_seq[0] == self.current_seq[-1]:
self.hit += 1
self.react_time.append(duration)
else:
self.mistake += 1
self.cal_allow = False # 每次点击后将禁止统计直至下一次报数后允许,以防重复统计按键次数
def consistent_cal(self):
"""一致数计算"""
if self.current_seq[0] == self.current_seq[-1]:
self.consistent += 1
# def dictate_test(p):
# """如果前后一致频次逼近所设定概率,则认为dictate方法测试通过"""
# ls = []
# c = 0
# epsilon = 0.1
# for k in range(10000):
# ls.append(p.dictate())
# for j in range(p.step, 10000):
# if ls[j-p.step] == ls[j]:
# c += 1
# expect = (p.prop_section[1] + p.prop_section[0]) / 2
# if (c / 10000 - expect) < epsilon:
# print('测试通过')
# else:
# print('测试未通过')
|
7ee24fb9dfc72bc8952ad0e45660c2fc24507824 | daniel-reich/turbo-robot | /58RNhygGNrKjPXwna_20.py | 973 | 4.28125 | 4 | """
Write a function that returns the **longest non-repeating substring** for a
string input.
### Examples
longest_nonrepeating_substring("abcabcbb") ➞ "abc"
longest_nonrepeating_substring("aaaaaa") ➞ "a"
longest_nonrepeating_substring("abcde") ➞ "abcde"
longest_nonrepeating_substring("abcda") ➞ "abcd"
### Notes
* If multiple substrings tie in length, return the one which occurs **first**.
* **Bonus** : Can you solve this problem in **linear time**?
"""
def longest_nonrepeating_substring(txt):
longest = ""
index = 0
while len(txt) > 0:
index += 1
if len(txt[ : index]) != len(set(txt[ : index])):
if len(txt[ : index - 1]) > len(longest):
longest = txt[ : index - 1]
txt = txt[1 :]
index = 0
if index == len(txt):
if len(txt) > len(longest):
longest = txt
txt = []
return longest
|
d6b587bf925f75652a5a682119f2573405761b60 | CTHS-20-21/Lab_3_03_War | /war.py | 1,148 | 3.84375 | 4 | # War starter code ##############
import random
# name: shuffled_deck
# purpose: will return a shuffled deck to the user
# input:
# returns: a list representing a shuffled deck
def shuffled_deck():
basic_deck = list(range(2, 15)) * 4
random.shuffle(basic_deck)
return basic_deck
deck = shuffled_deck()
print("The starter deck looks like this:\n" + str(deck)) # delete this line of code in your final lab submission
#################################
# Your code here (write the functions below, and complete the rest of the game)
# Write the function based on the contract
# name: player_turn
# purpose: takes in a player name and draws/removes a card from the deck, prints "user drew card x", and returns the value
# Arguments: player_name as string, deck as list
# returns: integer
#### Your code for player_turn here:
# Finish the contract and write the function based on the contract
# name: compare_scores (Write your own contract!)
# purpose:
# Arguments:
# returns:
#### Your code for compare_scores here:
#### Your code for the game 'war' here. This code should have a loop, and call player_turn and compare_scores
|
52d8eca55a2084b6ece5d476e04260f81437eddd | MrHamdulay/csc3-capstone | /examples/data/Assignment_7/bthpor002/question1.py | 568 | 4.3125 | 4 | #A program that prints out a unique lists without duplicates
#By Portia Buthelezi
#create an empty string
x_list= []
#Let the user input strings
x_string= input('Enter strings (end with DONE):\n')
#append the inputs to the list
while x_string !='DONE':
x_list.append(x_string)
x_string= input('')
#Creat new empty list
x_new_list=[]
for x_string in x_list:
if x_string not in x_new_list:
x_new_list.append(x_string)
else:
continue
print('\nUnique list:')
for i in x_new_list:
print(i)
|
9c03af2ac0e1362b30a69cb3a630ad2328b8aa5e | liuhao940826/python-demo | /yield_while的测试.py | 485 | 3.515625 | 4 | # encoding:UTF-8
def test_while_yield():
yield "哈哈哈"
yield "下面的我"
page = 0
# while True:
# print("我也进来了")
# page += 1
# if page > 3:
# print("我现在是:", page)
# yield page
# print("我被调用了")
if __name__ == '__main__':
print("我被执行了")
result = test_while_yield()
print("结果:{}".format(next(result)))
print("结果:{}".format(next(result)))
|
fe006598a3f96e1590e73f2a1f8acc0823f9f734 | vishalpmittal/practice-fun | /funNLearn/src/main/java/dsAlgo/namedAlgo/MinMax_PickLastStick.py | 4,463 | 3.734375 | 4 | """
Tag: algo
minmax / minimax / mm algorithm
In Minimax the two players are called maximizer and minimizer.
The maximizer tries to get the highest score possible while the
minimizer tries to do the opposite and get the lowest score possible.
Every board state has a value associated with it. In a given state if
the maximizer has upper hand then, the score of the board will tend to
be some positive value. If the minimizer has the upper hand in that board
state then it will tend to be some negative value. The values of the
board are calculated by some heuristics which are unique for every
type of game.
"""
from sys import maxsize # infinity (a really big number)
class Node(object):
def __init__(self, i_depth, i_playerNum, i_sticksRemaining, i_value=0):
self.i_depth = i_depth # how deep are we in the tree (decreases every iteration
self.i_playerNum = i_playerNum # (either +1 or -1)
self.i_sticksRemaining = i_sticksRemaining # amount of sticks left
self.i_value = i_value # gamestate: -inf, 0 or +inf
self.children = []
self.CreateChildren()
def CreateChildren(self):
if self.i_depth >= 0: # have we passed the DEPTH of 0 (stop of recursion)
for i in range(1, 3): # (how many stick are we gonna remove)
v = self.i_sticksRemaining - i
self.children.append(
Node(self.i_depth - 1, -self.i_playerNum, v, self.RealVal(v))
) # add to childrens list, depth goes down, player switches
def RealVal(self, value):
if value == 0:
return maxsize * self.i_playerNum # e.g. bullybot
elif value < 0:
return maxsize * -self.i_playerNum # this bot
return 0
def MinMax(node, i_depth, i_playerNum):
if (i_depth == 0) or (
abs(node.i_value) == maxsize
): # have we reached depth 0 or the best node?
return node.i_value # passing the best node up to the current node
i_bestValue = maxsize * -i_playerNum # possitive p
for i in range(len(node.children)):
child = node.children[i]
i_val = MinMax(child, i_depth - 1, -i_playerNum)
if abs(maxsize * i_playerNum - i_val) < abs(
maxsize * i_playerNum - i_bestValue
):
i_bestValue = i_val # store the found best value in this variable
# debug
return i_bestValue
def WinCheck(i_sticks, i_playerNum):
if i_sticks <= 0:
print("*" * 30)
if i_playerNum > 0:
if i_sticks == 0:
print("\tHuman won!")
else:
print("\tToo many chosen, you lost!")
else:
if i_sticks == 0:
print("\tComputer won!")
else:
print("\tComputer done did fucked up..")
print("*" * 30)
return 0
return 1
if __name__ == "__main__":
i_stickTotal = 11
i_depth = 4
i_curPlayer = 1
print(
"""Instructions: Be the player to pick up the last stick.
\t\t\tYou can only pick up one (1) or two (2) at a time."""
)
while i_stickTotal > 0:
## HUMAN TURN
print("\n%d sticks remain. How many will you pick up?" % i_stickTotal)
i_choice = input("\n1 or 2: ")
# i_choice = 1 debug
i_stickTotal -= int(float(i_choice)) # store choice of human
## COMPUTER TURN
if WinCheck(i_stickTotal, i_curPlayer):
i_curPlayer *= -1
node = Node(i_depth, i_curPlayer, i_stickTotal)
bestChoice = -100
i_bestValue = -i_curPlayer * maxsize
## DETERMINE NUMBER OF STICKS TO REMOVE
for i in range(len(node.children)):
n_child = node.children[i]
i_val = MinMax(n_child, i_depth, -i_curPlayer)
if abs(i_curPlayer * maxsize - i_val) <= abs(
i_curPlayer * maxsize - i_bestValue
):
i_bestValue = i_val
bestChoice = i
bestChoice += 1
print(
"Comp chooses: "
+ str(bestChoice)
+ "\tBased on value: "
+ str(i_bestValue)
)
i_stickTotal -= bestChoice
WinCheck(i_stickTotal, i_curPlayer)
i_curPlayer *= -1 # switch players
|
9aa9270db678881bd60c6a669f43e3ebf1cb58d3 | kurumeti/Data-Structure-and-Algorithms | /Assignment-2/4/collecting_signatues.py | 1,825 | 4.0625 | 4 | """
***************SAFE MOVE****************
=> Sort given segments based on right end
***************ALGORITHM****************
=> Check whether right end is to the right of
next segment left end i.e.,
> b[i] >= a[i + 1]
=> if not increment the count and add b[i + 1]
to the result
"""
class my_coordinates:
"""
This stores both left and right points of the segment
"""
point_one = 0
point_two = 0
def __init__(self, point_one, point_two):
self.point_one = point_one
self.point_two = point_two
def get_min_segment(num, cord):
"""
Actual logic goes here
"""
points = list()
index_one = 1
index_two = 0
points.append(cord[index_one].point_two)
count = 1
while(index_one < num):
if points[index_two] >= cord[index_one].point_one:
index_one += 1
else:
points.append(cord[index_one].point_two)
index_two += 1
count += 1
index_one += 1
print(count , points)
def main():
"""
Program starts here
"""
#num = int(input("Give n:"))
num = int(input())
cord = list()
#print("Give the end points of segments:")
for i in range(0, num):
temp_cord = [int(x) for x in input().split()]
cord.append(my_coordinates(temp_cord[0], temp_cord[1]))
"""
lambda is like inline function in C or C++
lambda x: x.point_two means
=> key value will be taken as cord: cord.point_two
"""
cord.sort(key= lambda x: x.point_two, reverse=False)
"""
This function is used to print objects
=>print ([cords.point_two for cords in cord])
"""
#print("The result is:")
get_min_segment(num, cord)
if __name__ == "__main__":
main()
|
918876e76fb7585799b191f390722ac2612f2465 | sudhansom/python_sda | /python_fundamentals/10-functions/fizzbuzz.py | 493 | 4.03125 | 4 | user_input = int(input("Enter the number: "))
# for num in range(1, user_input):
# if num % 3 == 0:
# if num % 5 ==0:
# print("FizzBuzz")
# else:
# print("Fizz")
# elif num % 5 == 0:
# print("Buzz")
# else:
# print(num)
for num in range(1, user_input):
output = ""
if num % 3 == 0:
output += "Fizz"
if num % 5 == 0:
output += "Buzz"
elif num % 3 != 0:
output = num
print(output)
|
eee5d59cc2f8f59e03a066bd4a182ba2ff8ac1c2 | blad00/PythonLearning | /real_decorators/Deco1.py | 2,486 | 3.875 | 4 | # Functions
def add_one(number):
return number + 1
add_one(2)
# First-Class Objects
def say_hello(name):
return f"Hello {name}"
def be_awesome(name):
return f"Yo {name}, together we are the awesomest!"
def greet_bob(greeter_func):
return greeter_func("Bob")
greet_bob(say_hello)
greet_bob(be_awesome)
# Inner Functions
def parent():
print("Printing from the parent() function")
def first_child():
print("Printing from the first_child() function")
def second_child():
print("Printing from the second_child() function")
second_child()
first_child()
parent()
# Returning Functions From Functions
def parent(num):
def first_child():
return "Hi, I am Emma"
def second_child():
return "Call me Liam"
if num == 1:
return first_child
else:
return second_child
first = parent(1)
second = parent(2)
first
second
first()
second()
# Simple Decorators
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
def say_whee():
print("Whee!")
say_whee = my_decorator(say_whee)
say_whee()
say_whee
from datetime import datetime
def not_during_the_night(func):
def wrapper():
if 7 <= datetime.now().hour < 22:
func()
else:
pass # Hush, the neighbors are asleep
return wrapper
def say_whee():
print("Whee!")
say_whee = not_during_the_night(say_whee)
say_whee()
# Syntactic Sugar!
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_whee():
print("Whee!")
say_whee()
# Reusing Decorators
from real_decorators.decorators import do_twice
@do_twice
def say_whee():
print("Whee!")
say_whee()
@do_twice
def greet(name):
print(f"Hello {name}")
say_whee()
greet("World")
# Returning Values From Decorated Functions
from real_decorators.decorators import do_twice
@do_twice
def return_greeting(name):
print("Creating greeting")
return f"Hi {name}"
hi_adam = return_greeting("Adam")
print(hi_adam)
print
print.__name__
help(print)
say_whee
say_whee.__name__
help(say_whee)
say_whee
say_whee.__name__
help(say_whee)
|
eb56feada29e38a0c0035a4263dc82c5c33ca3d7 | gustaslira/Random-Codes | /Pedra Papel Tesoura Lagarto Spock/pplts_v2.0.py | 543 | 4.0625 | 4 | sheldon, raj = input().split()
pedra, papel, tesoura, lagarto, Spock = 'pedra','papel','tesoura','lagarto','Spock'
if sheldon == raj:
print('De novo!')
elif (
(sheldon == pedra and (raj == lagarto or raj == tesoura)) or
(sheldon == papel and (raj == pedra or raj == Spock)) or
(sheldon == tesoura and (raj == papel or raj == lagarto)) or
(sheldon == lagarto and (raj == Spock or raj == papel)) or
(sheldon == Spock and (raj == tesoura or raj == pedra))
):
print('Bazinga!')
else:
print('Raj trapaceou!') |
cb4f009d6fd1eae75b198ab0960e9e7af380c0b7 | Qiumy/leetcode | /Python/136. Single Number.py | 668 | 3.75 | 4 | # Given an array of integers, every element appears twice except for one. Find that single one.
from functools import reduce
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 1:
return nums[0]
nums.sort()
for i in range(0, len(nums), 2):
if i == len(nums) - 1 or nums[i] != nums[i + 1]:
return nums[i]
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return reduce(lambda x,y: x^y, nums) |
6e171e5ca72cfcd51ad21c6bd70afc1ef50e9bc0 | jtorain21/CS-115 | /highway_robbery.py | 4,601 | 4.1875 | 4 | # Joshua Torain CIS 115 FON04
# write main function to control logic
# write functions to get the users name, age, and # of traffic violations
# write functions to determine risk code and risk type based on users input
# write a function to determine the insurance price based on user input
# write a function to display the results
# call the main function
# write main function to control logic
def main():
name = customer_name()
age = customer_age()
traffic_violations = customer_traffic_violations()
risk_code = customer_risk_code(traffic_violations)
risk_type = customer_risk_type(risk_code)
price = insurance_price(age, traffic_violations)
display_results(name, risk_type, price)
# function to get users name
def customer_name():
# store users input in variable called name
name = input('What is your name? ')
# return the variable, and capitalize it using capitalize() function
return name.capitalize()
# function to get users age
def customer_age():
# store users input as an integer in variable called age
age = int(input('How old are you? '))
# use a while loop to set age restrictions. use range() function, must be between 16 and 105
while age not in range(16, 106):
# if user enters invalid input print error message
print('Drivers must be between 16 and 105 years of age!')
# ask user to reenter age
age = int(input('How old are you? '))
# return the variable
return age
# function to get number of traffic violations
def customer_traffic_violations():
# store users input as an integer in variable called traffic_violations
traffic_violations = int(input('How many traffic violations have you received? '))
# use a while loop to set restrictions. must be zero or higher
while traffic_violations < 0:
# print error message is user gives invalid input
print('Violations may not be less than 0!')
# ask user to reenter data
traffic_violations = int(input('How many traffic violations have you received? '))
# return the variable
return traffic_violations
# function to calculate the users risk code. use traffic_violations as parameter
def customer_risk_code(traffic_violations):
# use if/elif statement to determine risk code based on number of traffic violations
if traffic_violations == 0:
risk_code = 4
elif traffic_violations == 1:
risk_code = 3
elif traffic_violations == 2:
risk_code = 2
elif traffic_violations == 3:
risk_code = 2
else:
risk_code = 1
# return the variable
return risk_code
# function to determine the users risk type, use risk_code as parameter
def customer_risk_type(risk_code):
# use if/elif statement to determine risk type based on risk code
if risk_code == 4:
risk_type = 'no risk'
elif risk_code == 3:
risk_type = 'low risk'
elif risk_code == 2:
risk_type = 'moderate risk'
else:
risk_type = 'high risk'
# return the variable
return risk_type
# function to determine the users insurance price, age and traffic_violations are the parameters
def insurance_price(age, traffic_violations):
# use if/elif statements to determine the price based on the users age and number of violations
if age < 25 and traffic_violations > 3:
price = '$480.00'
elif age < 25 and traffic_violations == 3:
price = '$450.00'
elif age < 25 and traffic_violations == 2:
price = '$405.00'
elif age < 25 and traffic_violations == 1:
price = '$380.00'
elif age < 25 and traffic_violations == 0:
price = '$325.00'
elif age > 24 and traffic_violations > 3:
price = '$410.00'
elif age > 24 and traffic_violations == 3:
price = '$390.00'
elif age > 24 and traffic_violations == 2:
price = '$365.00'
elif age > 24 and traffic_violations == 1:
price = '$315.00'
else:
price = '$275.00'
# return the variable
return price
# function to display the results to the user. Name, risk_type, and price are parameters
def display_results(name, risk_type, price):
print(name, 'as a', risk_type, 'driver, your insurance will cost', price)
# use while loop to allow user to make multiple quotes
while True:
# if user enters one, call the main function to run program
if input('Would you like to make a quote? If yes, press 1 ') == '1':
main()
# if user enters anything other than one, use break to stop loop and end program.
else:
break
|
2e3e8ade78847f8464acfb4f4959ac57b884e4e1 | Futureword123456/Interview | /Interview/6/59.py | 1,094 | 4.25 | 4 | # -*- coding: utf-8 -*-
# @Time : 2021/3/11 0011
# @Author : yang
# @Email : 2635681517@qq.com
# @File : 59.py
"""Python 插入排序"""
""""(1)首先对数组的前两个数据进行从小到大的排序。
(2)接着将第3个数据与排好序的两个数据比较,将第3个数据插入到合适的位置。
(3)然后,将第4个数据插入到已排好序的前3个数据中。
(4)不断重复上述过程,直到把最后一个数据插入合适的位置。最后,便完成了对原始数组的从小
到大的排序。"""
def insertion(arr):
"""遍历整个列表"""
for i in range(1, len(arr)):
key = arr[i] # 待排序的数组
j = i - 1
# arr[j]是已经排好序的那一小部分
while j >= 0 and key < arr[j]:
# 向后移动一个位置给需要插入的数据
arr[j + 1] = arr[j]
#
j = j - 1
# 插入到合适的位置
arr[j + 1] = key
if __name__ == "__main__":
lst = [5,8,9,6,2,4,10]
insertion(lst)
print(lst)
for i in lst:
print(i,end=" ")
|
1604299801f4aa4fe0f074f6c6ab35f696bf6a00 | thxa/1MAC | /ATM Solution/atm_class.py | 2,080 | 3.84375 | 4 | class ATM:
def __init__(self, balance, bank_name):
self.balance = balance
self.bank_name = bank_name
self.withdrawals_list = []
def withdraw(self, request):
print "welcome to " + self.bank_name
print "Current balance = %d" % self.balance
print "=" * 34
if request > self.balance:
print("Can't give you all this money !!")
else:
self.balance -= request
while request > 0:
give_string = "give "
if request >= 100:
self.withdrawals_list.append(request)
request -= 100
print give_string + str(100)
elif request >= 50:
self.withdrawals_list.append(request)
request -= 50
print give_string + str(50)
elif request >= 10:
self.withdrawals_list.append(request)
request -= 10
print give_string + str(10)
elif request >= 5:
self.withdrawals_list.append(request)
request -= 5
print give_string + str(5)
elif request >= 2:
self.withdrawals_list.append(request)
request -= 2
print give_string + str(2)
elif request >= 1:
self.withdrawals_list.append(request)
request -= 1
print give_string + str(1)
print "=" * 34
return self.balance
def show_withdrawals(self):
print "List"
for withdrawal in self.withdrawals_list:
print(withdrawal)
print "=" * 34
if __name__ == '__main__':
balance1 = 500
balance2 = 1000
atm1 = ATM(balance1, "Smart Bank")
atm2 = ATM(balance2, "Baraka Bank")
atm1.withdraw(277)
atm1.withdraw(800)
atm2.withdraw(100)
atm2.withdraw(2000)
atm1.show_withdrawals()
atm2.show_withdrawals() |
fb6fe2ee50dbefdd961a1053ce2a49420f16983e | rscalzo/subpipe | /Utils/Record.py | 10,626 | 3.53125 | 4 | #!/usr/bin/env python
# ============================================================================
# RS 2012/02/13: Implementation of Record class hierarchy
# ----------------------------------------------------------------------------
# This code defines a class hierarchy for constructing "record"-like objects,
# i.e., objects with attributes, from external data, including ASCII files.
# ============================================================================
import re
import os
import pyfits
import psycopg2
import psycopg2.extras
# Somewhere in here we need to define an exception for bad initialization.
# The below is an approximation but probably a crappy one.
class BadInit(Exception):
def __init__(self, msg, **kwargs):
self.msg = msg
self.kwargs = kwargs
def __str__(self):
return self.msg
# Base class for all the APIs below
class BaseRecord(object): pass
class KeywordRecord(BaseRecord):
"""
The simplest API imaginable for a record-like thing. It can be used
to override properties read in from other APIs.
"""
# This is a list of tuples (field, default).
# Example: ("x", "0.0")
# Overload as a class attribute in derived classes to implement a record.
_keyword_fields = [ ]
def _init_from_keywords(self, **kwargs):
for f in self._keyword_fields:
if kwargs.has_key(f[0]): setattr(self,f[0],kwargs[f[0]])
elif hasattr(self,f[0]): pass
else: setattr(self,f[0],f[1])
def __init__(self, **kwargs):
self._init_from_keywords(**kwargs)
class RegexRecord(BaseRecord):
"""
Represents the results of parsing groups from a regular expression.
"""
_regex = ""
_regex_fields = [ ]
def _init_from_regex(self, ascii_line):
match = re.search(self._regex, ascii_line)
if match == None: return
vals = match.groups()
try:
for f in self._regex_fields: setattr(self,f[0],vals[f[1]])
except IndexError:
msg = "Bad index filling {0} from regular expression\n" \
.format(self.__class__.__name__) \
+ "field = {0}, index = {1}, regex = {2}" \
.format(f[0],f[1],self._regex)
raise BadInit(msg)
except:
raise BadInit("Uncaught exception reading {0} from regex"
.format(self.__class__.__name__))
class AsciiRecord(BaseRecord):
"""
Represents a line of a multi-column text file with clear delimiters.
"""
# This is a list of tuples (field, index, informat, outformat, default)
# governing how the record is read and written. Basically,
# input: self.field = informat(column[index]) or default
# output: outstring = outformat.format(self.field)
# Example: [ "name", 1, (lambda x: x.strip()), '{0:s}', '' ]
# Overload as a class attribute in derived classes to implement a record.
# RS 2012/05/25: Set _ascii_separator to None by default, so that items
# in a record can be separated by arbitrary amounts of whitespace.
_ascii_separator = None
_ascii_fields = [ ]
def _init_from_ascii(self, ascii_line):
cols = ascii_line.split(self._ascii_separator)
try:
for f in self._ascii_fields:
# RS 2012/06/03: If field is empty, set it to None
if re.search("\S+", cols[f[1]]): val = f[2](cols[f[1]])
else: val = None
# FY 2014/07/09: If val is None, set field to default
if val is None: setattr(self, f[0], f[4])
else: setattr(self, f[0], val)
except:
raise BadInit("Badly formatted {0} ASCII table line:\n{1}"
.format(self.__class__.__name__, ascii_line),
ascii_line=ascii_line)
def __init__ (self, ascii_line):
self._init_from_ascii(ascii_line)
def asline(self):
return self._ascii_separator.join \
([f[3].format(getattr(self,f[0])) for f in self._ascii_fields])
def header(self):
return self._ascii_separator.join \
([re.sub(r'[a-rtz]','s',re.sub(r'\.\d+','',f[3])).format(f[0]) for f in self._ascii_fields])
@classmethod
def read_ascii_file(cls, fname):
objlist = [ ]
with open(fname) as file:
for line in file:
if line[0] == '#': continue
if len(line.strip())==0: continue
try:
objlist.append(cls(line))
except:
pass
return objlist
@staticmethod
def write_ascii_file(fname, objlist,header=False,append=False):
if append and os.path.exists(fname):
mode="a"
else:
mode="w"
with open(fname,mode) as file:
if header and len(objlist)>0:
file.write("{0}\n".format(objlist[0].header()))
file.write("\n".join([obj.asline() for obj in objlist]))
if append:
file.write("\n")
class FITSRecord(BaseRecord):
"""
Represents a row of a FITS binary table.
"""
# This is a list of tuples (field, colname, type, units, format, default)
# governing how the record is read in from the FITS file. The fields
# should correspond to the CFITSIO conventions for FITS binary tables.
# Example: [ "xsub", "X_IMAGE", "1E", "pixel", "F7.2", 0.0 ]
# Overload as a class attribute in derived classes to implement a record.
_fits_fields = [ ]
def _init_from_fitsrow(self, row, colnames):
try:
for f in self._fits_fields:
setattr(self,f[0],row[colnames.index(f[1])])
except IndexError:
msg = "Bad index filling {0} from FITS file\n" \
.format(self.__class__.__name__) \
+ "len(row) = {0}, ".format(len(row)) \
+ "len(colnames) = {0}, ".format(len(colnames)) \
+ "len(_fields) = {0}".format(len(self._fits_fields))
raise BadInit(msg)
except Exception as e:
raise e
raise BadInit("Uncaught exception reading {0} from FITS file"
.format(self.__class__.__name__))
def __init__(self, row, colnames):
self._init_from_fitsrow(row, colnames)
@classmethod
def read_fits_file(cls, fname, ext=1):
objlist = [ ]
with pyfits.open(fname) as ptr:
header = ptr[0].header
tbdata, colnames = ptr[ext].data, ptr[ext].columns.names
if not tbdata is None:
for r in tbdata: objlist.append(cls(r,colnames))
return objlist, header
@staticmethod
def write_fits_file(fitsname, objlist, header=None, keywords=[ ]):
"""Writes a series of FITSRecords to disk.
RS 2012/08/22: Now allows objlist to be an iterable of FITSRecords
possibly of different types. Each collection of FITSRecords of the
same type are written to a different extension in the order in which
they appear in objlist.
"""
# Determine which types of objects we're dealing with.
if len(objlist) == 0:
return
try:
types = [ ]
for s in objlist:
if not isinstance(s, FITSRecord): raise TypeError()
if s.__class__ not in types: types.append(s.__class__)
except TypeError:
raise BadInit("objlist must be an iterable of FITSRecords")
# If a pyfits header object is passed in, copy it to the primary HDU.
# Same with any one-off keywords the user would like to supply,
# which should appear as a list of (keyword, value, comment) tuples.
hdulist = [pyfits.PrimaryHDU(header=header)]
for kw in keywords: hdulist[0].header.update(*kw)
# Now create a new table extension for each type.
for t in types:
col_objs = [s for s in objlist if isinstance(s, t)]
if len(col_objs) == 0: continue
try:
# This parses the data into columns for a table to be written
# out all in one go, rather than line by line.
cols = [pyfits.Column
( name = f[1],
format = f[2],
unit = f[3],
disp = f[4],
array = [getattr(s, f[0]) for s in col_objs] )
for f in t._fits_fields]
except (TypeError, IndexError): continue
hdulist.append(pyfits.new_table(pyfits.ColDefs(cols)))
hdulist[-1].header.update("CLASSNAM", t.__name__,
"Class name of table row objects")
# Finally, write the primary header with extensions to disk, but only
# if we have at least one extension so we don't end up with weird
# corrupted files.
if len(hdulist) > 1:
pyfits.HDUList(hdulist).writeto(fitsname, clobber=True)
return
class PGRecord(BaseRecord):
"""
Represents a row of a Postgres table. Uses psycopg.
"""
_dbname = None
_dbhost = None
_dbuser = None
_dbpw = None
_sqlquery = ''
# This is a list of tuples (field, dbcolname, default).
# Example: ("gmag_err", "e_g", "0.0")
# Basically the same as KeywordRecord, but with the possibility that
# the field name in the database might not be what the user calls it.
_sql_fields = [ ]
def _init_from_sqlrow(self, **kwargs):
for f in self._sql_fields:
if kwargs.has_key(f[1]):
setattr(self,f[0],kwargs[f[1]])
elif hasattr(self,f[0]):
pass
else:
setattr(self,f[0],f[2])
def __init__(self, **kwargs):
self._init_from_sqlrow(**kwargs)
@classmethod
def pgquery(cls, *args, **kwargs):
conn = psycopg2.connect(host=cls._dbhost, database=cls._dbname,
user=cls._dbuser, password=cls._dbpw)
cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
if 'verbose' in kwargs and kwargs['verbose']:
print cursor.mogrify(cls._sqlquery, args)
cursor.execute(cls._sqlquery, args)
rows = cursor.fetchall()
results = [cls(**(dict(row))) for row in rows]
# Clean up
cursor.close()
conn.close()
return results
|
6d56212c0b0f188e7b3c939c8d57350daaf04f53 | bakkerjangert/AoC_2016 | /Day 3/day3b.py | 780 | 3.65625 | 4 | # Advent of Code 2016 - Day 2 part a
import numpy as np
with open('input.txt') as f:
lines = f.read().splitlines()
triangles = []
triangle1 = []
triangle2 = []
triangle3 = []
for line in lines:
triangle1.append(int(line.split()[0]))
triangle2.append(int(line.split()[1]))
triangle3.append(int(line.split()[2]))
if len(triangle1) == 3:
triangle1.sort()
triangles.append(tuple(triangle1))
triangle1 = []
triangle2.sort()
triangles.append(tuple(triangle2))
triangle2 = []
triangle3.sort()
triangles.append(tuple(triangle3))
triangle3 = []
possibles = 0
for item in triangles:
if item[0] + item[1] > item[2]:
possibles += 1
print(f'There are {possibles} possible triangles')
|
99a4db49287d29f3095200a7aa235d4d422691df | elixias/kaggle-python | /datacamp4.py | 1,842 | 3.84375 | 4 | """Opening files"""
filename = ""
file = open(filename, mode='r')
text = file.read()
print(text)
file.close() #check w print(file.closed)
#using with statement/context manager
#creates a context with the file open
#once completed file is no longer opened
#this is binding in a context manager construct
#with open(filename, mode="r") as file:#
"""Using numpy for numerical data flat files"""
import numpy as np #for files that contain only numerical data
data = np.loadtxt('filename.txt', delimiter=',', skiprows=1, usecols=[0,2], dtype=str) #skiprows skip the header, usecols is which columns u want, dtype to force everything into strings
print(data)
"""MNIST"""
###this is very interesting
###mnist dataset loaded as a txt file and visualized
# Import package
import numpy as np
# Assign filename to variable: file
file = 'digits.csv'
# Load file as array: digits
digits = np.loadtxt(file, delimiter=",")
# Print datatype of digits
print(type(digits))
# Select and reshape a row
im = digits[21, 1:]
im_sq = np.reshape(im, (28, 28))
# Plot reshaped data (matplotlib.pyplot already loaded as plt)
plt.imshow(im_sq, cmap='Greys', interpolation='nearest')
plt.show()
"""Loading dataset containing multiple datatypes"""
#when u import a structured array (each row being a structured array of different types)
#also, need to use genfromtext
#data = np.genfromtxt('titanic.csv', delimiter=',', names=True, dtype=None)
#or data = np.recfromcsv('titanic.csv', delimiter=',', names=True)
#data[i] for row and data['Column'] for column
"""Dataframes"""
#more useful for data scientists, modelling, splicing, groupbys, merge etc
data = pd.read_csv("filename.csv")
data.head()
convertedtonumpyarray = data.values
#data = pd.read_csv("digits.csv", header=None, nrows=5)
#data = pd.read_csv(file, sep="\t", comment='#', na_values=["Nothing"])
|
80ee2149be303c0343542df4f9cfddaca9b27a4e | z1223343/Leetcode-Exercise | /012_75_SortColors.py | 1,645 | 3.734375 | 4 | """
2 ideas of solutions:
1. count sort (by myself, two pass)
2. one pass (三向切分快速排序?)
1.
2. time O(N) space O(1)
"""
class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
countlist = [0 for i in range(3)]
for element in nums:
if element == 0:
countlist[0] += 1
elif element == 1:
countlist[1] += 1
else:
countlist[2] += 1
curr = 0
for i, num in enumerate(countlist):
for j in range(num):
nums[curr] = i # 就狠蛋疼,这里这样用指针遍历一个一个值改nums才行,如果重设nums = 0,然后用nums.append(i),
# 结果错误,nums 还是等于初始值。 python似乎重设nums的话实际上重新定义了一个新变量。
curr += 1
class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
p0 = curr = 0
p2 = len(nums) - 1
while curr <= p2: # 想明白了,这里有等于
if nums[curr] == 0:
nums[curr], nums[p0] = nums[p0], nums[curr]
p0 += 1
curr += 1
elif nums[curr] == 2:
nums[curr], nums[p2] = nums[p2], nums[curr]
p2 -= 1 # Note curr have no change
else:
curr += 1
|
f6eb57df0069d0766cb2774e79f709c4abbd2270 | uselessrepo/21jan | /p31.py | 229 | 4.40625 | 4 | def change(string):
if string[0:2] == 'Is' or string[0:2]=='is':
final = string
else:
final = "Is "+string
return final
string = input("Enter A String : ")
final = change(string)
print(final) |
9d118f5304c4e235435e48678c24887a3bfbfca2 | inwk6312winter2019/week4labsubmissions-sahithyabathini5 | /lab5_2.py | 666 | 3.703125 | 4 | import math
class Rectangle(point):
def __init__(self,width=0.0,height=0.0,corner=point(0.0,0.0)):
self.width=width
self.height=height
self.corner=corner
def find_center(Rectangle):
x1 = (Rectangle.width)/2
x2 = (Rectangle.height)/2
return (x1,x2)
p = point()
rect=Rectangle(10,20,p)
centre= find_center(rect)
print(centre)
#Task2-b
def move_rectangle(Rectangle,dx,dy):
Rectangle.corner.x=Rectangle.corner.x + dx
Rectangle.corner.y = Rectangle.corner.y + dy
return (Rectangle.corner.x,Rectangle.corner.y)
cor = point(4,5)
dx = 2
dy = 4
mv_ract = Rectangle(corner = cor)
moved_corner = move_rectangle(mv_ract,dx,dy)
print(moved_corner)
|
55027c728bbdd853f1d193c79fc4e6b66e608a01 | harleydutton/passgen | /passgen.py | 803 | 3.671875 | 4 | import random
import argparse
parser = argparse.ArgumentParser(description='Generate a password of given length.')
parser.add_argument('length',metavar='len',type=int,
help='the length of the password')
parser.add_argument('-cap', dest='cap', action='store_const', const=True,
default=False, help='Add caps to the password')
parser.add_argument('-sym', dest='sym', action='store_const', const=True,
default=False, help='Add caps to the password')
args = parser.parse_args()
out=""
legalChars="1234567890abcdefghijklmnopqrstuvwxyz"
capitals="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
if args.cap:
legalChars+=capitals
symbols="~!@#$%^&*()_+`-={}|[]<>?,.;:'\"\\/"
if args.sym:
legalChars+=symbols
for i in range(args.length):
out+=random.choice(legalChars)
print(out)
|
a90ae58b70ea5f8b1d9cc5a43477818b214a64b8 | ShvarevArthur/course | /check.py | 113 | 3.84375 | 4 | print("input a")
a = int(input())
print("input b")
b = int(input())
for i in range (0, b - a):
print("*\n")
|
4e42824aebad8d05d56b3e259183c41309276c8e | sidhu177/PythonRepo | /CurvePlot.py | 433 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Oct 29 08:31:22 2016
## Plot the curve y = t^2 exp(-t^2) for t values between 0 and 3.
@author: SIDHARTH
"""
import numpy as np
from matplotlib import pyplot as plt
t = np.linspace(0,3,50)
y = (t**2)*np.exp(-t**2)
plot1, = plt.plot(t,y, label='Line')
plt.title("A Skewed Graph")
plt.xlabel("Range")
plt.ylabel("Computed Value")
plt.legend(handles=[plot1])
plt.show()
|
91a535cae2574514a55a84432a912f3e9f05668a | zhyu/leetcode | /algorithms/reorderList/reorderList.py | 988 | 3.8125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param head, a ListNode
# @return nothing
def reorderList(self, head):
if head is None or head.next is None:
return
slow = fast = head
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
fast, slow.next = slow.next, None
fast = self.reverseList(fast)
self.merge2Lists(head, fast)
def reverseList(self, head):
if head is None or head.next is None:
return head
pre, cur = head, head.next
while cur:
nxt, cur.next = cur.next, pre
cur, pre = nxt, cur
head.next = None
return pre
def merge2Lists(self, l1, l2):
while l2:
n1, n2 = l1.next, l2.next
l1.next, l2.next = l2, n1
l1, l2 = n1, n2
|
0414fe95c6deb11a7309f61f62833c20d53a78b2 | sandeep9889/datastructure-and-algorithm | /problems/stacks/stack using deque/test.py | 280 | 3.796875 | 4 | from collections import deque
stack= deque()
#it isn for appending
stack.append('a')
stack.append('b')
stack.append('c')
print("initial stack")
print(stack)
# for pop
print(stack.pop()) # lifo principle then c will remove
print(stack.pop())#remove b
print(stack.pop())# remove c
|
4f15fea4c7c64f0fee41c569bf52e01aad4d29ea | GhostDovahkiin/Introducao-a-Programacao | /Monitoria/Estrutura de Decisão/15.py | 494 | 4.09375 | 4 | lado1 = float(input("Primeiro Lado: "))
lado2 = float(input("Segundo Lado: "))
lado3 = float(input("Terceiro Lado: "))
if (lado1+lado2 > lado3 or lado3+lado1 > lado2 or lado3+ladob2 > lado1):
if lado1 == lado2 and lado1 == lado3 and lado1 == lado3:
print("Triângulo Equilátero")
elif lado1 == lado2 or lado1 == lado3 or lado2 == lado3:
print("Triângulo Isóceles")
else:
print("Triângulo Escaleno")
else:
print("Não é um triângulo")
|
acbc10559d80426188d20971184e5b13f63caeb3 | drmrsmoke/GeekBrains | /hw4/hw4.py | 156 | 3.6875 | 4 | print(f"Числа кратные 20 и 21 в диапазоне от 20-240 {[n for n in range(20, 240) if n % 20 == 0 or n % 21 == 0]}")
# print(my_list)
|
a743498cfb4426a0d46dc1bcb2d867206f4c5a1b | CGayatri/Python-Practice1 | /outputs.py | 3,591 | 4.21875 | 4 | ############## Output Statements ###############
## print() stmt
print()
'''
F:\PY>py outputs.py
F:\PY>
'''
## print("string") stmt
print("Hello Double quotes")
'''
Hello Double quotes
'''
print('Hello Single quotes')
'''
Hello Single quotes
'''
# use of escape character - \n, \\, \t, \', \", \\n
print("This is the \nfirst line")
'''
This is the
first line
'''
print("This is the \tfirst line")
#This is the first line
print('this is the \\nfirst line')
#this is the \nfirst line
print(3*'Hai')
#HaiHaiHai
# + operator on number - arithmetic
print(4+5)
#9
# + operator on strings - concatenation
print("City name="+"Pune")
#City name=Pune
# using comma - a default space get added in between strings , cuz comma assumes values are different and hence space should be added
print("City name=","Pune")
#City name= Pune
## print(variale list) stmt
a, b = 2, 4
print(a)
#2
print(a, b)
#2 4
## 'sep' attribute - separator
print(a, b, sep=",")
#2,4
print(a, b, sep=':')
#2:4
print(a, b, sep='----')
#2----4
# several print() functions display outputs on separate new lines
print("Hello")
print("Dear")
print('How are u?')
'''
Hello
Dear
How are u?
'''
## 'end' attribute
print("Hello", end='')
print("Dear", end='')
print('How are u?', end='')
#HelloDearHow are u?
print('\n')
print("Hello", end='\t')
print("Dear", end='\t')
print('How are u?', end='\t')
#Hello Dear How are u?
print()
### print(object) stmt
lst = [10, 'A', 'Hai']
print(lst)
#[10, 'A', 'Hai']
d = {'Idli': 30.00, 'Roti':45.00, 'Pulao':55.50}
print(d)
#{'Idli': 30.0, 'Roti': 45.0, 'Pulao': 55.5}
print()
### print("string", variable list) stmt
a = 2
print(a, "is even number")
#2 is even number
print('You typed ', a, 'as input')
#You typed 2 as input
### print(formatted string) stmt
# %i, %d - integers; %f - floating point numbers; %s - string ; %c - a character
x = 10
print('value = %i' %x)
#value = 10
x, y = 10, 15
print('x= %i y=%d' %(x,y))
#x= 10 y=15
name = 'Linda'
print('Hai %s' %name)
#Hai Linda
print('Hai (%20s)' % name)
#Hai ( Linda)
print('Hai (%-20s)' %name)
#Hai (Linda )
print('Hai %20s' % name)
#Hai Linda
name = 'Linda'
print('Hai %c, %c' % (name[0], name[1]))
#Hai L, i
print('Hai %s' % name[0:2])
#Hai Li
num = 123.456789
print('The value is: %f' %num)
#The value is: 123.456789
print('The value is: %8.2f' %num)
#The value is: 123.46
### print('formatted string with replacement fields'.format(values))
n1, n2, n3 = 1, 2, 3
print('number1 = {0}'.format(n1))
#number1 = 1
print('number1={0}, number2={1}, number3={2}'.format(n1, n2, n3))
#number1=1, number2=2, number3=3
print('number1={1}, number2={0}, number3={2}'.format(n1, n2, n3))
#number1=2, number2=1, number3=3
### names in replacement fields
print('number1={two}, number2={one}, number3={three}'.format(one=n1, two=2, three=3))
#number1=2, number2=1, number3=3
### w/o names/indexes
print('number1={}, number2={}, number3={}'.format(n1, n2, n3))
#number1=1, number2=2, number3=3
name, salary = 'Ravi', 12500.75
print('Hello {0}, your salary is {1}'.format(name, salary))
#Hello Ravi, your salary is 12500.75
print('Hello {n}, your salary is {s}'.format(n=name, s=salary))
#Hello Ravi, your salary is 12500.75
print('Hello {:s}, your salary is {:.2f}'.format(name, salary))
#Hello Ravi, your salary is 12500.75
print('Hello {:s}, your salary is {:.1f}'.format(name, salary))
#Hello Ravi, your salary is 12500.8
print('Hello %s, your salary is %.2f' %(name, salary))
#Hello Ravi, your salary is 12500.75
|
dea5074676431dd20bb2ef6e216eb91d6bff1801 | MVasanthiM/guvi | /programs/min-hr_min.py | 47 | 3.53125 | 4 | m=int(input())
hr=m//60
min=m%60
print(hr,min)
|
642df7341124cbde0923116f88b6138ee60949ad | vishalsingh8989/karumanchi_algo_solutions_python | /Dynamic Programming/knapsack_2.py | 375 | 3.5 | 4 | """
repetition of items allowed.
"""
def knapsack(W, wt, val, n):
dp = [0]*(W+1)
for i in xrange(W+1):
for j in wt:
if j <= i:
dp[i] = max(dp[i], dp[i - j] + j)
return dp[-1]
if __name__ == "__main__" :
W = 10
val = [1, 3, 2]
wt = [5, 10, 15]
n = len(val)
print(knapsack(W, wt, val, n)) |
a84b5661175b0b10fe37fa70022323b49fdd7dc0 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/hamming/80246a917385418d845439527c945483.py | 285 | 3.515625 | 4 | __author__ = 'tracyrohlin'
def distance(string_1, string_2):
hamming_number = 0
for n in xrange(len(string_1)):
if string_1[n] == string_2[n]:
pass
else:
hamming_number += 1
return hamming_number
print distance('GATACA', 'GCATAA')
|
79fa2101e37db7197c6203f7c8f0c03c29b2559e | xinxin3713/programs | /design设计模式/observer_design/drinks.py | 1,874 | 4.25 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
__created__ = '2018/1/16'
__author__ = 'zhaohongyang'
"""
class Tea(object):
"""Class Tea"""
def __init__(self):
self.name = 'Tea'
self.price = 2
self.__subscribers = []
def get_price(self):
return self.price
def get_name(self):
return self.name
# 提供注册
def attch(self, subscriber):
self.__subscribers.append(subscriber)
# 更新价格
def update_price(self, price):
self.price = price
for sub in self.__subscribers:
sub.update_tea_price(self.price)
class Ice(object):
""" ice """
def __init__(self):
self.name = 'ice'
self.price = 1
self.__subscribers = []
def get_price(self):
return self.price
def get_name(self):
return self.name
# 提供注册
def attch(self, subscriber):
self.__subscribers.append(subscriber)
# 更新价格
def update_price(self, price):
self.price = price
for sub in self.__subscribers:
sub.update_ice_price(self.price)
class TeaWithIce(object):
def __init__(self):
self.ice_name = 'ice'
self.tea_name = 'tea'
self.ice_price = 1
self.tea_price = 2
def get_price(self):
return self.ice_price + self.tea_price
def get_name(self):
return self.ice_name + 'with' + self.tea_name
def update_ice_price(self, price):
self.ice_price = price
def update_tea_price(self, price):
self.tea_price = price
if __name__ == '__main__':
tea = Tea()
ice = Ice()
tea_with_ice = TeaWithIce()
tea.attch(tea_with_ice)
ice.attch(tea_with_ice)
print(tea_with_ice.get_price())
tea.update_price(price=5)
print(tea.get_price())
print(tea_with_ice.get_price())
|
dbec152b0e60aa09ce68aa161d19fae6b4bc1645 | CarolineXiao/AlgorithmPractice | /TopKLargestNumbers.py | 475 | 3.734375 | 4 | import heapq
class Solution:
"""
@param nums: an integer array
@param k: An integer
@return: the top k largest numbers in array
"""
def topk(self, nums, k):
if len(nums) <= k:
return sorted(nums, reverse=True)
heap = []
for i in range(len(nums)):
heapq.heappush(heap, nums[i])
if len(heap) > k:
heapq.heappop(heap)
return sorted(heap, reverse=True)
|
73566405be4484d48d674f728c7b9ef29a7d0b15 | manofpeace1/webapplication_study_archive | /python_ruby/String/1.py | 318 | 4.15625 | 4 | print("Hello World")
print("Hello")
print("Hello 'World'")
print('Hello "World"')
print('Hello '+'world')
print("Hello World "*3)
print("H ello"[1])
print('hello world'.capitalize())
print('hello world'.upper())
print('hello world'.__len__())
len('hello world')
print('Hello world'.replace('world'[2], 'programming'))
|
f43d645b151461e34547da8cb0d7945c1236bcb3 | SoyeonHH/Algorithm_Python | /LeetCode/148.py | 1,428 | 3.78125 | 4 | '''
LeetCode 148. Sort List
연결리스트를 O(n log n)에 정렬하라.
'''
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if l1 and l2:
if l1.val > l2.val:
l1, l2 = l2, l1
l1.next = self.mergeTwoLists(l1.next, l2)
return l1 or l2
def sortList_mergeSort(self, head: ListNode) -> ListNode:
if not (head and head.next):
return head
# Runner
half, slow, fast = None, head, head
while fast and fast.next:
half, slow, fast = slow, slow.next, fast.next.next
half.next = None # 연결 리스트 끊기
# Divide Reference
l1 = self.sortList_mergeSort(head)
l2 = self.sortList_mergeSort(slow)
return self.mergeTwoLists(l1, l2)
def sortList_Pythonic(self, head: ListNode) -> ListNode:
# Linked List -> Python List
p = head
lst: list = []
while p:
lst.append(p.val)
p = p.next
# sort
lst.sort()
# Python List -> Linked List
p = head
for i in range(len(lst)):
p.val = lst[i]
p = p.next
return head |
e80284b248387774fe6f1796ea4acf3048873ff7 | vkagwiria/thecodevillage | /Python Week 4/Day 2/exercise1.py | 208 | 4.28125 | 4 | # ask user for radius
# use a lambda function to calculate the area
area =lambda radius: radius*radius*3.142
radius = int(input("Please insert the radius here: "))
print("The area is", area(radius))
|
16a4fe28ddc40dac810c265ff6b21d7120694b2e | ashokreddy7013/python | /Python 8 to 9AM/RegualrExp/Demo6.py | 90 | 3.921875 | 4 |
import re
s1 = "Hello this is naveen"
result = re.sub("naveen","sathya",s1)
print(result) |
2f8dcabb14aade7a00ff8b0df9634ca2bfd7880a | Monikabandal/My-Python-codes | /Detect cycle in directed graph.py | 1,166 | 3.609375 | 4 | class graph:
def __init__(self,V):
self.vertices=V
self.node={}
def addedge(g,u,v):
try:
g[u].append(v)
except:
g[u]=[v]
def check_cycle(node,V,i,stack,visited):
stack[i]=1
visited[i]=1
try:
for j in node[i]:
if visited[j]==0:
if check_cycle(node,V,j,stack,visited)==1:
return True
else:
if stack[j]==1:
return True
except:
pass
stack[i]=0
return False
def is_cyclic(node,V):
visited=[0]*V
stack=[0]*V
for i in range(0,V):
if visited[i]==0:
if check_cycle(node,V,i,stack,visited)==True:
return True
return False
directed_graph=graph(4)
addedge(directed_graph.node,0,1)
addedge(directed_graph.node,0,2)
addedge(directed_graph.node,1,2)
addedge(directed_graph.node,2,0)
addedge(directed_graph.node,2,3)
addedge(directed_graph.node,3,3)
if is_cyclic(directed_graph.node,directed_graph.vertices) ==1 :
print 'Graph is cyclic'
else:
print 'Graph is acyclic' |
51a6e795a4cf86ffd742fbbcab813a702adb2957 | sunshinescience/dim_red_cluster | /figures.py | 918 | 3.765625 | 4 | import matplotlib.pyplot as plt
def plot_images(data, reshape=None, save_fname=None, show=False):
"""
Provides a figure with eight images plotted.
Parameters:
data: image data (e.g., digits.images)
reshape: Input reshape values as a tuple of two numbers (e.g., (8, 8)).
save_fname: whether or not to save the file to a .png file
show: whether or not to show the figure
"""
inversed_lst = range(0, 10)
fig = plt.figure(figsize=(10,2))
plt_index = 0
for i in inversed_lst:
plt_index = plt_index + 1
ax = fig.add_subplot(1, 10, plt_index)
data_ind = data[i]
if reshape is not None:
data_ind.reshape(reshape)
ax.imshow(data_ind, cmap=plt.cm.gray_r, interpolation='nearest')
plt.tight_layout()
if save_fname is not None:
plt.savefig(save_fname, dpi=150)
if show:
plt.show()
|
3c2924ea9a593f799f548f558f77b2a97bc1217b | disorn-inc/data_structure_algo_i | /data_structure/array/63_arrays_intro/strings.py | 147 | 3.5625 | 4 | strings = ["a", "b", "c", "d"]
strings[2]
strings.append("e")
strings.pop()
strings.insert(0, "x")
strings.insert(2, "alien")
print(strings) |
b47c02046b7ab21d83514cb8bcf945753dda0918 | abhinav3398/similarities | /helpers.py | 1,277 | 3.578125 | 4 | def lines(a, b):
"""Return lines in both a and b"""
lines_O_a = a.split('\n')
lines_O_b = b.split('\n')
lines_O_a = set(lines_O_a)
lines_O_b = set(lines_O_b)
common_lines = lines_O_a.intersection(lines_O_b)
return list(common_lines)
def sentences(a, b):
"""Return sentences in both a and b"""
from nltk.tokenize import sent_tokenize
sentences_O_a = sent_tokenize(a)
sentences_O_b = sent_tokenize(b)
sentences_O_a = set(sentences_O_a)
sentences_O_b = set(sentences_O_b)
common_sentences = sentences_O_a.intersection(sentences_O_b)
return list(common_sentences)
def substrings(a, b, n):
"""Return substrings of length n in both a and b"""
substrings_O_a = [a[i:i+n] for i in range(len(a)-n+1)]
substrings_O_b = [b[j:j+n] for j in range(len(b)-n+1)]
common_substrings = []
if len(substrings_O_a) < len(substrings_O_b):
for substring in substrings_O_a:
if substring in substrings_O_b:
common_substrings.append(substring)
else:
for substring in substrings_O_b:
if substring in substrings_O_a:
common_substrings.append(substring)
common_substrings = set(common_substrings)
return list(common_substrings)
|
fc585a57255fa96d28bd560186a16f46d4daee22 | TeluguOCR/datagen_initio | /counters/count_unichars.py | 442 | 4.03125 | 4 | #!/usr/bin/env python3
import sys
from collections import Counter
if len(sys.argv) == 1:
print('''Usage:{0} input_file
Counts the number of occurences of each unicode character in
the given <input_file>'''.format(sys.argv[0]))
sys.exit()
file_name = sys.argv[1]
count = Counter()
with open(file_name) as f:
for line in f:
count.update(line)
for char, k in sorted(count.items()):
print(char, " ", k) |
dfc950230c319e471f735e3d12c21bdf2adb432a | zero060699/Practice-Python | /kiemtrasonguyento.py | 354 | 3.515625 | 4 | while True:
n = int(input("Nhập 1 số nguyên dương:"))
dem=0
for i in range(n,n+1):
if n%i == 0:
dem+=1
if dem==2:
print(n,"Là số nguyên tố")
else:
print(n,"Không là số nguyên tố")
hoi = input("Tiếp tục ko?:")
if hoi is "k":
break
print("Bye") |
6bf6a1f365ef34ed3c878e150956b5557a952d6b | AllHailTheSheep/eulers | /16.py | 136 | 3.6875 | 4 | # sum the digits of 2^1000
from math import pow
num = int(pow(2, 1000))
sum = 0
for char in str(num):
sum += int(char)
print(sum) |
c68a9f0109d4d936f3a1148f5fe42743a1aa8ede | Dev-rromanov/----------- | /temp.py | 233 | 3.609375 | 4 | def foo(temperature):
if int(temperature) > 25:
return 'Hot'
elif int(temperature) > 15 and int(temperature) < 25:
return 'Warm'
elif int(temperature) < 15:
return 'Cold'
print (foo(26))
|
447ed845c9abf515d3a52e72025e91f192219855 | EveEuniceBanda/Beginners-Labs | /try_this Lab 12.py | 1,893 | 4.21875 | 4 | #!/usr/bin/env python3
#Global promptFunction get_user_age
#Function name: get_user_age
def get_user_age():
# Initialize your prompt string
prompt_age_msg = "Please enter your age"
#############################################################
# The prompt strng has been changed to a GLOLBAL variablle
# Prompt the user for their age
#...Because the input function returns a string value
#...We are converting the string valaue to an integer value
#############################################################
user_str= input(prompt_age_msg)
# The string function isdigit returns TRUE if all digits are numeric
if (user_str.isdigit()):
user_age = int(user_str)
else:
#if they entered a string value, then set the age to 0
#This will eventurally flag our error condition
user_age = 0
# Retuns the user's age
return user_age
#################################################################################
#BEGIN the main program
################################################################################
#Call the function, get_user_age
my_user_age = get_user_age()
################################################################################
#ERROR CHECKING: Check that the user_age is over 0
################################################################################
while (my_user_age <=0):
my_user_age = get_user_age()
#END of the while loop, for the USER-AGE intilixation
################################################################################
#Print out a statement using the user_age_variable
################################################################################
prompt_sge_mdg = "wrong format entered, Enter an integer value for your age."
print("Your age is: ", my_user_age, "years old.")
print()
|
275f04cb38322decc37546f1b3d1f5b7aabb659e | RakeshSuvvari/Joy-of-computing-using-Python | /factorial.py | 630 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 4 23:23:52 2021
@author: rakesh
"""
def factorial_ite(n):
answer = 1
for i in range(1,n+1):
answer = answer * i
return answer
'''
base case or anchor case
point where recursion stops
'''
def factorial_rec(n):
if(n == 0):
return 1
if n >= 1:
return n * factorial_rec(n-1)
n = int(input("Enter the +ve Number: "))
if n < 0:
print("Factorial not defined on negtive numbers")
else:
print("Using iterative method ",n,"! = ",factorial_ite(n))
print("Using recursion method ",n,"! = ",factorial_rec(n)) |
c44e3e766eb98e97a6582676b5ad62e4fec95ece | DanielJChong/PythonStack | /python/Day1_Notes.py | 2,261 | 4.15625 | 4 | # # var_name = "Some value";
# # "=" this is NOT and equals, it means "set as"
# # Primitive
# some_string = "Some value" # string
# some_number = 123 # integer
# some_decimal = 1.23 # floats
# some_boolean = True # boolean
# some_boolean_2 = False # boolean
# some_none = None # None == null
# # Composite
# some_list = [] # Lists, NOT Arrays, in Python
# some_list.append(1) # Adding something to the "List"; use instead of "push"
# some_list.pop()
# some_dictionary = {
# 'some_key': "Some value",
# 'some_other': 123
# }
# some_dictionary ['some_key']
# # Built-Ins
# # console.log("Something");
# print("The exact same thing")
# len() # how many characters are in the string or list
# print(len(some_list))
# print(len())
# # If Statements, for Python (same as before...)
# # if(5 > 2){
# # console.log("5 is bigger than 2")
# # }
# if 5 > 2:
# print('5 is bigger than 2')
# elif 2 > 5:
# # elif: = else if:
# # For Loops, for Python
# # for = range
# # "JavaScript"
# # for(i = 0; i < arr.length; i++){
# # console.log(i);
# # }
# print(range(2, 12, 1))
# # "2" is a starting point
# # "12" is the ending point, not including that number
# # "1" is how many numbers it is going up or down by
# # answer would be [2,3,4,5,6,7,8,9,10,11]
# #Example of for statement in Python
# for i in range (0, 12, 1):
# print(i)
# listy_list = [0, 4, 6]
# sum = 0
# # Modify list
# for i in range(len(listy_list)):
# listy_list[i] = 3
# # Use/Reference list
# for i in listy_list:
# sum += i
# # OR
# for i in range(len(listy_list)):
# sum += listy_list[i]
# print(sum)
# # "for i in range(len(listy_list)):"" is exactly the same as "for(i = 0; i < arr.length; i++)"
# # Functions
# # "JavaScript" =
# # function funcName(parameter) {
# # console.log(parameter);
# # };
# # funcName(123)
# # "Python" =
# def func_name(parameter):
# print(parameter)
# func_name(123)
first_name = "Zen"
last_name = "Coder"
age = 27
print("My name is {} {} and I am {} years old.".format(first_name, last_name, age))
# output: My name is Zen Coder and I am 27 years old.
print("My name is {} {} and I am {} years old.".format(age, first_name, last_name))
# output: My name is 27 Zen and I am Coder years old. |
3a06ffa2ccdf987ef1fa50e43a88d4afac343988 | skreynolds/python_practiceExercises | /46rot13/rot13.py | 1,167 | 4.5625 | 5 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
ROT13 is a simple letter substitution cipher that replaces a letter with the
letter 13 letters after it in the alphabet. ROT13 is an example of the Caesar
cipher.
Create a function that takes a string and returns the string ciphered with
Rot13. If there are numbers or special characters included in the string, they
should be returned as they are. Only letters from the latin/english alphabet
should be shifted, like in the original Rot13 "implementation".
Please note that using "encode" in Python is considered cheating.
Created on Sun Jun 17 15:40:23 2018
@author: shane
"""
import string
from codecs import encode as _dont_use_this_
def rot13(message):
alph = 'abcdefghijklmnopqrstuvwxyz'
#initialise output
out_string = ''
for e in message:
num = (ord(e.lower()) - 97) + 13
if num > 26:
num -= 26
if e.isupper():
out_string += chr(num+97).upper()
else:
out_string += chr(num+97)
return out_string
if __name__ == '__main__':
print(rot13("Test")) |
058ac196c75c9c5c9d9622db1bbba0e5a7a76e66 | python-yc/pycharm_script | /w3cschool/tmp.py | 214 | 3.515625 | 4 | def f():
c = 1
def fa():
d = c + 1
return d
return fa
a = f()
print(type(a))
print(a())
def f():
c = 1
def fa():
c = c + 1
return c
return fa
a = f()
|
0a5875cf9390b7b142e3b94fc9d95d08f57987c8 | IngSimon/Project-Repository | /script 5.file_gen.py | 1,383 | 3.796875 | 4 | """
This script creates a txt file with a specified percentage.
The name of directory: provided by user
"""
import os
import sys
import random
def trim_data(percent, name2, filename2, filename3, num2= 1024, filename1="./data/all_params.txt"):
num1 = int(round((num2*percent/100), 0))
with open(filename1) as file:
lines = file.read().splitlines()
random_lines = random.sample(lines, num1)
with open(filename2, "w") as output_file1:
output_file1.writelines(line + '\n' for line in lines if line not in random_lines)
output_file1.close()
with open(filename3, "w") as output_file2:
output_file2.writelines(line + '\n' for line in lines if line in random_lines)
output_file2.close()
num_of_lines = num2 - num1
remainder = 100 - percent
return remainder
percent = input('Please enter the percentage of entries to remove: ')
name2 = input('Please enter the name of the directory for the output files: ')
os.makedirs(name2)
filename2 = './' + name2 + '/' + "training" + '.txt'
filename3 = './' + name2 + '/' + "removed" + '.txt'
print 'A file {} with {} percent of the original data has been successfully generated'.format(filename2, trim_data(percent, name2, filename2, filename3, num2= 1024, filename1="./data/all_params.txt"))
|
0bc7c5a6a2d81fca4e6d955e81f5f2084c42d953 | mondchopers/roi | /ROI/test.py | 707 | 3.84375 | 4 | import itemkey as itk
## Testing that all buildings in dictionary are in the correct format ##
itemList = list(itk.itemDict.keys())
for i, building in itk.buildingDict.items():
check = True
# Input Check
for item in building[2]:
if len(item) == 0:
continue
if item[0] not in itemList:
check = False
print(item)
# Output Check
for item in building[1]:
if len(item) == 0:
continue
if item[0] not in itemList:
check = False
print(item)
if not check:
print("Building", building[0], i, "invalid")
break
else:
print("Building", building[0], i, "valid")
|
08ddebb75d4c65f081ec8cceab3153917db321ac | dalalsunil1986/Algoexpert-4 | /Easy/13-CaesarCipherEncryptor.py | 1,226 | 3.796875 | 4 | # Solution 1
# def caesarCipher(string, key):
# '''
# Time: O(n)
# Space: O(n)
# '''
# ans = ''
# for letter in string:
# asci = ord(letter)
# encrypt = asci + (key % 26)
# if encrypt <= 122:
# ans += chr(encrypt)
# else:
# ans += chr(96 + (encrypt % 122))
# return ans
# Solution 2
# def caesarCipherEncryptor(string, key):
# '''
# Time: O(n)
# Space: O(n)
# '''
# new = []
# key = key % 26
# for letter in string:
# new.append(getLetter(letter, key))
# return "".join(new)
# def getLetter(letter, key):
# newCode = ord(letter) + key
# return chr(newCode) if newCode <= 122 else chr(96+newCode % 122)
# Solution 3
def caesarCipherEncryptor(string, key):
'''
Time: O(n)
Space: O(n)
'''
new = []
key = key % 26
alphabet = list("abcdefghijklmnopqrstuvwxyz")
for letter in string:
new.append(getLetter(letter, key, alphabet))
return "".join(new)
def getLetter(letter, key, alphabet):
newCode = alphabet.index(letter) + key
return alphabet[newCode] if newCode <= 25 else alphabet[-1+newCode % 25]
print(caesarCipherEncryptor('xyz', 54))
|
c97d27aa75300dd6a59cd466ff0eb78805641041 | BruceLiu163/pythontutorial | /python_oop/about_class_property.py | 734 | 4.09375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
property:
使用property装饰器,定义属性
@property装饰器就是负责把一个方法变成属性调用
Python内置的@property装饰器就是负责把一个方法变成属性调用
Python内置的@property装饰器就是负责把一个方法变成属性调用
Python内置的@property装饰器就是负责把一个方法变成属性调用
"""
class Student(object):
@property
def name(self):
return self._name
@name.setter
def name(self, name):
if not isinstance(name, str):
raise ValueError('---name must be str!!---')
self._name = name
stu1 = Student()
stu1.name = 'Bruce Liu'
print(stu1.name)
|
7b06158802ae136ade8c5e57d52be20b6cc34039 | kuronbo/maze | /maze/solver.py | 441 | 3.546875 | 4 | def dfs(maze):
"""深さ優先探索により迷路のスタートからゴールまでの経路を探す"""
def _dfs(path):
if maze.is_goal(path[-1]):
return path
for posi in maze.next_road_positions(path[-1]):
new_path = None
if posi not in path:
new_path = _dfs(path+[posi])
if new_path:
return new_path
return _dfs([maze.start])
|
d400f3cdfb19d280a2a8ca1d9b3a2d3b246f2e88 | AnkitMittal0501/PythonProject | /oops2.py | 225 | 3.65625 | 4 | class cons:
def __init__(self, a, b):
self.a = a
self.b = b
def sum(self,d):
return self.a+self.b+d
def sub(self):
return self.a-self.b
c=cons(3,2)
print(c.sum(5))
print(c.sub()) |
f1f7fe2c25d024e95a20b9c636fcb001a056521a | RandyHodges/Self-Study | /Python/controlStructures/InvestmentCalculator.py | 1,625 | 4.34375 | 4 |
# ================= Compulsory Task ==================
# Create a new Python file in this folder called "InvestmentCalculator.py".
# At the top of the file include the line:
# import math
# Ask the user to input:
# The amount that they are depositing, stored as ‘P’.
# The interest rate (as a percentage), stored as ‘i’.
# The number of years of the investment. stored as ‘t’.
# Then ask the user to input whether they want “simple” or “compound” interest, and store this in a variable called ‘interest’.
# Only the number of the interest rate should be entered - don’t worry about having to deal with the added ‘%’,
# e.g. The user should enter 8 and not 8%.
# Depending on whether they typed “simple” or “compound”, output the appropriate amount that they will get after the given period at the interest rate.
# Print out the answer!
# Try enter 20 years and 8 (%) and see what a difference there is depending on the type of interest rate!
import math
P = input("Please enter the amount you are depositing: ")
i = input("Please enter the interest rate: ")
t = input("Please enter the number of years for investment: ")
interest = input("Do you want to calculate simple or compund interest? simple/compund: ")
simpleValue = float(P) * (1+(float(i)/100)*int(t))
compoundValue = (float(P) * (math.pow(1+(float(i)/100),int(t))))
if interest == "simple":
print("\nThe value of your simple investment after your selected period is: R" + str(simpleValue))
else:
print("\nThe value of your compund investment after your selected period is: R" + str(compoundValue))
|
a9c4c03fcb56365e720027c97623e7785bfb810c | Hitbee-dev/Data_Science_with_Book | /02_DeepLearning-from-scratch-2/common/dataset.py | 4,109 | 3.65625 | 4 | # https://github.com/WegraLee/deep-learning-from-scratch-2
# 여러가지 dataset 생성기를 딥러닝 라이브러리 없이 구현
import sys
import os
sys.path.append('..')
import urllib.request
import pickle
import numpy as np
class Spiral:
def __init__(self, sample_num=100, feature_num=2, class_num=3):
self.sample_num = sample_num
self.feature_num = feature_num
self.class_num = class_num
def load_data(self, seed=2019):
np.random.seed(seed)
x = np.zeros((self.sample_num * self.class_num, self.feature_num))
t = np.zeros((self.sample_num * self.class_num, self.class_num), dtype=np.int)
for j in range(self.class_num):
for i in range(self.sample_num):
rate = i / self.sample_num
radius = 1 * rate
theta = j * 4 + 4 * rate + np.random.randn() * 0.2
idx = self.sample_num * j + i
x[idx] = np.array([radius * np.sin(theta), radius * np.cos(theta)]).flatten()
t[idx, j] = 1
return x, t
class PTB:
def __init__(self):
self.url_base = 'https://raw.githubusercontent.com/tomsercu/lstm/master/data/'
self.key_file = {
'train':'ptb.train.txt',
'test':'ptb.test.txt',
'valid':'ptb.valid.txt'
}
self.save_file = {
'train':'ptb.train.npy',
'test':'ptb.test.npy',
'valid':'ptb.valid.npy'
}
self.vocab_file = 'ptb.vocab.pkl'
self.dataset_dir = os.path.dirname(os.path.abspath("__file__")) + '/' + 'ptb_dataset'
self.file_name = ""
def _download(self, file_name):
self.file_name = self.file_name
file_path = self.dataset_dir + '/' + self.file_name
if os.path.exists(file_path):
return
if not os.path.exists(self.dataset_dir):
os.mkdir(self.dataset_dir)
print('Downloading ' + self.file_name + ' ... ')
try:
urllib.request.urlretrieve(self.url_base + self.file_name, file_path)
except urllib.error.URLError:
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
urllib.request.urlretrieve(self.url_base + self.file_name, file_path)
print('Done')
def load_vocab(self):
vocab_path = self.dataset_dir + '/' + self.vocab_file
if os.path.exists(vocab_path):
with open(vocab_path, 'rb') as f:
word_to_id, id_to_word = pickle.load(f)
return word_to_id, id_to_word
word_to_id = {}
id_to_word = {}
data_type = 'train'
self.file_name = self.key_file[data_type]
file_path = self.dataset_dir + '/' + self.file_name
self._download(self.file_name)
words = open(file_path).read().replace('\n', '<eos>').strip().split()
for i, word in enumerate(words):
if word not in word_to_id:
tmp_id = len(word_to_id)
word_to_id[word] = tmp_id
id_to_word[tmp_id] = word
with open(vocab_path, 'wb') as f:
pickle.dump((word_to_id, id_to_word), f)
return word_to_id, id_to_word
def load_data(self, data_type='train'):
'''
:param data_type: 데이터 유형: 'train' or 'test' or 'valid (val)'
:return:
'''
if data_type == 'val': data_type = 'valid'
save_path = self.dataset_dir + '/' + self.save_file[data_type]
word_to_id, id_to_word = self.load_vocab()
if os.path.exists(save_path):
corpus = np.load(save_path)
return corpus, word_to_id, id_to_word
self.file_name = self.key_file[data_type]
file_path = self.dataset_dir + '/' + self.file_name
self._download(self.file_name)
words = open(file_path).read().replace('\n', '<eos>').strip().split()
corpus = np.array([word_to_id[w] for w in words])
np.save(save_path, corpus)
return corpus, word_to_id, id_to_word
|
b8c5b6562387976ead48601daa4741c12e68702c | haoen110/FullStackPython | /02.Python/01.PythonBasic/codes/006if.py | 239 | 3.609375 | 4 | # 006if.py
n = int(input("请输入一个数,判断数是否大于100、小于0、介于20~50之间"))
if n > 100:
print("这个数大于100")
elif n < 0:
print("这个数小于0")
elif 20 < n < 50:
print("这个数介于20~50之间") |
05fb9cb9b6cda319de611a46860019be4998d70e | csatyajith/leetcode_solutions | /september_challenge/root_to_leaf_sum.py | 1,160 | 3.921875 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def traverse_tree(self, node, num, nums):
if node:
num += str(node.val)
if not node.left and not node.right:
nums.append(num)
else:
self.traverse_tree(node.left, num, nums)
self.traverse_tree(node.right, num, nums)
return nums
def sumRootToLeaf(self, root: TreeNode) -> int:
nums = self.traverse_tree(root, "", [])
sum_d = 0
for num in nums:
num_d = 0
for i in range(len(num)):
num_d += int(num[-(i + 1)]) * (2 ** i)
sum_d += num_d
print(nums)
return sum_d
if __name__ == '__main__':
sol = Solution()
root = TreeNode(1)
root.left = TreeNode(0)
root.right = TreeNode(1)
root.left.left = TreeNode(0)
root.left.right = TreeNode(1)
root.right.left = TreeNode(0)
root.right.right = TreeNode(1)
print(sol.sumRootToLeaf(root))
|
df401f43a0e4e7182f5dc4b223315867d636bd3a | aurel1212/Sp2018-Online | /students/darrell/wk6 - assignments/calculator-activity/calculator/subtracter.py | 255 | 3.71875 | 4 | """ This module provides a subtraction operator """
class Subtracter(object):
""" subtractor class """
@staticmethod
def calc(operand_1: object, operand_2: object) -> object:
""" calc method """
return operand_1 - operand_2
|
30e9e1f2b4e5705eca4b2a5855f2852e4e2ab821 | constans73/ejercicios_basicos | /listas2.py | 750 | 4.3125 | 4 | """
Escribir un programa que almacene las asignaturas de un curso
(por ejemplo Matemáticas, Física, Química, Historia y Lengua)
en una lista y la muestre por pantalla el mensaje Yo estudio <asignatura>, donde <asignatura>
es cada una de las asignaturas de la lista.
"""
asignaturas = ["Matematicas", "Física", "Química", "Historia", "Lengua"]
print ("Yo estudio", asignaturas[0])
print ("Yo estudio", asignaturas[1])
print ("Yo estuido", asignaturas[2])
print ("Yo estudio", asignaturas[3])
print ("Yo estudio", asignaturas[4])
####### SOLUCION DEL AUTOR ############
#import os
#os.system("cls")
subjects = ["Matemáticas", "Física", "Química", "Historia", "Lengua"]
for subject in subjects:
print("Yo estudio " + subject) |
f5cc7cbd79ee0c2989817a63deada9ad5d5eb8f5 | hika019/AnacondaProjects | /Python/numpy/nought_and_cross.py | 1,204 | 3.5 | 4 | # -*- coding: utf-8 -*-
import numpy as np
nought = 0
cross = 1
user = nought #初手
X = 3
Y = 3
win = 3
def bord():
global bord
bord = np.zeros([Y, X])
bord[:,:] = np.nan
return bord
def select_XY():
print('X座標Y座標')
put = str(input())
return put
def put():
while True:
XY = select_XY()
x, y = int(XY[0]), int(XY[1])
if x <= X-1 and y <= Y-1 and x >=0 and y >=0:#範囲内かどうか
if bord[y,x] == 0 or bord[y,x] == 1:
print('------------------')
print('既に置かれています')
else:
return y,x
#print(X, Y)
print('エラーもう一度')
def nought_or_cross():
N_or_C = user
#print(N_or_C)
for i in range(X*Y):
Nought_or_Cross = N_or_C % 2
change_bord(Nought_or_Cross)
N_or_C = N_or_C +1
def change_bord(nought_or_cross):
y, x = put()
#print(y,x)
bord[y, x] = nought_or_cross
print(bord)
print('------------------------')
def start():
print('初手{}'.format(user))
print(bord())
#bord()
nought_or_cross()
start() |
9f94511f86a9953633ce33603b74d27219224e17 | kennykingcodes/NUMPY-USER-INPUT-SIMPLE-INTEREST-CALCULATOR- | /import numpy_financial as npf.py | 553 | 3.5625 | 4 | """ USE $ pip install numpy-financial TO GET MODULE """
import numpy_financial as npf
""" USE $ pip install numpy TO GET MODULE """
import numpy as np
#Simple interest
principal = int(input("enter principal amount: ")) # Principal Amount
annual_rate = float(input("enter annual interest rate: ")) # yearly rate of interest
t = int(input("enter number of years: ")) # TIME
amount = int(principal * (1 + annual_rate * t)) # FORMULA TO FOLLOW
print("Total payment amount (Principal + Interest): $" + str(amount)) # OUTPUT DATA |
59a5c42dab59a5e8bb69aa65bcdaa4008db98752 | maulia-c/Python-Project-Protek | /Protek-Chapter-6-Python/statistik.py | 370 | 3.8125 | 4 | def sum(*all):
m=0
for x in all:
m+=x
print(m)
def average(*all):
m=0
n=0
for x in all:
m+=x
n+=1
avg=m/n
print(avg)
def max (*all):
m=all[0]
for x in all:
if(x>m):
m=x
print(m)
def min(*all):
m=all[0]
for x in all:
if(x<m):
m=x
print(m)
|
a2f9f655dedddd02dcbf07cf499e0eb09cbfce64 | sameersaini/hackerank | /Strings/separateNumbers.py | 1,176 | 3.875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the separateNumbers function below.
# algo is to start from smallest number and then generate its next number and then search it in the string till all the numbers are found.
# if this fails then repeat the step one for numbers of greater length.
# if no match is found till half length of string then return no.
def separateNumbers(s):
ans = False
for i in range(1, len(s)//2+1):
number = int(s[0:i])
found = True
pos = i + 1
next = number + 1
while found:
nextLength = len(str(next))
if pos + nextLength - 1 <= len(s):
check = s[pos-1: pos + nextLength-1]
if int(check) == next:
next += 1
pos += nextLength
else:
found = False
else:
break
if found and pos >= len(s):
print("YES " + s[0:i])
return
print("NO")
return
if __name__ == '__main__':
q = int(input())
for q_itr in range(q):
s = input()
separateNumbers(s)
|
041f8570ca006cce0c8b94c8b26ad44ed6cffdff | danielforero19/taller-30-de-abril | /ejercicio 3.py | 142 | 3.546875 | 4 | n1 = int(input("ingresa el primer numero: "))
n2 = int(input("ingresa el segundo numero: "))
op = n1+n2
print("la suma", n1,"+", n2, "da", op) |
63f0e2c12f909c17fe39167aa35fb318b09fcf4d | siyoon210/Python-Practice | /Do-it-first-python/mission/5-02.py | 409 | 3.578125 | 4 | # 치즈 접시가 비어 있어요
cheeze = []
# 치즈 접시에 문자열 '치즈'가 무한으로 추가되고, 그때마다 '치즈 추가!'를 출력해요
while True:
cheeze.append('치즈')
print('치즈 추가!')
# cheeze 속 치즈가 50개가 되면 추가를 멈추고 '아이~ 배불러!'를 출력해요
if len(cheeze) == 50:
print('아이~ 배불러!')
break
|
b3d99395f21b98e2719d07e5ffdc1b589621a6c7 | ghostkilla/python_100 | /src/1/nlp_9.py | 405 | 3.609375 | 4 | import random
str = 'I couldn’t believe that I could actually understand what I was reading : the phenomenal power of the human mind .'
shuffled_words = []
for word in str.split():
if len(word) > 4:
shuffled_word = word[:1] + ''.join(random.sample(word[1:-1], len(word) - 2)) + word[-1:]
shuffled_words.append(shuffled_word)
else:
shuffled_words.append(word)
print(' '.join(shuffled_words))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.