blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
48ea70aaf45047d633f7469efd286ddcfb1a4ec3 | jamesjakeies/python-api-tesing | /python3.7quick/5polygon.py | 347 | 4.53125 | 5 | # polygon.py
# Draw regular polygons
from turtle import *
def polygon(n, length):
"""Draw n-sided polygon with given side length."""
for _ in range(n):
forward(length)
left(360/n)
def main():
"""Draw polygons with 3-9 sides."""
for n in range(3, 10):
polygon(n, 80)
exitonclick()
main()
|
1f7ed4325ab493a60d95e04fa38d22d30578a966 | jamesjakeies/python-api-tesing | /python3.7quick/4face.py | 622 | 4.25 | 4 | # face.py
# Draw a face using functions.
from turtle import *
def circle_at(x, y, r):
"""Draw circle with center (x, y) radius r."""
penup()
goto(x, y - r)
pendown()
setheading(0)
circle(r)
def eye(x, y, radius):
"""Draw an eye centered at (x, y) of given radius."""
circle_at(x, y, radius)
def face(x, y, width):
"""Draw face centered at (x, y) of given width."""
circle_at(x, y, width/2)
eye(x - width/6, y + width/5, width/12)
eye(x + width/6, y + width/5, width/12)
def main():
face(0, 0, 100)
face(-140, 160, 200)
exitonclick()
main()
|
d6d0c17beb728a9731c6869436b05a2df5805458 | jamesjakeies/python-api-tesing | /python_crash_tutorial/Ch2/mymax2.py | 689 | 3.71875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author: xurongzhong#126.com wechat:pythontesting qq:37391319
# 技术支持 钉钉群:21745728(可以加钉钉pythontesting邀请加入)
# qq群:144081101 591302926 567351477
# CreateDate: 2018-6-12
# mymax2.py
# Write max function without built-in max().
def mymax2(x, y):
"""Return larger of x and y."""
largest_so_far = x
if y > largest_so_far:
largest_so_far = y
return largest_so_far
def main():
print("MyMax: Enter two values to find the larger.")
first = float(input("First value: "))
second = float(input("Second value: "))
print("The larger value is", mymax2(first, second))
main()
|
8b356cc4864e395ad9b3f85e7ed89774d0a1fe3e | jamesjakeies/python-api-tesing | /python_crash_tutorial/Ch2/evens_comp.py | 200 | 4.21875 | 4 | # evens_comp.py
# Find even values in a list of numbers using list comprehension
def evens(items):
"""Return list of even values in items."""
return [item for item in items if item % 2 == 0]
|
68f115a2695bbabb5b8fbfadb15119bbad899585 | jamesjakeies/python-api-tesing | /python_crash_tutorial/Ch2/mymin.py | 235 | 4.09375 | 4 | # mymin.py
# Find smallest element of a list
def mymin(items):
"""Return smallest element in items."""
smallest = items[0]
for item in items[1:]:
if item < smallest:
smallest = item
return smallest
|
29362f4276d7ac83c520b89417bed94d2a771a4f | jamesjakeies/python-api-tesing | /python_crash_tutorial/Ch1/randomwalk.py | 352 | 4.25 | 4 | # randomwalk.py
# Draw path of a random walk.
from turtle import *
from random import randrange
def random_move(distance):
"""Take random step on a grid."""
left(randrange(0, 360, 90))
forward(distance)
def main():
speed(0)
while abs(xcor()) < 200 and abs(ycor()) < 200:
random_move(10)
exitonclick()
main()
|
758a998bc6b956e29baec359b0d916ff8992fd32 | Chetan2808/Basic-Python-Questions | /Find_Substring.py | 116 | 3.71875 | 4 | User=input("Enter a string:")
for i in range(len(User)):
for j in range(i,len(User)):
print(User[i:j+1]) |
72ccfe3dc8a06d969b0a10750ff5e759c3362367 | waynelinbo/ToC_DEMO | /GuessA4B4.py | 1,929 | 3.546875 | 4 | import random
class GuessA4B4():
def __init__(self):
self.answer = ""
self.record = ""
self.generate()
def generate(self):
self.record = ""
a = int((random.random())*10)
b = int((random.random())*10)
while b == a :
b = int((random.random())*10)
c = int((random.random())*10)
while (c == a) | (c == b) :
c = int((random.random())*10)
d = int((random.random())*10)
while (d == a) | (d == b) | (d == c) :
d = int((random.random())*10)
st = str(a) + str(b) + str(c) + str(d)
print(st)
self.answer = st
def compare(self, st, m):
if len(st) != 4:
return "0"
try :
num = int(st)
except ValueError:
return "1"
for i in range(4):
for j in range(i+1,4):
if st[i] == st[j] :
return "2"
A = 0
B = 0
for i in range(4):
for j in range(4):
if i == j :
if st[i] == self.answer[j] :
A += 1
else :
if st[i] == self.answer[j] :
B += 1
if m == 0:
self.record += st + " => "+ str(A) + "A" + str(B) + "B" + "\n"
if A == 4:
return "-1"
else:
return str(A) + "A" + str(B) + "B"
"""
s = GuessA4B4()
while(1):
x = input("4 integers : ")
a = s.compare(x)
if a == "2":
print("please input 4 different intreger\n")
elif a == "1":
print("please input 4 \"integer\"\n")
elif a == "0":
print("please input \"4\" integer\n")
elif a == "-1":
print("congratulations\n")
s.generate()
else:
print(a + "\n")
""" |
a3a9af479cf44706b7a4f4902e64ebcabf88094c | WillDutcher/Python_Essential_Training | /chap05/precedence.py | 682 | 4.03125 | 4 | #!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
# Completed Chap05: Lesson 24 - Operator precedence
# Precedence order is:
print("**\n\tExponent\n")
print("+x, -x\n\tPositive, negative\n")
print("*, /, //, %\n\tMultiplication, division, remainder\n")
print("+, -\n\tAddition and subtraction\n")
print("<<, >>\n\tBitwise shifts\n")
print("&\n\tBitwise AND\n")
print("^\n\tBitwise OR\n")
print("|\n\tExponent\n")
print("in, not in, is, is not, <, <=, >, >=, !=, ==\n\tComparisons, including membership tests and identity tests\n")
print("not x\n\tBoolean NOT\n")
print("and\n\tBoolean AND\n")
print("or\n\tBoolean OR\n")
z = 2 + 4 * 5
print(z)
|
51578c97eb0b4a7478be114fa2eca98b713613ca | WillDutcher/Python_Essential_Training | /Chap05/bitwise.py | 674 | 4.375 | 4 | #!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
# Completed Chap05: Lesson 21 - Bitwise operators
x = 0x0a
y = 0x02
z = x & y
# 02x gives two-character string, hexadecimal, with leading zero
# 0 = leading zero
# 2 = two characters wide
# x = hexadecimal display of integer value
# 08b gives eight-character string, binary, with leading zeroes
# 0 = leading zeroes, where applicable
# 8 = 8 characters wide
# b = binary display of integer value
print(f'(hex) x is {x:02x}, y is {y:02x}, z is {z:02x}')
print(f'(bin) x is {x:08b}, y is {y:08b}, z is {z:08b}')
print("&\tAnd")
print("|\tOr")
print("^\tXor")
print("<<\tShift left")
print(">>\tShift right")
|
2b5a45674ba5f67b391b312f89361584336efb8c | WillDutcher/Python_Essential_Training | /Chap02/while.py | 627 | 3.71875 | 4 | #!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
words = ['one', 'two', 'three', 'four', 'five']
n = 0
while(n < 5):
print(words[n])
n += 1
moreWords = ["ten", "nine", "eight", "seven", "six", "five", "four", "three", "two", "one", "zero"]
x = 10
while(x < 11):
print('x = ', moreWords[x])
x -= 1
if x == 0:
break
ageList = [37, 38, 39, 40, 41, 42]
age = 36
year = 2015
while age < 44:
if year > 2018:
print("In the year", year, "\b, I will be", age, "years old.")
else:
print("In the year", year, "\b, I was", age, "years old.")
age +=1
year += 1
|
1ce0280f860821796f022583f2b5b96950f587b9 | WillDutcher/Python_Essential_Training | /Chap05/boolean.py | 670 | 4.1875 | 4 | #!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
# Completed Chap05: Lesson 23 - Comparison operators
print("\nand\t\tAnd")
print("or\t\tOr")
print("not\t\tNot")
print("in\t\tValue in set")
print("not in\t\tValue not in set")
print("is\t\tSame object identity")
print("is not\t\tNot same object identity\n")
print("*"*50,"\n")
a = True
b = False
x = ( 'bear', 'bunny', 'tree', 'sky', 'rain' )
y = 'tree'
if a and b:
print('expression is true')
else:
print('expression is false')
if y in x:
print("Yep, it is.")
else:
print("Nope, it's not.")
if y is x[0]:
print("Yes, that's the same.")
else:
print("No, they're different.")
|
192b0b3df4141933e1bbb32f231016f6df1ff8b6 | Purav16/Collections-Java-Data-Structures-Java-Python-3.6-JavaScript-Programs | /Reversed_Array.py | 145 | 3.5625 | 4 | import numpy as np
import numpy as np
x = np.arange(12, 38)
print("Original array:")
print(x)
print("Reverse array:")
x = x[::-1]
print(x) |
3034e9856e10055dce53165daf2219e69158ceea | Purav16/Collections-Java-Data-Structures-Java-Python-3.6-JavaScript-Programs | /Python list operations.py | 411 | 3.859375 | 4 | #list operations
power = [1,2,3,4,5,6,7,8,9]
list2 = [x*x for x in power]
print(list2)
#getting values wth both lists
#Square operation within the list with index values
list3 = [[x,x*x] for x in power]
print(list3)
#loops
list4 = [x*x for x in power if x > 4]
print(list4)
#Strip() function
list5 = ['111n111', '111m111' ,'000y000' ,'000x000']
list6 = [element.strip(0,1) for element in list5]
print(list6)
|
b550146c5d6d639c6e90bcc3b43078f00c5ee973 | Purav16/Collections-Java-Data-Structures-Java-Python-3.6-JavaScript-Programs | /Sets_Duplication_Python.py | 197 | 3.953125 | 4 | #Python Sets
set_1 = {'One' , 'Two' , 'Three' , 'Four'}
print_set={x for x in set_1}
print(print_set,1)
#Duplication removal/not allowed in Sets
a = set('vslvnlsndlsvSHVJskdslhsjksaa')
print(a)
|
fef1ca3fec0d8aa599fba152711d7715fc4bcbe7 | Qg2TzVSm/leetcode | /arraypartitioni.py | 940 | 3.609375 | 4 | # Given an array of 2n integers,
# your task is to group these integers into n pairs of integer,
# say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n
# as large as possible.
# Example 1:
# Input: [1,4,3,2]
# Output: 4
# Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min(3, 4).
# Note:
# n is a positive integer, which is in the range of [1, 10000].
# All the integers in the array will be in the range of [-10000, 10000].
class Solution(object):
def arrayPairSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if nums:
if len(nums)%2 == 0:
if min(nums)>= -10000 and max(nums)<=10000:
nums.sort()
n = 0
for x in range(0, int(len(nums)/2)):
n += min(nums[2*x],nums[2*x+1])
return n
s = Solution()
s = s.arrayPairSum([1,4,3,2]) |
501c5e366a15a6a278849893d83c9497d8bf3c19 | BhuviGoel/Backup-Files | /backupFiles.py | 1,933 | 4.09375 | 4 | import os
import shutil
import time
def main():
# initializing the count
deleted_folders_count = 0
deleted_files_count = 0
# specify the path
path = input("Enter the path of files/folder you want to delete: ")
# converting days to seconds
days = 30
seconds = time.time() - (days * 24 * 60 * 60)
if os.path.exists(path):
for root_folder, folders, files in os.walk(path):
# comparing the days
if seconds >= get_file_or_folder_age(root_folder):
# remove_folder function
remove_folder(root_folder)
deleted_folders_count += 1
else:
for folder in folders:
# folder path
folder_path = os.path.join(root_folder, folder)
# comparing with the days
if seconds >= get_file_or_folder_age(folder_path):
# remove_folder function
remove_folder(folder_path)
deleted_folders_count += 1
for f in files:
# file path
file_path = os.path.join(root_folder, f)
# comparing the days
if seconds >= get_file_or_folder_age(file_path):
# remove_file function
remove_file(file_path)
deleted_files_count += 1
else:
# if the path is not a directory
if seconds >= get_file_or_folder_age(path):
remove_file(path)
deleted_files_count += 1
else:
# file/folder is not found
print(f'"{path}" is not found')
deleted_files_count += 1
print(f"Total folders deleted: {deleted_folders_count}")
print(f"Total files deleted: {deleted_files_count}")
def remove_folder(path):
# removing the folder
if not shutil.rmtree(path):
print(f"{path} is removed successfully")
else:
print(f"Unable to delete the "+path)
def remove_file(path):
# removing the file
if not os.remove(path):
print(f"{path} is removed successfully")
else:
print("Unable to delete the "+path)
def get_file_or_folder_age(path):
# getting ctime of the file/folder
# time will be in seconds
ctime = os.stat(path).st_ctime
return ctime
main() |
f6f56d895de0d31d13cbd555a4c467ff87a128c6 | krishna6431/Python-For-Everybody-Specialization-Coursera-Assignment | /Course3_Using Python to Access Web Data/Week6_JSON/Assignment1/json_parsing.py | 484 | 3.890625 | 4 | # json parsing assignment
#code is written by krishna
#part of course 3 of python for everybody specialization
import json
import urllib.request
url=input("Enter location: ")
data=urllib.request.urlopen(url).read().decode('utf-8')
print("Retrieving",url)
print("Retrieved",len(data),"characters")
info=json.loads(data)
su=0
count=0;
for item in info["comments"]:
su+=int(item["count"])
count+=1
print("Count:",count)
print("Sum:",su)
# thank u so much
|
c3a7c04b0d8508310f94bde26fd9cb387dd95d9b | krishna6431/Python-For-Everybody-Specialization-Coursera-Assignment | /Course2_Python Data Structures/Week1_Graded_Assignment/week1_assignment.py | 445 | 3.765625 | 4 | # Problem Statement :
# 6.5 Write code using find() and string slicing (see section 6.10) to extract
# the number at the end of the line below. Convert the extracted value to a
# floating point number and print it out.
# Code is Written By Krishna
# The code below almost works
text = "X-DSPAM-Confidence: 0.8475";
ind=text.find(" ")
le=len(text)
#print(ind)
res=float(text[ind+1:le])
print(res)
# Thank u so much
|
e11c85cd026cab5ee7c69cba87b1a1f9d5ee8812 | frendylio/EE362 | /Quizes/selection.py | 587 | 3.90625 | 4 | def selection(L):
# Para todos los indexes
for LoopIndexes in range(len(L)):
IndexMin = LoopIndexes
for LoopMin in range(LoopIndexes+1, len(L)):
if L[IndexMin] > L[LoopMin]:
IndexMin = LoopMin
# Cambia el IndexMin with the LoopIndexes
temp = L[LoopIndexes]
L[LoopIndexes] = L[IndexMin]
L[IndexMin] = temp
return L
L = [15, 6, 33, 2, 11, 7, 3, 20, 18, 12, 4, 9, 3, -1, 0]
print("Initial Raw List:", L)
print("Sorted List:", selection(L))
|
04a8f02c0f4f8ed0e69ee61eac3d7fc15c511570 | spacesanjeet/Calculator_func | /calculator_func2.py | 3,292 | 4.21875 | 4 | # author: sanjeet
# calculator with functions
import math # math module
def _sum(x, y): # addition funcition
return x + y
def subtract(x, y): # subtraction function
return x - y
def multiply(x, y): # multiplication function
return x * y
def divide(x, y): # division function
return x / y
def floor_divide(x, y): # floor division function
return x // y
def modulus(x, y): # modulus function
return x % y
def square(x): # square function
return x * x
def square_root(x): # square_root function
return math.sqrt(x)
def power(x, y): # power function
return x ** y
def main(): # main function of the program
print('Calculator')
print('1. Sum')
print('2. Subtract')
print('3. Multiplication')
print('4. Division')
print('5. Floor Division')
print('6. Modulus')
print('7. Square')
print('8. Square Root')
print('9. Power')
print('10. Exit')
while True: # to make sure it continues till the user doesn't quit
choice = int(input('Enter your choice: '))
if choice == 1:
num1 = float(input('Enter a number: '))
num2 = float(input('Enter another number: '))
print('Result is', _sum(num1, num2))
elif choice == 2:
num1 = float(input('Enter a number: '))
num2 = float(input('Enter another number: '))
print('Result is', subtract(num1, num2))
elif choice == 3:
num1 = float(input('Enter a number: '))
num2 = float(input('Enter another number: '))
print('Result is', multiply(num1, num2))
elif choice == 4:
num1 = float(input('Enter a number: '))
num2 = float(input('Enter another number: '))
try:
result = divide(num1, num2)
print('Result is', result)
except:
print("Divide by zero error! Can't divide a number by zero")
elif choice == 5:
num1 = float(input('Enter a number: '))
num2 = float(input('Enter another number: '))
try:
result = floor_divide(num1, num2)
print('Result is', result)
except:
print("Divide by zero error! Can't divide a number by zero")
elif choice == 6:
num1 = float(input('Enter a number: '))
num2 = float(input('Enter another number: '))
try:
result = modulus(num1, num2)
print('Result is', result)
except:
print("Divide by zero error! Can't divide a number by zero")
elif choice == 7:
num1 = float(input('Enter a number: '))
print('Result is', square(num1))
elif choice == 8:
num1 = float(input('Enter a number: '))
print('Result is', square_root(num1))
elif choice == 9:
num1 = float(input('Enter a number: '))
num2 = float(input('Enter another number: '))
print('Result is', power(num1, num2))
elif choice == 10:
print('Thank you!')
break
else:
print('Enter correct choice')
if __name__ == '__main__': # calling the main function
main()
|
a2c421eb4362050d43e86b98dd059a7d60c42f2d | Gborgman05/algs | /py/recursion/pascals_triangle_row.py | 464 | 3.671875 | 4 | # returns a list representing that row in pascals triangle
# row index starts at 0 for [1]
class Solution:
def getRow(self, rowIndex: int) -> List[int]:
if rowIndex == 0:
return [1]
else:
prev = self.getRow(rowIndex - 1)
summed = [1]
for i in range(len(prev) - 1):
summed.append(prev[i] + prev[i+1])
summed.append(1)
return summed
|
c39b64942c8f2733a95a17299b71a8bdcf27c186 | Gborgman05/algs | /ds_scratch/queue.py | 322 | 3.515625 | 4 | # Galen Borgman
# 8/17/2022
# queue
class Q:
def __init__(self, contents=None):
if contents:
self.contents = contents
self.len = len(contents)
else:
self.contents = []
self.len = 0
def __len__(self):
return self.len
# def enqueue(self, item):
|
4b19e1b99629ed304bad294febfa89a0889959d3 | Gborgman05/algs | /py/binary_search.py | 985 | 3.609375 | 4 | import pdb
# https://leetcode.com/problems/binary-search/submissions/
class Solution:
def search(self, nums) -> int:
def sub_search(nums, target, min_index, max_index):
index = (max_index + min_index) // 2
if max_index < min_index:
return -1
elif nums[index] == target:
return index
elif nums[index] > target:
return sub_search(nums, target, min_index, index - 1)
else:
return sub_search(nums, target, index + 1, max_index)
max_index = len(nums) - 1
min_index = 0
return sub_search(nums, target, min_index, max_index)
def bin_search(nums, target):
a = 0
z = len(nums) - 1
# pdb.set_trace()
while a <= z:
mid = (z - a) // 2 + a
if target == nums[mid]:
return mid
elif target < nums[mid]:
z = mid - 1
else:
a = mid + 1
return -1
|
40a908c9b3cf99674e66b75f56809d485f0a81f9 | Gborgman05/algs | /py/populate_right_pointers.py | 1,019 | 3.859375 | 4 | """
# Definition for a Node.
class Node:
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
self.val = val
self.left = left
self.right = right
self.next = next
"""
class Solution:
def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':
saved = root
levels = []
l = [root]
n = []
while l:
n = []
for node in l:
if node:
if node.left:
n.append(node.left)
if node.right:
n.append(node.right)
levels.append(l)
l = n
for level in levels:
for i in range(len(level)):
if level[i] == None:
continue
if i < len(level) - 1:
level[i].next = level[i+1]
else:
level[i].next = None
return root
|
d1c0270de8164f19ea92d9683d6e320cd3d3e37b | Gborgman05/algs | /py/two_sum_sorted.py | 482 | 3.59375 | 4 | # common problem variant, the input array is sorted
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
# Use two pointers traverse from others
start = 0
end = len(numbers) - 1
while start < end:
summ = numbers[start] + numbers[end]
if summ > target:
end -= 1
elif summ < target:
start += 1
else:
return [start+1, end+1] |
4675d4799ea461abc8cbf6dc89446c5fd0814e23 | Gborgman05/algs | /llist/rot_llist.py | 785 | 3.921875 | 4 | # https://leetcode.com/explore/learn/card/linked-list/213/conclusion/1295/
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
saved = head
counter = 0
prev = None
end = None
while counter < k:
if head.next == None:
head = saved
counter += 1
prev = None
end = head
else:
if not prev:
prev = head
head = head.next
if prev:
prev.next = None
head.next = save |
b0bee34fec7a1510ab5c017f505e1495fc15bcf9 | Gborgman05/algs | /py/is_power_of_three.py | 252 | 3.640625 | 4 | class Solution:
def isPowerOfThree(self, n: int) -> bool:
po = 0
tst = 0
while n > tst:
tst = 3 ** po
if n == tst:
return True
po += 1
return False
|
f4fe5b4f7033a7378bb3cee62f1044e49a1b48da | Gborgman05/algs | /py/reverse_words.py | 490 | 3.71875 | 4 | # reverses words but maintains the order of words in a sentence s
class Solution:
def reverseWords(self, s: str) -> str:
def reverse(word):
word = list(word)
l = 0
h = len(word) - 1
while l < h:
tmp = word[l]
word[l] = word[h]
word[h] = tmp
l += 1
h -= 1
return "".join(word)
return " ".join([reverse(word) for word in s.split()]) |
0de0a4d4ab72a858625e1f5778457805ad813e7f | JoshuaKrause/Diodes | /python/game.py | 3,288 | 3.859375 | 4 | import player
import board
import deck
import random
import copy
class Game():
def __init__(self, player_one=player.Player("ONE"), player_two=player.Player("TWO")):
self.player_one = player_one
self.player_two = player_two
self.active_player = self.player_one
self.other_player = self.player_two
self.board = board.Board()
self.deck = deck.Deck()
self.player_one.hand = self.deck.draw_hand()
self.player_two.hand = self.deck.draw_hand()
def switch_player(self):
""" Switch current player to the next player. """
if self.active_player == self.player_one:
self.active_player = self.player_two
self.other_player = self.player_one
else:
self.active_player = self.player_one
self.other_player = self.player_two
def fill_random_board(self, pieces):
""" Fills the board with random cards.
pieces = number of desired cards (int)
"""
total = pieces
while total > 0:
column = random.choice(self.board.get_moves())
card = self.deck.draw_card()
while card not in deck.COLOR_CARDS:
self.deck.discard_card(card)
card = self.deck.draw_card()
self.board.drop_piece(card, column)
total -= 1
def copy_game(self):
""" Returns a deep copy of the game board.
Return: Board object
"""
return copy.deepcopy(self)
def player_move(self):
""" Simple game loop function. """
active = True
while active:
player_input = input('Which card,column: ')
try:
card, column = player_input.split(',')
if not self.active_player.check_hand(card):
print('Invalid card.')
continue
column = int(column)
self.apply_move(card, column)
active = False
except:
print('Bad input')
continue
def apply_move(self, card, column):
""" Applies a move to the board and updates the active player's hand. Then switches players.
card: specified card (string)
column: target column (int)
"""
self.active_player.remove_card(card)
self.active_player.draw_card(self.deck.draw_card())
score, discards = self.board.play_card(card, column)
self.active_player.score += score
if discards:
self.deck.discard_cards(discards)
self.switch_player()
def forecast_move(self, card, column):
""" Creates a copy of the game and applies the supplied move.
card: string
column: int
Return: Game object
"""
game = self.copy_game()
game.apply_move(card, column)
return game
def __str__(self):
output = str(self.board)
output += "\n"
output +="Active player: {} | Current hand: {}\n".format(self.active_player.name, self.active_player.show_hand())
output += "Player One score: {}\nPlayer Two score: {}".format(self.player_one.score, self.player_two.score)
output += "\n"
return output
|
9be5e6cad8942160830e3d4bcca8c66dcac52370 | Avinashgurugubelli/python_data_structures | /linked_lists/singly_linked_list/main.py | 2,546 | 4.46875 | 4 | from linked_list import LinkedList
from node import Node
# Code execution starts here
if __name__ == '__main__':
# Start with the empty list
linked_list_1 = LinkedList()
# region nodes creation
first_node, second_node, third_node = Node(), Node(), Node()
first_node.data = 5
second_node.data = 10
third_node.data = 36
# endregion
# region assigning nodes to linked list
linked_list_1.head = first_node
'''
Three nodes have been created.
We have references to these three blocks as first,
second and third
linked_list_1.head second_node third_node
| | |
| | |
+----+------+ +----+------+ +----+------+
| 5 | None | | 10 | None | | 36 | None |
+----+------+ +----+------+ +----+------+
'''
linked_list_1.head.next = second_node # Link first node with second
'''
Now next of first Node refers to second. So they
both are linked.
linked_list_1.head second_node third_node
| | |
| | |
+----+------+ +----+------+ +----+------+
| 5 | o-------->| 10 | null | | 36 | null |
+----+------+ +----+------+ +----+------+
'''
second_node.next = third_node # Link second node with the third node
'''
Now next of second Node refers to third. So all three
nodes are linked.
linked_list_1.head second third
| | |
| | |
+----+------+ +----+------+ +----+------+
| 5 | o-------->| 10 | o-------->| 36 | null |
+----+------+ +----+------+ +----+------+
'''
lst_Length = linked_list_1.get_list_length
print('length of linked List: '+ str(lst_Length))
linked_list_1.print_list()
# endregion
# region Node insertion
linked_list_1.insert_node_at_position(0, 112) # Insertion at beginning
linked_list_1.insert_node_at_position(linked_list_1.get_list_length, 236) # Insertion at end
linked_list_1.insert_node_at_position(3, 99)
# endregion
# region node deletion
linked_list_1.delete_node_at_position(0)
linked_list_1.delete_node_at_position(3)
linked_list_1.delete_node_at_position(linked_list_1.get_list_length)
# end region |
901a642b7560b36db5eefdc85f3df7d50919a136 | Avinashgurugubelli/python_data_structures | /linked_lists/doubly_linked_lists/doubly_linked_list.py | 4,462 | 3.59375 | 4 | from dl_node import DLNode
class DoublyLinkedList:
def __init__(self):
self.head = DLNode
# print list
def print_list(self):
current_node = self.head
while current_node != None:
print(str(current_node.data))
current_node = current_node.next
def get_length(self):
counter = 0
current_node = self.head
while current_node != None:
counter += 1
current_node = current_node.next
return counter
# region insertion
def insertion_at_begining(self, node_data):
new_node = DLNode()
new_node.data = node_data
if self.head.next == None:
self.head = new_node
else:
new_node.next = self.head
self.head.previous = new_node
self.head = new_node
self.print_list()
def insertion_at_end(self, data):
new_node = DLNode()
new_node.data = data
current_node = self.head
while current_node.next != None:
current_node = current_node.next
current_node.next = new_node
new_node.previous = current_node
print('node with data {} inserted at end'.format(data))
self.print_list()
def insertion_at_position(self, position, data):
current_node = self.head
new_node = DLNode()
new_node.data = data
if position < 0 or position > self.get_length():
print('invalid position')
return
elif position == 0:
self.insertion_at_begining(data)
elif position == self.get_length():
self.insertion_at_end(data)
else:
counter = 1
while current_node != None and counter < position - 1:
current_node = current_node.next
counter += 1
new_node.next = current_node.next
new_node.previous = current_node
current_node.next = new_node
print('node with data {} at position {} inserted, current list length: {}'.format(
data, position, self.get_length()))
self.print_list()
# endregion insertion
# region deletion
def delete_at_begining(self):
if self.head == None:
raise ValueError('currently list is empty')
else:
current_node = self.head
self.head = current_node.next
print('node with data {} deleted at begining, current list length: {}'.format(
current_node.data, self.get_length()))
self.print_list()
def delete_at_end(self):
if self.head == None:
raise ValueError('currently list is empty')
else:
counter = 1
list_length = self.get_length()
current_node = self.head
while current_node != None and counter < list_length:
if counter == list_length-1:
deleted_node = current_node.next
current_node.next = None
print('node with data {} deleted at end, current list length: {}'.format(
deleted_node.data, self.get_length()))
self.print_list()
return
else:
counter += 1
current_node = current_node.next
def delete_at_postion(self, position):
if position <= 0 or position > self.get_length():
print('invalid postion {}, position should be positive number and less than the list length to delete'.format(position))
elif position == 1:
self.delete_at_begining()
elif position == self.get_length():
self.delete_at_end()
else:
current_node = self.head
previous_node = current_node
counter = 1
while current_node != None and counter <= position:
if counter == position:
previous_node.next = current_node.next
print('node with data {} deleted at position {}, current list length: {}'.format(
current_node.data, position, self.get_length()))
self.print_list()
return
else:
counter += 1
previous_node = current_node
current_node = current_node.next
# endregion deletion
|
2156df459912744499eb02f3c4fc9418428a85a9 | DayGitH/Python-Challenges | /DailyProgrammer/DP20150601A.py | 4,068 | 3.5 | 4 | """
[2015-06-01] Challenge #217 [Easy] Lumberjack Pile Problem
https://www.reddit.com/r/dailyprogrammer/comments/3840rp/20150601_challenge_217_easy_lumberjack_pile/
#Description:
The famous lumberjacks of /r/dailyprogrammer are well known to be weird and interesting. But we always enjoy solving
their problems with some code.
For today's challenge the lumberjacks pile their logs from the forest in a grid n x n. Before using us to solve their
inventory woes they randomly just put logs in random piles. Currently the pile sizes vary and they want to even them
out. So let us help them out.
#Input:
You will be given the size of the storage area. The number of logs we have to put into storage and the log count in
each pile currently in storage. You can either read it in from the user or hardcode this data.
##Input Example:
3
7
1 1 1
2 1 3
1 4 1
So the size is 3 x 3. We have 7 logs to place and we see the 3 x 3 grid of current size of the log piles.
#Log Placement:
We want to fill the smallest piles first and we want to evenly spread out the logs. So in the above example we have 7
logs. The lowest log count is 1. So starting with the first pile in the upper left
and going left-right on each row we place 1 log in each 1 pile until all the current 1 piles get a log. (or until we
run out). After that if we have more logs we then have to add logs to piles with 2 (again moving left-right on each
row.)
Keep in mind lumberjacks do not want to move logs already in a pile. To even out the storage they will do it over time
by adding new logs to piles. But they are also doing this in an even distribution.
Once we have placed the logs we need to output the new log count for the lumberjacks to tack up on their cork board.
#Output:
Show the new n x n log piles after placing the logs evenly in the storage area.
Using the example input I would generate the following:
##example output:
3 2 2
2 2 3
2 4 2
Notice we had 6 piles of 1s. Each pile got a log. We still have 1 left. So then we had to place logs in piles of size
2. So the first pile gets the last log and becomes a 3 and we run out of logs and we are done.
#Challenge inputs:
Please solve the challenge using these inputs:
##Input 1:
4
200
15 12 13 11
19 14 8 18
13 14 17 15
7 14 20 7
##Input 2:
15
2048
5 15 20 19 13 16 5 2 20 5 9 15 7 11 13
17 13 7 17 2 17 17 15 4 17 4 14 8 2 1
13 8 5 2 9 8 4 2 2 18 8 12 9 10 14
18 8 13 13 4 4 12 19 3 4 14 17 15 20 8
19 9 15 13 9 9 1 13 14 9 10 20 17 20 3
12 7 19 14 16 2 9 5 13 4 1 17 9 14 19
6 3 1 7 14 3 8 6 4 18 13 16 1 10 3
16 3 4 6 7 17 7 1 10 10 15 8 9 14 6
16 2 10 18 19 11 16 6 17 7 9 13 10 5 11
12 19 12 6 6 9 13 6 13 12 10 1 13 15 14
19 18 17 1 10 3 1 6 14 9 10 17 18 18 7
7 2 10 12 10 20 14 13 19 11 7 18 10 11 12
5 16 6 8 20 17 19 17 14 10 10 1 14 8 12
19 10 15 5 11 6 20 1 5 2 5 10 5 14 14
12 7 15 4 18 11 4 10 20 1 16 18 7 13 15
## Input 3:
1
41
1
## Input 4:
12
10000
9 15 16 18 16 2 20 2 10 12 15 13
20 6 4 15 20 16 13 6 7 12 12 18
11 11 7 12 5 7 2 14 17 18 7 19
7 14 4 19 8 6 4 11 14 13 1 4
3 8 3 12 3 6 15 8 15 2 11 9
16 13 3 9 8 9 8 9 18 13 4 5
6 4 18 1 2 14 8 19 20 11 14 2
4 7 12 8 5 2 19 4 1 10 10 14
7 8 3 11 15 11 2 11 4 17 6 18
19 8 18 18 15 12 20 11 10 9 3 16
3 12 3 3 1 2 9 9 13 11 18 13
9 2 12 18 11 13 18 15 14 20 18 10
#Other Lumberjack Problems:
* [Hard - Simulated Ecology - The
Forest](http://www.reddit.com/r/dailyprogrammer/comments/27h53e/662014_challenge_165_hard_simulated_ecology_the/)
* [Hard - Lumberjack Floating Log Problem]
(http://www.reddit.com/r/dailyprogrammer/comments/2lljyq/11052014_challenge_187_hard_lumberjack_floating/)
"""
def main():
pass
if __name__ == "__main__":
main()
|
37c053274b93adc82558ab9dcca33eaac67fc591 | DayGitH/Python-Challenges | /DailyProgrammer/DP20171121A.py | 2,141 | 3.96875 | 4 | """
[2017-11-21] Challenge #341 [Easy] Repeating Numbers
https://www.reddit.com/r/dailyprogrammer/comments/7eh6k8/20171121_challenge_341_easy_repeating_numbers/
#Description
Locate all repeating numbers in a given number of digits. The size of the number that gets repeated should be more than
1. You may either accept it as a series of digits or as a complete number. I shall explain this with examples:
11**3259**92**321**9824**321**2**3259**
We see that:
+ 321 gets repeated 2 times
+ 32 gets repeated 4 times
+ 21 gets repeated 2 times
+ 3259 gets repeated 2 times
+ 25 gets repeated 2 times
+ 59 gets repeated 2 times
Or maybe you could have no repeating numbers:
1234565943210
You must consider such a case:
**987**020**987**040**9898**
Notice that 987 repeated itself twice (987, 987) and 98 repeated itself four times (98, 98, **98**7 and **98**7).
Take a chunk "9999". Note that there are three 99s and two 999s.
**99**99 9**99**9 9**999**
**999**9 9**999**
#Input Description
Let the user enter 'n' number of digits or accept a whole number.
#Output Description
> RepeatingNumber1:x RepeatingNumber2:y
If no repeating digits exist, then display 0.
Where x and y are the number of times it gets repeated.
#Challenge Input/Output
Input | Output
:--|--:
82156821568221 | 8215682:2 821568:2 215682:2 82156:2 21568:2 15682:2 8215:2 2156:2 1568:2 5682:2 821:2 215:2 156:2
568:2 682:2 82:3 21:3 15:2 56:2 68:2
11111011110111011 | 11110111:2 1111011:2 1110111:2 111101:2 111011:3 110111:2 11110:2 11101:3 11011:3 10111:2 1111:3
1110:3 1101:3 1011:3 0111:2 111:6 110:3 101:3 011:3 11:10 10:3 01:3
98778912332145 | 0
124489903108444899 | 44899:2 4489:2 4899:2 448:2 489:2 899:2 44:3 48:2 89:2 99:2
# Note
Feel free to consider '0x' as a two digit number, or '0xy' as a three digit number. If you don't want to consider it
like that, it's fine.
-----------------------------------------------------------------
If you have any challenges, please submit it to /r/dailyprogrammer_ideas!
Edit: Major corrections by /u/Quantum_Bogo, error pointed out by /u/tomekanco
"""
def main():
pass
if __name__ == "__main__":
main()
|
66231a3abc2241b21c33466b458eed3ac198ec13 | DayGitH/Python-Challenges | /DailyProgrammer/20120307C.py | 2,606 | 4.09375 | 4 | # -*- coding: utf-8 -*-
'''
Challenge #19 will use The Adventures of Sherlock Holmes [https://www.gutenberg.org/cache/epub/1661/pg1661.txt] from
Project Gutenberg [https://www.gutenberg.org/].
Write a program that will build and output a word index for The Adventures of Sherlock Holmes. Assume one page contains
40 lines of text as formatted from Project Gutenberg's site. There are common words like "the", "a", "it" that will
probably appear on almost every page, so do not display words that occur more than 100 times.
Example Output: the word "abhorrent" appears once on page 1, and the word "medical" appears on multiple pages, so the
output for this word would look like:
abhorrent: 1
medical: 34, 97, 98, 130, 160
Exclude the Project Gutenberg header and footer, book title, story titles, and chapters.
'''
import re
with open('20120307.txt', 'r') as f:
text = f.read()
# Remove header and footer
window_strip = re.compile(r"(?<=[\n]{10}).*(?=[\n]{10})", re.DOTALL)
txt = window_strip.search(text)
# Remove glossary
content_strip = re.compile(r"(?<=[\n]{5}).*", re.DOTALL)
txt = content_strip.search(txt.group())
# Remove story and chapter titles
chapter_strip = re.compile(r"([IVX]+\. THE ADVENTURE.*?\n)|(ADVENTURE [IVX]+\..*?\n)|(\n[IVX]+\.\n)", re.DOTALL)
txt = chapter_strip.sub('', txt.group())
# split into 40 line strings
txt = txt.split('\n')
span = 40
txt = ["\n".join(txt[i:i+span]) for i in range(0, len(txt), span)]
#remove everything except letters and spaces
alpha_strip = re.compile(r"[^a-zA-Z\s]+", re.DOTALL)
for p in range(len(txt)):
txt[p] = txt[p].replace('\n', ' ')
txt[p] = alpha_strip.sub('', txt[p])
# blacklist holds words that occur more than 100 times and need not be counted
# whitelist is a dictionary that holds the word as the key and a list of page numbers as values
blacklist = []
whitelist = {}
for n, p in enumerate(txt, start=1):
# split pages into words
working_string = p.split(' ')
for w in working_string:
# check if word is in blacklist
if w.lower() in blacklist:
continue
#check if word is in whitelist; if yes add to it, if too many added remove and add to blacklist
elif w.lower() in whitelist:
# print(w.lower(), n)
whitelist[w.lower()].append(n)
if len(whitelist[w.lower()]) > 100:
blacklist.append(w.lower())
del whitelist[w.lower()]
# if not in whitelist, add to whitelist
else:
whitelist[w.lower()] = [n]
# print result
for i in sorted(whitelist):
print(i, whitelist[i]) |
e6deb9da2c71fc5474e85b1fc19b40c1d1796d0f | DayGitH/Python-Challenges | /DailyProgrammer/DP20150213C.py | 6,309 | 3.546875 | 4 | """
[2015-02-13] Challenge #201 [Hard] Mission Improbable
https://www.reddit.com/r/dailyprogrammer/comments/2vs1c6/20150213_challenge_201_hard_mission_improbable/
# **(Hard)**: Mission Improbable
Imagine a scenario involving one event - let's call it event A. Now, this event can either happen, or it can not
happen. This event could be getting heads on a coin flip, winning the lottery, you name it - as long as it has a 'true'
state and a 'false' state, it's an event.
Now, the probability of event A happening, or the probability of event A not happening, is 100% - it must either happen
or not happen, as there isn't any other choice! We can represent probabilities as a fraction of 1, so a probability of
100% is, well, 1. (A probability of 50% would be 0.5, 31% would be 0.31, etc.) This is an important observation to make
- the sum of the probabilities of *all the possible outcomes* must be 1. The probability of getting a head on a fair
coin flip is one half - 0.5. The probability of not getting a head (ie. getting a tail) is one half, 0.5, also. Hence,
the sum of all the probabilities in the scenario is 0.5+0.5=1. This 'sum event' is called the sample space, or S.
We can represent this one-event scenario with a diagram, [like this](http://i.imgur.com/qwmIb6E.png). Each coloured
blob is one outcome; all the outcomes are in S, and thus are all are in the big circle, representing S. The red blob
represents the outcome of A *not* occurring, and the green blob represents the outcome of A occurring.
Now, let's [introduce some numbers](http://i.imgur.com/avK6iUQ.png). Let's say the probability of A occurring is 0.6
(60%). As A occurring, and A not occurring, are the only possible outcomes, then the probability of A not occurring
must be 40%, or 0.4. This type of reasoning lets us solve basic problems, [like this
one](http://i.imgur.com/buH6RQn.png). If the probability of A not occurring is 0.67, then what is the probability of A
occurring? Well, the probability of S is 1, and so 0.67 plus our unknown must sum to 1 - therefore, the probability of
A occurring is 1-0.67=**0.33**.
What about scenarios with more than one event? Look at [this diagram](http://i.imgur.com/xTxM2eV.png). This shows the
sample space with two events, A and B. I've put coloured blobs for three of the four possible outcomes - of course, the
fourth is in the empty region in A. Each region on the diagram is one possible outcome. Now, we come to something
important. [This region on the diagram](http://i.imgur.com/xi0MNZ6.png) is **NOT** representing A - it is representing
A **and not B**. [This region here](http://i.imgur.com/GJhGvs5.png) represents the probability of A as a whole - and,
as you can see, the probability of A occurring is the probability of A and B, plus the probability of A and *not* B -
in other words, the sum probability of all outcomes where A occurs.
Applying this additive rule lets us solve some more complex problems. [Here's a diagram representing Stan's journey to
work this morning](http://i.imgur.com/eyQnbyk.png). Stan needs to catch two buses - the driver of the first bus is a
grumpy old fellow and waits for hardly any time for Stan to get on; the driver of the second is much nicer, and waits
for Stan where he can. Of course, if Stan misses the first bus, then it's likely that he will miss the second bus, too.
We know that, on 85% of days (0.85), Stan gets to work on time. We also said before that the driver of bus 2 is nice,
and hence it's very rare to miss the second bus - the chance of getting on the first bus, and missing the second, is
tiny - 1% (0.01). Stan tells us to work out how often he misses the first bus but not the second bus, given that he
misses the second bus on 12% (0.12) of days.
Let's look at that last fact - the probability that Stan misses the second bus is 0.12. This means that the [sum of all
probabilities in this region on the diagram must be 0.12](http://i.imgur.com/p9XM9uo.png). We already know that the
probability of missing bus 2, but *not* missing bus 1 is 0.01. Hence, as there is only one other possible outcome
involving missing bus 2, the probability of missing *both* buses must be 0.11, as 0.11+0.01=0.12! Thus our diagram now
[looks like this](http://i.imgur.com/PqO8HI1.png). Now, out of the 4 possible outcomes in this scenario, we know three
of them. We also know that the total sum of the probabilities of the four outcomes must equal one (the sample space);
therefore, 0.85+0.01+0.11+**?**=1. This tells us that the probability of missing bus 1, but *not* missing bus 2 is
1-0.85-0.01-0.11=0.03. Therefore, we've solved Stan's problem. Your challenge today is, given a set of events and the
probabilities of certain outcomes occurring, find the probability of an unknown outcome - or say if not enough
information has been given.
# Input and Output
## Input Description
On the first line of input, you will be given a number **N**, and then the list of event names, like this:
3 A B
You will then be given **N** lines containing probabilities in this format:
A & !B: 0.03
Where the `&` indicates the left and right occur together, and the `!` indicates negation - ie. `A & !B` indicates that
event A occurs and event B doesn't.
Finally, on the last line, you will be given an outcome for which to find the probability of, like this:
!A & !B
Thus, an input set describing Stan and his buses would look like this (where B1 is missing bus 1, B2 is missing bus 2):
3 B1 B2
!B1 & B2: 0.01
!B1 & !B2: 0.85
B2: 0.12
B1 & !B2
**You may assume all probabilities are in increments of 1/100 - ie. 0.27, 0.9, 0.03, but not 0.33333333 or 0.0001.**
## Output Description
Output the probability of the given unknown - in the example above,
0.03
# Example I/O
## Input
[(Represents this scenario as a diagram)](http://i.imgur.com/720vIok.png)
6 A B C
B: 0.7
C: 0.27
A & B & !C: 0
A & C & !B: 0
A & !B & !C: 0.13
!A & !B & !C: 0.1
B & C
## Output
0.2
## Input
3 B1 B2
!B1 & B2: 0.01
!B1 & !B2: 0.85
B2: 0.12
B1 & !B2
## Output
0.03
## Input
1 A B
A & B: 0.5
A
## Output
Not enough information.
# Addendum
Now might be the time to look into Prolog.
"""
def main():
pass
if __name__ == "__main__":
main()
|
6413f86569da08a37374f72a6c330b1fd67ff02e | DayGitH/Python-Challenges | /DailyProgrammer/DP20170705B.py | 896 | 4.21875 | 4 | """
[2017-07-05] Challenge #322 [Intermediate] Largest Palindrome
https://www.reddit.com/r/dailyprogrammer/comments/6ldv3m/20170705_challenge_322_intermediate_largest/
# Description
Write a program that, given an integer input n, prints the largest integer that is a palindrome and has two factors
both of string length n.
# Input Description
An integer
# Output Description
The largest integer palindrome who has factors each with string length of the input.
# Sample Input:
1
2
# Sample Output:
9
9009
(9 has factors 3 and 3. 9009 has factors 99 and 91)
# Challenge inputs/outputs
3 => 906609
4 => 99000099
5 => 9966006699
6 => ?
# Credit
This challenge was suggested by /u/ruby-solve, many thanks! If you have a challenge idea, please share it in
/r/dailyprogrammer_ideas and there's a good chance we'll use it.
"""
def main():
pass
if __name__ == "__main__":
main()
|
8361a2e4b7a97bc2728ff6df895f0b77a184661d | DayGitH/Python-Challenges | /DailyProgrammer/DP20141031.py | 6,892 | 3.625 | 4 | """
[10/31/2014] Challenge #186 [Special] Code or Treat - Halloween 2014
https://www.reddit.com/r/dailyprogrammer/comments/2kwfqr/10312014_challenge_186_special_code_or_treat/
#Description:
Happy Halloween. For Today's challenge we will go off our typical path and do a special challenge posting. I have come
up with 2 challenges. One will be [Easy] the other [Intermediate]. They do have a Halloween theme and it is intended to
be a bit light hearted in our typical approach to challenges. Have fun :)
#[Easy] Bag Inventory:
##Description:
So to help out all the trick or treaters we need to develop a tool to help inventory their candy haul for the night.
You will be given a text file that contains a listing of every piece of candy in the bag. Your challenge is to develop
a solution to inventory the candy and print out a summary of how much candy you got.
You must answer these basic questions
* How many pieces of candy did you get
* How much of each type
* What percentage of total candy does that type occupy
##Input:
Use this gist listing as your text file to represent your bag of candy.
[Candy Bag Link] (https://gist.github.com/coderd00d/54215798871d0c356cfb)
##Output:
You must answer the basic questions. How you display it and present it we leave to the programmer to decide. Some
suggestions could be a text output. Perhaps you do a histogram or pie chart. Maybe show a real time tally as you go
through the bag counting the candy and display it as a gif for all to enjoy.
#[Intermediate] - The Coding Dead
##Description:
Zombie lore has been very popular in the recent years. We are entertained by the stories of the dead coming back to
life as a zombie and the struggle of human to survive the zombie horde. In Zombie lore it is common that if you are
bitten by a zombie you become a zombie. This behavior works much like a plague. The zombie grow in numbers and the
living must deal with them by usually do a fatal wound to the zombie's brain/spinal cord.
We will explore this plague of zombies by creating zombie simulator. This simulator will randomly populate a map and
have 3 types of entities: Zombies, Victims and hunters.
* Zombies -- The walking dead back to life. They will roam looking to bite victims to turn them into zombies.
* Victims -- Innocent humans who are not trained in Zombie lore and have no skills or knowledge to fight back.
* Hunters -- Trained humans in Zombie lore who seek out to destroy Zombies to save the planet.
##Simulation Map
Our simulation will run on a 20x20 Map. Each spot can occupy Either a Zombie, Victim, Hunter or be an empty space. You
need to develop a way to support this map and to be able to create the map by randomly placing a set amount of starting
Zombies, Victims or Hunters. Only 1 entity per a space.
##Input
You will feed your simulation 4 numbers. x y z t
* x - how many zombies to randomly spawn
* y - how many victims to randomly spawn
* z - how many hunters to randomly spawn.
* t - how many "ticks" of time to run the simulation
##Map Error Checking:
So on a 20x20 map you have 400 spots. If x+y+z > 400 you will return an error. You cannot create a map that holds more
than it can hold.
##Simulation
Our simulation will have a "tick". This is a unknown unit of time. But in this time actions occur as follows to define
our simulation.
* Movement
* Zombie slaying
* Bite
##Movement
Movement occurs for all our life forms. If the life forms try to move and the space is occupied they will just continue
to occupy their current location.
* Zombies -- will try to move 1 space. They will either move up, down, left or right. Zombies are not able to move
diagonal. They just cannot handle such a movement.
* Victims -- typically do not move. However, if they are next to a zombie (up, down, left, right or diagonal) they will
try to move 1 square. Note they might end up in a square next to the zombie again or a new zombie. The panic of
movement and being a "victim" does not mean they make the optimal move.
* Hunters - Will move to 1 new spot in any direction (up, down, left, right, diagonal) to seek and find a zombie to
destroy.
## Zombie Slaying
Once movement occurs if a hunter is next to in any direction (up, down, left, right, diagonal) to a zombie he will slay
a zombie. If the hunter is next to two zombies he will slay two zombies. However if the hunter is next to three or more
zombies he will only be able to slay two of them. Just not enough time to kill more than two. When you slay a zombie
you remove it off our map.
## Bite
Zombies will bite a non-zombie if they are (up, down, left, right) of a non-zombie. They will not be able to bite at a
diagonal to represent the simple mind of the zombie. Victims or Hunters can be bitten. Once bitten the Victim or Hunter
becomes a zombie. You will change them into a Zombie.
## Data
We want to gather data during the simulation. Each time an entity changes spots in movement we record this distance by
entity.
* Zombie Stumble Units - number of spots zombies moved too
* Victim Flee Units - number of spots victims moved too
* Hunter Seek Units - number of spots hunters moved too.
We will maintain a population number. We will know our original population because we are given those numbers.
As time goes on we want to record the final population of all 3 entities. Also we want to record some basic events.
* Number of "Single" kills by hunter (killing only 1 zombie a turn)
* Number of "Double" kills by a hunter (killing 2 zombies a turn)
* Total zombies killed by Hunters
* Number of Victims bitten
* Number of Hunters bitten
* Total number of non-zombies bitten
## Output
The programmer should output at the end of the simulation a report of what happened.
* Output the x y z t values. So your starting populations and how many ticks the simulator ran
* Output all the Data above in the data
* You will show the final population counts of your entities.
## Final
With all this data we can compute a decay rate. Either the zombie population is decaying or the non-zombie population
is decaying. If the decay difference is within 5 then the population is a balance. So for example if 100 zombies are
killed but 95 are created it is a balance. (The difference between killed zombies and bites was 5 or less) However if
the decay difference is more than 5 in favor of bites the Zombies Win. If the decay difference is more than 5 in favor
of the Hunters then the Humans win.
You will decide who wins the simulation. Humans, Zombies or a tie.
## Now have fun
Using different x y z and t values try to see if you can get a balance For a total population (x + y + z) for the
following numbers of (x + y + z)
* 100
* 200
* 300
# Message From the Mods
From the Moderator Staff of /r/dailyprogrammer enjoy your 2014 Halloween :) Thank you for your participation in our
subreddit.
"""
def main():
pass
if __name__ == "__main__":
main()
|
d3028bc45866eafad2bc8500fb8454c0ee67a798 | DayGitH/Python-Challenges | /DailyProgrammer/DP20130308C.py | 2,818 | 3.5 | 4 | """
[03/08/13] Challenge #120 [Hard] Bytelandian Exchange 3
https://www.reddit.com/r/dailyprogrammer/comments/19whtk/030813_challenge_120_hard_bytelandian_exchange_3/
# [](#HardIcon) *(Hard)*: Bytelandian Exchange 3
Bytelandian Currency is coins with positive integers on them. (Don't worry about 0-valued coins because they're useless
for this problem.) You have access to two peculiar money changing machines:
* Machine 1 takes one coin of any value N. It pays back 3 coins of the values N/2, N/3 and N/4, rounded down. For
example, if you insert a 19-valued coin, you get three coins worth 9, 6, and 4.
* Machine 2 takes two coins at once, one of any value N, and one of any positive value. It returns a single coin of
value N+1.
These two machines can be used together to get arbitrarily large amounts of money from a single coin, provided it's
worth enough. If you can change an N-valued coin into an N-valued coin *and* a 1-valued coin, you can repeat the
process to get arbitrarily many 1-valued coins. __What's the smallest N such that an N-valued coin can be changed into
an N-valued coin and a 1-valued coin?__
For instance, it can be done with a coin worth 897. Here's how. Use Machine 1 to convert it into coins worth 448, 299,
and 224. Through repeated applications of Machine 1, the 299-valued coin can be converted into 262 1-valued coins, and
the 224-valued coin can be converted into 188 1-valued coins. At this point you have a 448-valued coin and 450 1-valued
coins. By using Machine 2 449 times, you can make this into a 897-valued coin and a 1-valued coin. To summarize this
strategy:
* 897 -> 448 + 299 + 224 (Machine 1)
* 299 + 224 -> 450x1 (repeated Machine 1)
* 448 + 450x1 -> 897 + 1 (repeated Machine 2)
But of course, 897 is not the lowest coin value that lets you pull this trick off. Your task is to find the lowest such
value.
[Here is a python script that will verify the steps of a correct solution (will not verify that it's optimal,
though).](http://pastebin.com/JJuKJBLp)
*Author: Cosmologicon*
# Formal Inputs & Outputs
## Input Description
None
## Output Description
The lowest N such that an N-valued coin can be converted into an N-valued coin *and* a 1-valued coin.
# Sample Inputs & Outputs
## Sample Input
None
## Sample Output
None
# Challenge Input
None
## Challenge Input Solution
None
# Note
Please direct any questions about this challenge to /u/Cosmologicon
__Bonus:__ Now consider the case where Machine 1 is broken and will not give out any 1-valued coins (so for instance,
putting a 5-valued coin into Machine 1 gives you a 2-valued coin and nothing else). In this case, what's the smallest N
such that an N-valued coin can be converted into an N-valued coin *and* a 2-valued coin?
"""
def main():
pass
if __name__ == "__main__":
main()
|
20cf5b34e570d982ae6a87c47d62ddab00c2b011 | DayGitH/Python-Challenges | /DailyProgrammer/DP20130701A.py | 2,368 | 3.875 | 4 | """
[07/01/13] Challenge #131 [Easy] Who tests the tests?
https://www.reddit.com/r/dailyprogrammer/comments/1heozl/070113_challenge_131_easy_who_tests_the_tests/
# [](#EasyIcon) *(Easy)*: Who tests the tests?
[Unit Testing](http://en.wikipedia.org/wiki/Unit_testing) is one of the more basic, but effective, tools for [software
testing](http://en.wikipedia.org/wiki/Software_testing) / quality assurance. Your job, as an expert test-engineer, is
to double-check someone else's test data, and make sure that the expected output is indeed correct. The two functions
you are testing is string-reversal and string-to-upper functions.
For each line of input, there are three space-delimited values: the first being the test index (as either 0 or 1), then
the test input string, and finally the "expected" output. You must take the test input string, run it through your
implementation of the appropriate function based on the test index, and then finally compare it to the "expected"
output. If you are confident your code is correct and that the strings match, then the "expected" output is indeed
good! Otherwise, the "expected" output is bad (and thus invalid for unit-testing).
*Author: nint22*
# Formal Inputs & Outputs
## Input Description
You will be given an integer N on the first line of input: it represents the following N lines of input. For each line,
you will be given an integer T and then two strings A and B. If the integer T is zero (0), then you must reverse the
string A. If the integer T is one (1), then you must upper-case (capitalize) the entire string A. At the end of either
of these operations, you must test if the expected result (string B) and the result of the function (string A) match.
## Output Description
If string A, after the above described functions are executed, and B match, then print "Good test data". Else, print
"Mismatch! Bad test data". "Matching" is defined as two strings being letter-for-letter, equivalent case, and of the
same length.
# Sample Inputs & Outputs
## Sample Input
6
0 Car raC
0 Alpha AhplA
0 Discuss noissucsiD
1 Batman BATMAN
1 Graph GRAPH
1 One one
## Sample Output
Good test data
Mismatch! Bad test data
Mismatch! Bad test data
Good test data
Good test data
Mismatch! Bad test data
"""
def main():
pass
if __name__ == "__main__":
main()
|
72b14d6febd7390c2adb660e704e6c62276a45b1 | DayGitH/Python-Challenges | /ProjectEuler/pr0016.py | 204 | 3.8125 | 4 | """
2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 21000?
"""
number = 2**1000
sum = 0
for n in str(number):
sum += int(n)
print(sum) |
dda4acd237e4f4c44dcbd0febd58e09c71b83183 | DayGitH/Python-Challenges | /DailyProgrammer/20120430C.py | 1,368 | 4.09375 | 4 | """
The prime HP reached starting from a number , concatenating its prime factors, and repeating until a prime is reached.
If you have doubts, refer the article here [http://mathworld.wolfram.com/HomePrime.html]
write a function to calculate the HP of a given number.
Also write a function to compute the Euclid-Mullin sequence [http://mathworld.wolfram.com/Euclid-MullinSequence.html].
"""
import numpy as np
def is_prime(n):
"""https://stackoverflow.com/questions/15285534/isprime-function-for-python-language"""
if n == 2 or n == 3: return True
if n < 2 or n%2 == 0: return False
if n < 9: return True
if n%3 == 0: return False
r = int(n**0.5)
f = 5
while f <= r:
if n%f == 0: return False
if n%(f+2) == 0: return False
f +=6
return True
def factorize(n):
active_num = n
factors = []
n = 2
while active_num != 1:
if active_num % n == 0:
active_num /= n
factors.append(str(n))
else:
n += 1
return factors
def home_prime(n):
while not is_prime(n):
n = int(''.join(factorize(n)))
return n
def euclid_mullin(n):
e_m = []
for i in range(n):
e_m.append(int(factorize(np.prod(e_m)+1)[0]))
print(e_m)
return e_m
if __name__ == '__main__':
print(home_prime(5))
euclid_mullin(9) |
9843b352194d21f8a67d7de52ba0b2c59c27bc2f | DayGitH/Python-Challenges | /DailyProgrammer/DP20160916C.py | 2,259 | 4.25 | 4 | """
[2016-09-16] Challenge #283 [Hard] Guarding the Coast
https://www.reddit.com/r/dailyprogrammer/comments/5320ey/20160916_challenge_283_hard_guarding_the_coast/
# Description
Imagine you're in charge of the coast guard for your island nation, but you're on a budget. You have to minimize how
many boats, helicopters and crew members to adequately cover the coast. Each group is responsible for a square area of
coastline.
It turns out this has a mathematical relationship to some interesting mathematics. In fractal geometry, the
[Minkowski–Bouligand Dimension](https://en.wikipedia.org/wiki/Minkowski%E2%80%93Bouligand_dimension), or box counting
dimension, is a means of counting the fractal geometry of a set *S* in Euclidian space R^n. Less abstractly, imagine
the set *S* laid out in an evenly space grid. The box counting dimension would be the minimum number of square tiles
required to cover the set.
More realistically, when doing this counting you'll wind up with some partial tiles and have to overlap, and that's OK
- overlapping boxes are fine, gaps in coastal coverage are not. What you want to do is to minimize the number of tiles
overall. It's easy over estimate, it's another to minimize.
# Input Description
You'll be given two things: a tile size N representing the side of the square, and an ASCII art map showing you the
coastline to cover.
Example:
2
*****
* *
* *
* *
*****
# Output Description
Your program should emit the minimum number of tiles of that size needed to cover the boundary.
From the above example:
8
# Challenge Input
4
**
* **
* *
** *
* *
** *
* *
* *
** **
* *
** ***
* *
* *
** *
* **
** *
** *
* **
* **
* ***
** *
* *
** **
* ****
** ******
*********
"""
def main():
pass
if __name__ == "__main__":
main()
|
78237d17e529cdd02fe42dd409c705b22e255eb8 | DayGitH/Python-Challenges | /DailyProgrammer/20120403B.py | 1,081 | 4.46875 | 4 | """
Imagine you are given a function flip() that returns a random bit (0 or 1 with equal probability). Write a program that
uses flip to generate a random number in the range 0...N-1 such that each of the N numbers is generated with equal
probability. For instance, if your program is run with N = 6, then it will generate the number 0, 1, 2, 3, 4, or 5 with
equal probability.
N can be any integer >= 2.
Pseudocode is okay.
You're not allowed to use rand or anything that maintains state other than flip.
Thanks to Cosmologicon for posting this challenge to /r/dailyprogrammer_ideas!
"""
import random
import matplotlib.pyplot as plt
from bitarray import bitarray
def flip():
return random.getrandbits(1)
def binary_to_int(n):
out = 0
for bit in n:
out = (out << 1) | bit
return out
def randomize(a):
for n, i in enumerate(a):
a[n] = flip()
return a
number = 200
binary = bin(number)[2:]
a = len(binary) * bitarray('0')
while True:
a = randomize(a)
if binary_to_int(a) <= number:
break
print(binary_to_int(a))
|
f050174939af3edb52e8fa2e13b61909a7f469aa | DayGitH/Python-Challenges | /DailyProgrammer/DP20160406B.py | 2,394 | 3.84375 | 4 | """
[2016-04-06] Challenge #261 [Intermediate] rearranged magic squares
https://www.reddit.com/r/dailyprogrammer/comments/4dmm44/20160406_challenge_261_intermediate_rearranged/
# Description
An NxN magic square is an NxN grid of the numbers 1 through N^2 such that each row, column, and major diagonal adds up
to M = N(N^(2)+1)/2. [See this week's Easy problem for an
example.](https://www.reddit.com/r/dailyprogrammer/comments/4dccix/20160404_challenge_261_easy_verifying_3x3_magic/)
You will be given an NxN grid that is not a magic square, but whose rows can be rearranged to form a magic square. In
this case, rearranging the rows means to put the rows (horizontal lines of numbers) in a different order, but within
each row the numbers stay the same. So for instance, the top row can be swapped with the second row, but the numbers
within each row cannot be moved to a different position horizontally, and the numbers that are on the same row as each
other to begin with must remain on the same row as each other.
Write a function to find a magic square formed by rearranging the rows of the given grid.
There is more than one correct solution. Format your grid however you like. You can parse the program's input to get
the grid, but you don't have to.
# Example
15 14 1 4 12 6 9 7
12 6 9 7 => 2 11 8 13
2 11 8 13 15 14 1 4
5 3 16 10 5 3 16 10
# Inputs
[Challenge inputs](http://pastebin.com/tWzmKrJh)
Any technique is going to eventually run too slowly when the grid size gets too large, but you should be able to handle
8x8 in a reasonable amount of time (less than a few minutes). If you want more of a challenge, see how many of the
example inputs you can solve.
I've had pretty good success with just randomly rearranging the rows and checking the result. Of course, you can use a
"smarter" technique if you want, as long as it works!
# Optional bonus
(Warning: hard for 12x12 or larger!) Given a grid whose rows can be rearranged to form a magic square, give the
*number* of different ways this can be done. That is, how many of the N! orderings of the rows will result in a magic
square?
If you take on this challenge, include the result you get for as many of the [challenge input
grids](http://pastebin.com/tWzmKrJh) as you can, along with your code.
"""
def main():
pass
if __name__ == "__main__":
main()
|
e9e109a400f3da638ea1ba1e6a71e697f962ace3 | DayGitH/Python-Challenges | /DailyProgrammer/DP20121120B.py | 1,324 | 4.03125 | 4 | """
[11/20/2012] Challenge #113 [Intermediate] Text Markup
https://www.reddit.com/r/dailyprogrammer/comments/13hmz5/11202012_challenge_113_intermediate_text_markup/
**Description:**
Many technologies, notably user-edited websites, take a source text with a special type of mark-up and output HTML
code. As an example, Reddit uses a special formatting syntax to turn user texts into bulleted lists, web-links, quotes,
etc.
Your goal is to write a function that specifically implements the Reddit markup language, and returns all results in
appropriate HTML source-code. The actual HTML features you would like to implement formatting (i.e. using CSS bold vs.
the old <b> tag) is left up to you, though "modern-and-correct" output is highly desired!
[Reddit's markup description is defined here](http://www.reddit.com/help/commenting). You are required to implement all
9 types found on that page's "Posting" reference table.
**Formal Inputs & Outputs:**
*Input Description:*
String UserText - The source text to be parsed, which may include multiple lines of text.
*Output Description:*
You must print the HTML formatted output.
**Sample Inputs & Outputs:**
The string literal `*Test*` should print <b>Test</b> or <div style="font-weight:bold;">Test</div>
"""
def main():
pass
if __name__ == "__main__":
main()
|
0b541c06a55954a41a1cf02de616696c28d9abf8 | DayGitH/Python-Challenges | /DailyProgrammer/DP20121023B.py | 1,571 | 4.1875 | 4 | """
[10/23/2012] Challenge #106 [Intermediate] (Jugs)
https://www.reddit.com/r/dailyprogrammer/comments/11xjfd/10232012_challenge_106_intermediate_jugs/
There exists a problem for which you must get exactly 4 gallons of liquid, using only a 3 gallon jug and a 5 gallon
jug. You must fill, empty, and/or transfer liquid from either of the jugs to acquire exactly 4 gallons.
The solution to this particular problem is the following:
- Fill the 5 gallon jug
- Transfer from the 5 gallon jug to the 3 gallon jug, leaving 2 gallons in the 5 gallon jug and 3 gallons in the 3
gallon jug
- Empty the 3 gallon jug
- Transfer from the 5 gallon jug to the 3 gallon jug, leaving 0 gallons in the 5 gallon jug and 2 gallons in the 3
gallon jug
- Fill the 5 gallon jug
- Transfer from the 5 gallon jug to the 3 gallon jug, leaving 4 gallons in the 5 gallon jug and 3 gallons in the 3
gallon jug
- Empty the 3 gallon jug (optional)
The challenge will be to output a set of instructions to achieve an arbitrary final volume given 2 arbitrary sized
gallon jugs. Jugs should be sized in a whole number (integer) amount of gallons. The program must also determine if the
desired volume is impossible with this method (i.e. 2 - 4 gallon jugs to make 3 gallons). The program should be
deterministic, meaning that running with the same inputs always produces the same solution (preventing a random pouring
algorithm). The program should also consider outputting the most optimal set of instructions, but is not necessary.
"""
def main():
pass
if __name__ == "__main__":
main()
|
f4c2aa66b7f75d032477be09044bff09be73f24e | DayGitH/Python-Challenges | /DailyProgrammer/DP20150325B.py | 4,693 | 3.546875 | 4 | """
[2015-03-25] Challenge #207 [Intermediate] Bioinformatics 2: DNA Restriction Enzymes
https://www.reddit.com/r/dailyprogrammer/comments/307m27/20150325_challenge_207_intermediate/
Continuing with our bioinformatics theme today. If you like these sorts of problems, I encourage you to check out
Project Rosalind (their site seems back up): http://rosalind.info/
# Description
Restriction enzymes are DNA-cutting enzymes found in bacteria (and harvested from them for use). Because they cut
within the molecule, they are often called restriction endonucleases. In order to be able to sequence DNA, it is first
necessary to cut it into smaller fragments. For precise molecular biology work, what is needed is a way to cleave the
DNA molecule at a few specifically-located sites so that a small set of homogeneous fragments are produced. The tools
for this are the restriction endonucleases. The rarer the site it recognizes, the smaller the number of pieces produced
by a given restriction endonuclease.
For more information on how these enzymes work, including a great visualization of how they cut, have a look here:
http://users.rcn.com/jkimball.ma.ultranet/BiologyPages/R/RestrictionEnzymes.html
These enzymes can cleave the DNA at a site that leaves both strands the same length. This is called a "blunt" end
because of this and can be visualized like this:
5'-GG +CC-3'
3'-CC GG-5'
Other DNA restriction enzymes cleave the ends at different lengths, although it's symmetrical about the central axis.
These are called "sticky" ends, and here's a simple visualization of one of those cuts:
5'-ATCTGACT + GATGCGTATGCT-3'
3'-TAGACTGACTACG CATACGA-5'
In both cases the two strands are cut at a point of symmetry (the upper and lower strands are symmetrical if rotated).
Today your challenge is to write a program that can recognize the locations where various enzymes will cut DNA.
# Input
You'll be given a list of DNA restriction enzymes and their recognition site and where the cut occurs. The input will
be structured as enzyme name, if the enzyme makes a "sticky" or "blunt" end cut, the DNA recognition sequence and the
position of the cut marked with a caret ("\^"). For the sticky ends, you should assume the mirror image of the
complementary strand gets the same cut, leaving one of the strands to overhang (hence it's "sticky").
BamHI sticky G^GATCC
HaeIII blunt GG^CC
HindIII sticky A^AGCTT
Then you'll be given a DNA sequence and be asked to cut it with the listed enzymes. For sake of convenience, the DNA
sequence is broken into blocks of 10 bases at a time and in lengths of 6 blocks per row. You should merge these
together and drop the first column of digits.
This sequence was taken from the genome of *Enterobacteria phage phiX174 sensu lato*
http://www.genome.jp/dbget-bin/www_bget?refseq+NC_001422 and modified for this challenge.
1 gagttttatc gcttccatga cgcagaagtt aacactttcg gatatttctg atgagtcgaa
61 aaattatctt gataaagcag gaattactac tgcttgttta cgaattaaat cgaagtggac
121 tgctggcgga aaatgagaaa attcgaccta tccttgcgca gctcgagaag ctcttacttt
181 gcgacctttc gccatcaact aacgattctg tcaaaaactg acgcgttgga tgaggagaag
241 tggcttaata tgcttggcac gttcgtcaag gactggttta gatatgagtc acattttgtt
301 catggtagag attctcttgt tgacatttta aaagagcgtg gattactatc tgagtccgat
361 gctgttcaac cactaatagg taagaaatca tgagtcaagt tactgaacaa tccgtacgtt
421 tccagaccgc tttggcctct attaagctta ttcaggcttc tgccgttttg gatttaaccg
481 aagatgattt cgattttctg acgagtaaca aagtttggat ccctactgac cgctctcgtg
541 ctcgtcgctg cgttgaggct tgcgtttatg gtacgctgga ctttgtggga taccctcgct
601 ttcctgctcc tgttgagttt attgctgccg tcaaagctta ttatgttcat cccgtcaaca
661 ttcaaacggc ctgtctcatc atggaaggcg ctgaatttac ggaaaacatt attaatggcg
721 tcgagcgtcc ggttaaagcc gctgaattgt tcgcgtttac cttgcgtgta cgcgcaggaa
781 acactgacgt tcttactgac gcagaagaaa acgtgcgtca aaaattacgt gcggaaggag
841 tgatgtaatg tctaaaggta aaaaacgttc tggcgctcgc cctggtcgtc cgcagccgtt
# Output
Your program should emit the name of the enzyme, the cut positions for that enzyme, and the contextualized cut. For the
above the solution would be:
BamHI 517 agttt[g gatcc]ctactg
HaeIII 435 gcttt[gg cc]tctattaa
HaeIII 669 caaac[gg cc]tgtctcat
HindIII 444 ctatt[a agctt]attcag
HindIII 634 cgtca[a agctt]attatg
# Bonus
Write some code that identifies any and all symmetrical points along the DNA sequence where an enzyme (not just the
three listed) could cut. These should be even-length palindromes between 4 and 10 bases long.
# Notes
If you have your own idea for a challenge, submit it to /r/DailyProgrammer_Ideas, and there's a good chance we'll post
it.
"""
def main():
pass
if __name__ == "__main__":
main()
|
b268c2242ac7769abf8155f8299f3222452c706c | DayGitH/Python-Challenges | /DailyProgrammer/DP20120702A.py | 1,509 | 4.28125 | 4 | """
Before I get to today's problem, I'd just like to give a warm welcome to our two new moderators, nooodl and Steve132! We
decided to appoint two new moderators instead of just one, because rya11111 has decided to a bit of a break for a while.
I'd like to thank everyone who applied to be moderators, there were lots of excellent submissions, we will keep you in
mind for the next time. Both nooodl and Steve132 have contributed some excellent problems and solutions, and I have no
doubt that they will be excellent moderators.
Now, to today's problem! Good luck!
If a right angled triangle has three sides A, B and C (where C is the hypothenuse), the pythagorean theorem tells us
that A**2 + B**2 = C**2
When A, B and C are all integers, we say that they are a pythagorean triple. For instance, (3, 4, 5) is a pythagorean
triple because 3**2 + 4**2 = 5**2 .
When A + B + C is equal to 240, there are four possible pythagorean triples: (15, 112, 113), (40, 96, 104),
(48, 90, 102) and (60, 80, 100).
Write a program that finds all pythagorean triples where A + B + C = 504.
Edit: added example.
"""
def pyth_triples(n):
for a in range(n//2):
for b in range(a+1, n//2):
for c in range(b+1, n//2):
if a+b+c == n and (a**2) + (b**2) == (c**2):
print([a, b, c])
elif a+b+c > n:
break
if a+b > n:
break
def main():
pyth_triples(504)
if __name__ == "__main__":
main()
|
612ed23619b17daf6df385d2f5eb9a363eadabdc | DayGitH/Python-Challenges | /DailyProgrammer/DP20140714A.py | 1,387 | 4.09375 | 4 | """
[7/14/2014] Challenge #171 [Easy] Hex to 8x8 Bitmap
https://www.reddit.com/r/dailyprogrammer/comments/2ao99p/7142014_challenge_171_easy_hex_to_8x8_bitmap/
#Description:
Today we will be making some simple 8x8 bitmap pictures. You will be given 8 hex values that can be 0-255 in decimal
value (so 1 byte). Each value represents a row. So 8 rows of 8 bits so a 8x8 bitmap picture.
#Input:
8 Hex values.
##example:
18 3C 7E 7E 18 18 18 18
#Output:
A 8x8 picture that represents the values you read in.
For example say you got the hex value FF. This is 1111 1111 . "1" means the bitmap at that location is on and print
something. "0" means nothing is printed so put a space. 1111 1111 would output this row:
xxxxxxxx
if the next hex value is 81 it would be 1000 0001 in binary and so the 2nd row would output (with the first row)
xxxxxxxx
x x
##Example output based on example input:
xx
xxxx
xxxxxx
xxxxxx
xx
xx
xx
xx
#Challenge input:
Here are 4 pictures to process and display:
FF 81 BD A5 A5 BD 81 FF
AA 55 AA 55 AA 55 AA 55
3E 7F FC F8 F8 FC 7F 3E
93 93 93 F3 F3 93 93 93
#Output Character:
I used "x" but feel free to use any ASCII value you want. Heck if you want to display it using graphics, feel free to
be creative here.
"""
def main():
pass
if __name__ == "__main__":
main()
|
08e590ff030b1b2a50b3a0caadd086f4def3630c | DayGitH/Python-Challenges | /DailyProgrammer/20120611B.py | 2,005 | 4.40625 | 4 | """
You can use the reverse(N, A) procedure defined in today's easy problem [20120611A] to completely sort a list. For
instance, if we wanted to sort the list [2,5,4,3,1], you could execute the following series of reversals:
A = [2, 5, 4, 3, 1]
reverse(2, A) (A = [5, 2, 4, 3, 1])
reverse(5, A) (A = [1, 3, 4, 2, 5])
reverse(3, A) (A = [4, 3, 1, 2, 5])
reverse(4, A) (A = [2, 1, 3, 4, 5])
reverse(2, A) (A = [1, 2, 3, 4, 5])
And the list becomes completely sorted, with five calls to reverse(). You may notice that in this example, the list is
being built "from the back", i.e. first 5 is put in the correct place, then 4, then 3 and finally 2 and 1.
Let s(N) be a random number generator defined as follows:
s(0) = 123456789
s(N) = (22695477 * s(N-1) + 12345) mod 1073741824
Let A be the array of the first 10,000 values of this random number generator. The first three values of A are then
123456789, 752880530 and 826085747, and the last three values are 65237510, 921739127 and 926774748
Completely sort A using only the reverse(N, A) function.
"""
def s(n, sp):
if n == 0:
return 123456789
else:
return (22695477 * sp + 12345) % 1073741824
def reverse(n, a):
return a[:n][::-1] + a[n:]
def basic_revsort(a):
copy_a = a[:]
sort_loc = len(a)
count = 0
while copy_a:
num = max(copy_a)
copy_a.remove(num)
i = a.index(num)+1
if i == sort_loc:
pass
elif i == 0:
a = reverse(sort_loc, a)
count += 1
else:
a = reverse(i, a)
a = reverse(sort_loc, a)
count += 2
sort_loc -= 1
print(count)
return a
def main():
generate = 10000
result = -1
out = []
for i in range(generate):
result = s(i, result)
out.append(result)
# out = [2, 5, 4, 3, 1]
out = basic_revsort(out)
print(sorted(out))
print(out)
if __name__ == "__main__":
main()
|
e1bbe5b69b0a21c4ab1cc925835b0167ef8dcbda | DayGitH/Python-Challenges | /DailyProgrammer/DP20170915C.py | 3,041 | 3.890625 | 4 | """
[2017-09-15] Challenge #331 [Hard] Interactive Interpreter
https://www.reddit.com/r/dailyprogrammer/comments/7096nu/20170915_challenge_331_hard_interactive/
#Description
Make an interactive interpreter with 2 different capabilities
1. It should be able to take a mathematical string (fx "5 + 2") and return the result of it
2. It should be capable of assigning variables (fx "x = 5 + 2") store the value for the variable for later use and
return the value
3. Using assigned variables instead of numbers (fx "y = x * 2")
Variable names must start with a character a-z and can be continued by any alphanumeric character.
All variables will be numerical (can be either floats or integers), feel free to support arbitrarily large numbers.
The mathematical evaluator shall be capable of adding, subtracting, multiplying, dividing, exponents and handling
nested parenthesis.
exponents will be using ^ as symbol.
The usual order of mathematics apply, so PEMDAS shall be applied in evaluations.
**PLEASE** refrain from using your languages built in evaluators.
#Input description
A list of strings such as (divided by \n):
5 + 5
(2 * 5 + 1) / 10
x = 1 / 2
y = x * 2
Assume all inputs to be written properly, i.e. no undefined variables or wrong placed parenthesis
Assume all whitespace as negligible so "1 2" and "12" can be assumed the same
#Output description
Output for each input line, fx from above would be:
10
1.1
0.5
1
#Challenge input
9 + 10
(2 * 5 + 1) / 10
x = 1 / 2
y = x * 2
(x + 2) * (y * (5 - 100))
z = 5*-3.14
2.6^(2 + 3/2) * (2-z)
#Challenge output
19
1.1
0.5
1
-237.5
-15.7
501.625937332
#Bonus
##Bonus 1 - Functions
Variables are nice, but it's all quite limited until we got functions
functions doesnt eval on declaration, so just make a newline as output from a funtion declaration
functions and variables can exist with the same name.
functions either look like 'func()' or 'func(arg1, arg2, arg3)' with any number of arguments needed
arguments given for functions are only used within the function themself and overwrites any variable with the given
name.
a = 2
func(a) = a
func(1) will return 1
func(1) + a will return 3
if the function requires no arguments
###Bonus input
a = 10
a() = 2
a() + a
avg(a, b) = (a + b) / 2
x = avg(69, 96)
avg(x, avg(a(), a)) + a
###Bonus output
10
12
82.5
54.25
##Bonus 2 - Errors
Handle errors 'gracefully'
Errors include but are likely not limited to:
1. Undefined variables (fx "pi * 2", pi has never been defined)
2. Wrong variable naming
3. parenthesis placed wrongly (too many open, too many closing, closing when none open etc)
4. dividing by 0
5. Functions calling itself or calling functions that end up calling itself
Return error description as output if an error occurred
#Extra
If you have any challenges, please share it at /r/dailyprogrammer_ideas!
"""
def main():
pass
if __name__ == "__main__":
main()
|
8be851749005732519c82b72d3b7796187b59edc | DayGitH/Python-Challenges | /DailyProgrammer/DP20160408C.py | 2,212 | 4.15625 | 4 | """
[2016-04-08] Challenge #261 [Hard] magic square dominoes
https://www.reddit.com/r/dailyprogrammer/comments/4dwk7b/20160408_challenge_261_hard_magic_square_dominoes/
# Description
An NxN magic square is an NxN grid of the numbers 1 through N^2 such that each row, column, and major diagonal adds up
to M = N(N^(2)+1)/2. [See this week's Easy problem for an
example.](https://www.reddit.com/r/dailyprogrammer/comments/4dccix/20160404_challenge_261_easy_verifying_3x3_magic/)
For some even N, you will be given the numbers 1 through N^2 as N^(2)/2 pairs of numbers. You must produce an NxN magic
square using the pairs of numbers like dominoes covering a grid. That is, your output is an NxN magic square such that,
for each pair of numbers in the input, the two numbers in the pair are adjacent, either vertically or horizontally. The
numbers can be swapped so that either one is on the top or left.
For the input provided, there is guaranteed to be at least one magic square that can be formed this way. (In fact there
must be at least eight such magic squares, given reflection and rotation.)
Format the grid and input it into your function however you like.
# Efficiency
An acceptable solution to this problem must be significantly faster than brute force. (This is Hard, after all.) You
don't need to get the optimal solution, but you should run your program to completion on at least one challenge input
before submitting. Post your output for one of the challenge inputs along with your code (unless you're stuck and
asking for help).
Aim to finish one of the three 4x4 challenge inputs within a few minutes (my Python program takes about 11 seconds for
all three). I have no idea how feasible the larger ones are. I started my program on a 6x6 input about 10 hours ago and
it hasn't finished. But I'm guessing someone here will be more clever than me, so I generated inputs up to 16x16.
Good luck!
# Example input
1 9
2 10
3 6
4 14
5 11
7 15
8 16
12 13
# Example output
9 4 14 7
1 12 6 15
16 13 3 2
8 5 11 10
# Challenge inputs
[Challenge inputs](http://pastebin.com/6dkYxvrM)
"""
def main():
pass
if __name__ == "__main__":
main()
|
ee03cfef4f096a1fd5b906914fdf0f20de7ca636 | DayGitH/Python-Challenges | /DailyProgrammer/DP20140512A.py | 4,159 | 3.515625 | 4 | """
[5/12/2014] Challenge #162 [Easy] Novel Compression, pt. 1: Unpacking the Data
https://www.reddit.com/r/dailyprogrammer/comments/25clki/5122014_challenge_162_easy_novel_compression_pt_1/
# [](#EasyIcon) _(Easy)_: Novel Compression, pt. 1: Unpacking the Data
Welcome to this week's Theme Week. We're going to be creating our very own basic compression format for short novels or
writing. This format will probably not be practical for actual use, but may serve as a rudimentary introduction to how
data compression works. As a side task, it is advised to use structured programming techniques, so your program is easy
to extend, modify and maintain later on (ie. later this week.) To keep in line with our Easy-Intermediate-Hard trend,
our first step will be to write the **decompresser**.
The basic idea of this compression scheme will be the dictionary system. Words used in the data will be put into a
dictionary, so instead of repeating phrases over and over again, you can just repeat a number instead, thus saving
space. Also, because this system is based around written text, it will be specifically designed to handle sentences and
punctuation, and will not be geared to handle binary data.
# Formal Inputs and Outputs
## Input Description
The first section of the input we are going to receive will be the dictionary. This dictionary is just a list of words
present in the text we're decompressing. The first line of input will be a number **N** representing how many entries
the dictionary has. Following from that will be a list of **N** words, on separate lines. This will be our simple
dictionary. After this will be the data.
## Data Format
The pre-compressed data will be split up into human-readable 'chunks', representing one little segment of the output.
In a practical compression system, they will be represented by a few bytes rather than text, but doing it this way
makes it easier to write. Our chunks will follow 7 simple rules:
* If the chunk is just a number (eg. `37`), word number 37 from the dictionary (zero-indexed, so 0 is the 1st word) is
printed **lower-case**.
* If the chunk is a number followed by a caret (eg. `37^`), then word 37 from the dictionary will be printed
lower-case, **with the first letter capitalised**.
* If the chunk is a number followed by an exclamation point (eg. `37!`), then word 37 from the dictionary will be
printed **upper-case**.
* If it's a hyphen (`-`), then instead of putting a space in-between the previous and next words, put a hyphen instead.
* If it's any of the following symbols: `. , ? ! ; :`, then put that symbol at the end of the previous outputted word.
* If it's a letter `R` (upper or lower), print a new line.
* If it's a letter `E` (upper or lower), the end of input has been reached.
Remember, this is just for basic text, so not all possible inputs can be compressed. Ignore any other whitespace, like
tabs or newlines, in the input.
**Note**: All words will be in the Latin alphabet.
## Example Data
Therefore, if our dictionary consists of the following:
is
my
hello
name
stan
And we are given the following chunks:
2! ! R 1^ 3 0 4^ . E
Then the output text is:
HELLO!
My name is Stan.
Words are always separated by spaces unless they're hyphenated.
## Output Description
Print the resultant decompressed data from your decompression algorithm, using the rules described above.
# Challenge
## Challenge Input
20
i
do
house
with
mouse
in
not
like
them
ham
a
anywhere
green
eggs
and
here
or
there
sam
am
0^ 1 6 7 8 5 10 2 . R
0^ 1 6 7 8 3 10 4 . R
0^ 1 6 7 8 15 16 17 . R
0^ 1 6 7 8 11 . R
0^ 1 6 7 12 13 14 9 . R
0^ 1 6 7 8 , 18^ - 0^ - 19 . R E
(Line breaks added in data for clarity and ease of testing.)
## Expected Challenge Output
I do not like them in a house.
I do not like them with a mouse.
I do not like them here or there.
I do not like them anywhere.
I do not like green eggs and ham.
I do not like them, Sam-I-am.
"""
def main():
pass
if __name__ == "__main__":
main()
|
d9e6142a29f8024d9e90061aa3adbe9348fe809d | DayGitH/Python-Challenges | /DailyProgrammer/DP20120927C.py | 1,072 | 3.640625 | 4 | """
[9/27/2012] Challenge #101 [difficult] (Boolean Minimization)
https://www.reddit.com/r/dailyprogrammer/comments/10lbjo/9272012_challenge_101_difficult_boolean/
For difficult 101, I thought I'd do something with binary in it.
Write a program that reads in a file containing 2^n 0s and 1s as ascii characters. You will have to solve for N given
the number of 0s and 1s in the file,
as it will not be given in the file. These 0s and 1s are to be interpreted as the outputs of a truth table in N
variables.
Given this truth table, output a minimal boolean expression of the function in some form. (
[Hint1](http://en.wikipedia.org/wiki/Quine%E2%80%93McCluskey_algorithm),
[hint2](http://en.wikipedia.org/wiki/Karnaugh_map))
For example, one implementation could read in this input file
0000010111111110
This is a 4-variable boolean function with the given truth table. The program could minimize the formula, and could
output
f(abcd)=ac'+ab'+bcd'
or
f(0123)=02'+01'+123'
"""
def main():
pass
if __name__ == "__main__":
main()
|
245e17b2a3818b720d4b3add92f1a61fa6520148 | DayGitH/Python-Challenges | /DailyProgrammer/DP20140905C.py | 1,723 | 3.6875 | 4 | """
[9/05/2014] Challenge #178 [Hard] Regular Expression Fractals
https://www.reddit.com/r/dailyprogrammer/comments/2fkh8u/9052014_challenge_178_hard_regular_expression/
#Description:
For today's challenge you will be generating fractal images from regular expressions. This album describes visually how
it works:
* [https://imgur.com/a/QWMGi]
For the challenge you don't need to worry about color, just inclusion in the set selected by the regular expression.
Also, don't implicitly wrap the regexp in \^...$. This removes the need to use .* all the time.
#Input:
On standard input you will receive two lines. The first line is an integer n that defines the size of the output image
(nxn). This number will be a power of 2 (8, 16, 32, 64, 128, etc.).
The second line will be a regular expression with literals limited to the digits 1-4. That means you don't need to
worry about whitespace.
#Output:
Output a binary image of the regexp fractal according to the specification. You could print this out in the terminal
with characters or you could produce an image file. Be creative! Feel free to share your outputs along with your
submission.
#Example Input & Output:
##Input Example 1:
256
[13][24][^1][^2][^3][^4]
##Output Example 1:
* [http://i.imgur.com/zhSr365.png]
## Input Example 2 (Bracktracing) :
256
(.)\1..\1
## Output Example 2:
* [http://i.imgur.com/iLu7Pq4.png]
# Extra Challenge:
Add color based on the length of each capture group.
#Challenge Credit:
Huge thanks to /u/skeeto for [his idea posted on our idea subreddit]
(http://www.reddit.com/r/dailyprogrammer_ideas/comments/24ykjs/intermediatehard_regexp_fractals/)
"""
def main():
pass
if __name__ == "__main__":
main()
|
0b0a585867ad3f4081fb6734d314797ad4dfe6e3 | DayGitH/Python-Challenges | /DailyProgrammer/20120310A.py | 363 | 4.1875 | 4 | """
Write a program that will compare two lists, and append any elements in the second list that doesn't exist in the first.
input: ["a","b","c",1,4,], ["a", "x", 34, "4"]
output: ["a", "b", "c",1,4,"x",34, "4"]
"""
inp1 = ["a","b","c",1,4,]
inp2 = ["a", "x", 34, "4"]
final = inp1[:]
for a in inp2:
if a not in final:
final.append(a)
print(final) |
9d08436fd87235a0f4682b3c1d62897fcd53bb30 | DayGitH/Python-Challenges | /DailyProgrammer/DP20140602A.py | 4,494 | 3.578125 | 4 | """
[6/2/2014] Challenge #165 [Easy] ASCII Game of Life
https://www.reddit.com/r/dailyprogrammer/comments/271xyp/622014_challenge_165_easy_ascii_game_of_life/
# [](#EasyIcon) _(Easy)_: ASCII Game of Life
Hello people. Sorry for submitting this early, but I have exams this week and the next so I'll have to submit these
challenges a little bit early - I'm sure that's not an issue though! Welcome to June, and it's time for a run of
similarly themed challenges - all of them will be based on ASCII data. Not too dissimilar to [this
challenge](http://www.reddit.com/r/dailyprogrammer/comments/236va2/4162014_challenge_158_intermediate_part_1_the/) from
a while ago.
This first challenge is based on a game (the mathematical variety - not quite as fun!) called [Conway's Game of
Life](http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life). This is called a cellular automaton. This means it is
based on a 'playing field' of sorts, made up of lots of little cells or spaces. For Conway's game of life, the grid is
square - but other shapes like hexagonal ones could potentially exist too. Each cell can have a value - in this case,
on or off - and for each 'iteration' or loop of the game, the value of each cell will change depending on the other
cells around it. This might sound confusing at first, but looks easier when you break it down a bit.
* A cell's "neighbours" are the 8 cells around it.
* If a cell is 'off' but exactly 3 of its neighbours are on, that cell will also turn on - like reproduction.
* If a cell is 'on' but less than two of its neighbours are on, it will die out - like underpopulation.
* If a cell is 'on' but more than three of its neighbours are on, it will die out - like overcrowding.
Fairly simple, right? This might sound boring, but it can generate fairly complex patterns - [this one, for
example](http://upload.wikimedia.org/wikipedia/commons/e/e5/Gospers_glider_gun.gif), is called the Gosper Glider Gun
and is designed in such a way that it generates little patterns that fly away from it. There are other examples of such
patterns, like ones which grow indefinitely.
Your challenge is, given an initial 'state' of 'on' and 'off' cells, and a number, simulate that many steps of the Game
of Life.
# Formal Inputs and Outputs
## Input Description
You will be given a number **N**, and then two more numbers **X** and **Y**. After that you will be given a textual
ASCII grid of 'on' and 'off' states that is **X** cells wide and **Y** cells tall. On the grid, a period or full-stop
`.` will represent 'off', and a hash sign `#` will represent 'on'.
The grid that you are using must 'wrap around'. That means, if something goes off the bottom of the playing field, then
it will wrap around to the top, like this: http://upload.wikimedia.org/wikipedia/en/d/d1/Long_gun.gif See how those
cells act like the top and bottom, and the left and right of the field are joined up? In other words, the neighbours of
a cell can look like this - where the lines coming out are the neighbours:
#-...- ...... ../|\.
|\.../ ...... ......
...... |/...\ ......
...... #-...- ......
...... |\.../ ..\|/.
|/...\ ...... ..-#-.
## Output Description
Using that starting state, simulate **N** iterations of Conway's Game of Life. Print the final state in the same format
as above - `.` is off and `#` is on.
# Sample Inputs & Output
## Sample Input
7 10 10
..........
..........
..#.......
...#......
.###......
..........
..........
..........
..........
..........
## Sample Output
..........
..........
..........
..........
...#......
....##....
...##.....
..........
..........
..........
# Challenge
## Challenge Input
32 17 17
.................
.................
....###...###....
.................
..#....#.#....#..
..#....#.#....#..
..#....#.#....#..
....###...###....
.................
....###...###....
..#....#.#....#..
..#....#.#....#..
..#....#.#....#..
.................
....###...###....
.................
.................
(just for laughs, see how the output changes when you change **N**. Cool, eh?)
# Notes
To test your program, use one of the many online simulation programs. There are plenty written in JavaScript you can
get at with a Google search (or Bing, if you'd prefer. I wouldn't.)
"""
def main():
pass
if __name__ == "__main__":
main()
|
bec41056bd304f919fda37f71847a03c7e963d1a | DayGitH/Python-Challenges | /DailyProgrammer/20120509C.py | 2,551 | 3.734375 | 4 | """
T9 Spelling: The Latin alphabet contains 26 characters and telephones only have ten digits on the keypad. We would like
to make it easier to write a message to your friend using a sequence of keypresses to indicate the desired characters.
The letters are mapped onto the digits as 2=ABC, 3=DEF, 4=GHI, 5=JKL, 6=MNO, 7=PQRS, 8=TUV, 9=WXYZ. To insert the
character B for instance, the program would press 22. In order to insert two characters in sequence from the same key,
the user must pause before pressing the key a second time. The space character should be printed to indicate a pause.
For example "2 2? indicates AA whereas "22? indicates B. Each message will consist of only lowercase characters a-z and
space characters. Pressing zero emits a space. For instance, the message "hi" is encoded as "44 444?, "yes" is encoded
as "999337777?, "foo bar" (note two spaces) is encoded as "333666 6660022 2777?, and "hello world" is encoded as
"4433555 555666096667775553?.
This challenge has been taken from Google Code Jam Qualification Round Africa 2010
[http://code.google.com/codejam/contest/dashboard?c=351101#s=p2] ... Please use the link for clarifications. Thank You
"""
import re
T9_dict = {'2': 'a', '22': 'b', '222': 'c',
'3': 'd', '33': 'e', '333': 'f',
'4': 'g', '44': 'h', '444': 'i',
'5': 'j', '55': 'k', '555': 'l',
'6': 'm', '66': 'n', '666': 'o',
'7': 'p', '77': 'q', '777': 'r', '7777': 's',
'8': 't', '88': 'u', '888': 'v',
'9': 'w', '99': 'x', '999': 'y', '9999': 'z'}
"""
Inverse dictionary creator from https://stackoverflow.com/questions/2568673/inverse-dictionary-lookup-python
"""
T9_dict2 = {v: k for k, v in T9_dict.items()}
def splitter(inp):
res = []
inp = inp.split(' ')
for i in inp:
res += [m.group(0) for m in re.finditer(r"(\d)\1*", i)]
return res
def decoder(l):
res = ''
for i in l:
if '0' in i:
res += ' '
else:
res += T9_dict[i]
return res
def encoder(str):
res = ''
hold = ''
for i in str:
if i == ' ':
res += '0'
else:
if hold in T9_dict2[i]:
res += ' '
res += T9_dict2[i]
hold = res[-1]
return res.strip()
def main():
# inp = input('T9 input: ') #
inp = '4433555 555666096667775553'
s = splitter(inp)
t = decoder(s)
print(t)
inp = 'hello world'
w = encoder(inp)
print(w)
if __name__ == "__main__":
main()
|
6bfd5474c2198120894dafdbd17ee6ac8a063a51 | DayGitH/Python-Challenges | /ProjectEuler/pr0025.py | 582 | 3.75 | 4 | """
The Fibonacci sequence is defined by the recurrence relation:
F(n) = F(n−1) + F(n−2), where F(1) = 1 and F(2) = 1.
Hence the first 12 terms will be:
F(1) = 1
F(2) = 1
F(3) = 2
F(4) = 3
F(5) = 5
F(6) = 8
F(7) = 13
F(8) = 21
F(9) = 34
F(10) = 55
F(11) = 89
F(12) = 144
The 12th term, F(12), is the first term to contain three digits.
What is the first term in the Fibonacci sequence to contain 1000 digits?
"""
n=3
toggle = True
a = 1
b = 1
c = 1
while toggle:
a, b = b, a + b
if len(str(b)) == 1000:
toggle = False
print(n,len(str(b)),b)
n += 1
|
280830e249c6aa473cc2e635872ced65a46b687b | DayGitH/Python-Challenges | /DailyProgrammer/DP20140606C.py | 9,427 | 3.6875 | 4 | """
[6/6/2014] Challenge #165 [Hard] Simulated Ecology - The Forest
https://www.reddit.com/r/dailyprogrammer/comments/27h53e/662014_challenge_165_hard_simulated_ecology_the/
#Description:
The study of balance is interesting. Take for example a forest. Forests are very complex eco-systems with lots of
things happening. For this challenge we will
simulate a virtual forest and watch over simulated time the effects of a forest. We will see trees grow and be
harvested. We will see the impact of
industry upon the forest and watch as the wild life "fights" back.
For this simulated forest we will be dealing with 3 aspects.
* Trees which can be a Sapling, Tree or Elder Tree.
* Lumberjacks (He chops down down trees, he eats his lunch and goes to the Lava-try)
* Bears (He maws the lumberjacks who smells like pancakes)
##Cycle of time:
The simulation will simulate by months. You will progessive forward in time with a "tick". Each "tick" represents a
month. Every 12 "ticks" represents a year.
Our forest will change and be in constant change. We will record the progress of our forest and analyze what happens to
it.
##Forest:
The forest will be a two dimensional forest. We will require an input of N to represent the size of the forest in a
grid that is N x N in size.
At each location you can hold Trees, Bears or Lumberjacks. They can occupy the same spot but often events occur when
they occupy the same spot.
Our forest will be spawned randomly based on the size. For example if your value of N = 10. You will have a 10 by 10
forest and 100 spots.
10% of the Forest will hold a Lumberjack in 10 random spots. (using our 100 spot forest this should be 10
lumberjacks)
50% of the Forest will hold Trees (Trees can be one of 3 kinds and will start off as the middle one of "Tree") in
random spots.
2% of the Forest will hold Bears.
How you get the size of the forest is up to you. Either users enter it in, read it from a file, pass by argument or
hard coded. Your choice. But you have
to spawn the initial forest with the above percentages. I would recommend keeping N like 5 or higher. Small Forests are
not much fun.
##Events:
During the simulation there will be events. The events occur based on some logic which I will explain below. The events
essentially are the spawning of
new Trees, Lumberjacks, Bears or the decay of Trees, Lumberjacks and Bears. I will detail the events below in each
description of the 3 elements of our forest.
## Trees:
Every month a Tree has a 10% chance to spawn a new "Sapling". In a random open space adjacent to a Tree you have a 10%
chance to create a "Sapling".
For example a Tree in the middle of the forest has 8 other spots around it. One of these if they do not have a type of
Tree in it will create a "Sapling".
After 12 months of being in existence a "Sapling" will be upgrade to a "Tree". A "Sapling" cannot spawn other trees
until it has matured into a "Tree".
Once a "Sapling" becomes a tree it can spawn other new "Saplings". At this point once a "Sapling" matures into a "Tree"
it exists and matures. When a "Tree"
has been around for 120 months (10 years) it will become an "Elder Tree".
Elder Trees have a 20% chance to spawn a new "Sapling" instead of 10%.
If there are no open adjacent spots to a Tree or Elder Tree it will not spawn any new Trees.
## Lumberjacks:
They cut down trees, they skip and jump they like to press wild flowers.
Lumberjacks each month will wander. They will move up to 3 times to a randomly picked spot that is adjacent in any
direction. So for example a Lumberjack in the middle of your grid has
8 spots to move to. He will wander to a random spot. Then again. And finally for a third time.
When the lumberjack moves if he encounters a Tree (not a sapling) he will stop and his wandering for that month comes
to an end.
He will then harvest the Tree for lumber. Remove the tree. Gain 1 piece of lumber. Lumberjacks will not harvest
"Sapling". They will harvest an Elder Tree.
Elder Trees are worth 2 pieces of lumber.
Every 12 months the amount of lumber harvested is compared to the number of lumberjacks in the forest. If the lumber
collected equals or exceeds the amount of lumberjacks
in the forest a new lumberjack is hired and randomly spawned in the forest. Actually a math formula is used to
determine if we hire 1 or many lumberjacks. We hire a number
of new lumberjacks based on lumber gathered. Let us say you have 10 lumberjacks. If you harvest 10-19 pieces of lumber
you would hire 1 lumberjack. But if you harvest 20-29
pieces of lumber you would hire 2 lumberjacks. If you harvest 30-39 you would gain 3 lumberjacks. And so forth.
However if after a 12 month span the amount of lumber collected is below the number of lumberjacks then a lumberjack is
let go to save money and 1 random lumberjack
is removed from the forest. However you will never reduce your Lumberjack labor force below 0.
## Bears:
They wander the forest much like a lumberjack. Instead of 3 spaces a Bear will roam up to 5 spaces. If a bear comes
across a Lumberjack he will stop his wandering
for the month. (For example after 2 moves the bear lands on a space with a lumberjack he will not make any more moves
for this month)
Lumberjacks smell like pancakes. Bears love pancakes. Therefore the Bear will unfortunately maw and hurt the
lumberjack. The lumberjack will be removed from the
forest (He will go home and shop on wednesdays and have buttered scones for tea).
We will track this as a "Maw" accident. During the course of 12 months if there 0 "Maw" accidents then the Bear
population will increase by 1.
If however there are any "Maw" accidents the Lumberjacks will hire a Zoo to trap and take a Bear away. Remove 1 random
Bear. Note that if your Bear population reaches
0 bears then there will be no "Maw" accidents in the next year and so you will spawn 1 new Bear next year.
If there is only 1 lumberjack in the forest and he gets Maw'd. He will be sent home. But a new one will be hired
immediately and respawned somewhere else in the forest.
The lumberjack population will not drop below 1.
## Time:
The simulation occurs for 4800 months (400 years). Or until the following condition occur.
* You have 0 Trees left in the forest. So no Saplings, Trees or Elder Trees exist.
#Output:
Every month you will print out a log of spawn or decay events. If nothing happens then nothing is logged.
Example:
Month [0001]: [3] pieces of lumber harvested by Lumberjacks.
Month [0001]: [10] new Saplings Created.
Month [0002]: [2] pieces of lumber harvested by Lumberjacks.
Month [0002]: [9] new Saplings Created.
Month [0003]: [1] Lumberjack was Maw'd by a bear.
Month [0120]: [10] Trees become Elder Trees
Every year you will print out a log of events for yearly events:
Year [001]: Forest has 30 Trees, 20 Saplings, 1 Elder Tree, 9 Lumberjacks and 2 Bears.
Year [001]: 1 Bear captured by Zoo.
Year [001]: 9 pieces of lumber harvested 1 new Lumberjack hired.
Year [002]: Forest has 50 Trees, 25 Saplings, 2 Elder Tree, 10 Lumberjacks and 1 Bears.
Year [002]: 1 new Bear added.
Year [003]: Forest has 100 Trees, 99 Saplings, 10 Elder Tree, 1 Lumberjacks, and 0 Bears.
Year [003]: 1 new Bear added.
Year [003]: 3 Pieces of lumber harvested 3 new Lumberjacks hired.
#Optional Output 1:
At the end of the simulation you can bring out an ASCII graph showing the yearly populations of Bears, Trees,
Lumberjacks and open space (BTL Graph)
I recommend 50 Spots and each spot = 2%.
Example:
year 1: [BTTTTTTTTTTTTTTTTTTTTLLL______________________]
year 2: [BBTTTTTTTTTTTTTTTTTTTLLLL_____________________]
year 3: [BTTTTTTTLLLLLLLL______________________________]
year 4: [BBBTTTTTTTTTTTTTTTTTLLLLLLLL__________________]
So for year 1 we had 2% Bears, 40% Trees (Saplings+Trees+Elder Trees), 6% Lumberjacks and the rest was open space
Each spot is 2%. We have 50 characters. So 100%. We round "up" for figuring out how many to display and just use "_" as
filler at the end for open space.
#Optional Output 2:
You can over the course of the simulation output the "Map" in ASCII or any other form you wish. Use like "B" For bear
"S" for sapling "T" for tree "E" for Elder Tree, "L" For lumberjack and "." for empty.
Some people can use "animated" ascii via like a ncurses library and show in realtime what is happening. (logs go to a
file or not shown) Etc. Ultimately be creative
here in how you might want to show over time the impact of how the forest is changing.
Or you can just print out the forest every year or every 10 years.
#Ackward events/issues/etc:
When bears and lumberjacks roam if the random spot already has a bear or lumberjack in it a new spot is picked. If the
2nd attempt at a spot still has a same kind of element then it will stop roaming for the month. More or less we don't
want more than 1 lumberjacks or bears in the same spot.
Bears can roam into a Tree spot. Nothing happens. If a bear roams into a lumberjack he maws him. If a lumberjack roams
into a Bear spot he will get maw'd by the bear.
#Spawn/Decay/Removal Rates:
You might encounter issues with these. Feel free to tweak as needed. The challenge is more a test of design.
Picking/playing with and testing these rates is part of design work. It might look good on paper but when tested it
might not work without some minor tweaks.
"""
def main():
pass
if __name__ == "__main__":
main()
|
a79267445937abe1983f1c084b700732ca840e21 | DayGitH/Python-Challenges | /DailyProgrammer/DP20150803A.py | 2,995 | 3.703125 | 4 | """
[2015-08-03] Challenge #226 [Easy] Adding fractions
https://www.reddit.com/r/dailyprogrammer/comments/3fmke1/20150803_challenge_226_easy_adding_fractions/
#Description
Fractions are the bane of existence for many elementary and middle-schoolers. They're sort-of hard to get your head
around (though thinking of them as pizza slices turned out to be very helpful for me), but even worse is that they're
so hard to calculate with! Even adding them together is no picknick.
Take, for instance, the two fractions 1/6 and 3/10. If they had the same denominator, you could simply add the
numerators together, but since they have different denominators, you can't do that. First, you have to make the
denominators equal. The easiest way to do that is to use cross-multiplication to make both denominators 60 (i.e. the
original denominators multiplied together, 6 \* 10). Then the two fractions becomes 10/60 and 18/60, and you can then
add those two together to get 28/60.
*(if you were a bit more clever, you might have noticed that the lowest common denominator of those fractions is
actually 30, not 60, but it doesn't really make much difference).*
You might think you're done here, but you're not! 28/60 has not been reduced yet, those two numbers have factors in
common! The greatest common divisor of both is 4, so we divide both numerator and denominator with 4 to get 7/15, which
is the real answer.
For today's challenge, you will get a list of fractions which you will add together and produce the resulting fraction,
reduced as far as possible.
**NOTE:** Many languages have libraries for rational arithmetic that would make this challenge really easy (for
instance, Python's `fractions` module does exactly this). You are allowed to use these if you wish, but the spirit of
this challenge is to try and implement the logic yourself. I highly encourage you to only use libraries like that if
you can't figure out how to do it any other way.
#Formal inputs & outputs
##Inputs
The input will start with a single number N, specifying how many fractions there are to be added.
After that, there will follow N rows, each one containing a fraction that you are supposed to add into the sum. Each
fraction comes in the form "X/Y", so like "1/6" or "3/10", for instance.
##Output
The output will be a single line, containing the resulting fraction reduced so that the numerator and denominator has
no factors in common.
#Sample inputs & outputs
##Input 1
2
1/6
3/10
##Output 1
7/15
##Input 2
3
1/3
1/4
1/12
##Output 2
2/3
#Challenge inputs
##Input 1
5
2/9
4/35
7/34
1/2
16/33
##Input 2
10
1/7
35/192
61/124
90/31
5/168
31/51
69/179
32/5
15/188
10/17
#Notes
If you have any challenge suggestions, please head on over to /r/dailyprogrammer_ideas and suggest them! If they're
good, we might use them!
"""
def main():
pass
if __name__ == "__main__":
main()
|
cedde37647701d970cc14b091dd084966a18d480 | DayGitH/Python-Challenges | /DailyProgrammer/DP20120808A.py | 1,026 | 4.1875 | 4 | """
[8/8/2012] Challenge #86 [easy] (run-length encoding)
https://www.reddit.com/r/dailyprogrammer/comments/xxbbo/882012_challenge_86_easy_runlength_encoding/
Run-Length encoding is a simple form of compression that detects 'runs' of repeated instances of a symbol in a string
and compresses them to a list of pairs of 'symbol' 'length'. For example, the string
"Heeeeelllllooooo nurse!"
Could be compressed using run-length encoding to the list of pairs
[(1,'H'),(5,'e'),(5,'l'),(5,'o'),(1,'n'),(1,'u'),(1,'r'),(1,'s'),(1,'e')]
Which seems to not be compressed, but if you represent it as an array of 18bytes (each pair is 2 bytes), then we save 5
bytes of space compressing this string.
Write a function that takes in a string and returns a run-length-encoding of that string. (either as a list of pairs
or as a 2-byte-per pair array)
BONUS: Write a decompression function that takes in the RLE representation and returns the original string
"""
def main():
pass
if __name__ == "__main__":
main()
|
e78435c9acf2b2a8331204b05a3c6c29dfebf685 | DayGitH/Python-Challenges | /DailyProgrammer/DP20150116C.py | 982 | 3.875 | 4 | """
[2015-01-16] Challenge #197 [Hard] Crazy Professor
https://www.reddit.com/r/dailyprogrammer/comments/2snhei/20150116_challenge_197_hard_crazy_professor/
#Description
He's at it again, the professor at the department of Computer Science has posed a question to all his students knowing
that they can't brute-force it. He wants them all to think about the efficiency of their algorithms and how they could
possibly reduce the execution time.
He posed the problem to his students and then smugly left the room in the mindset that none of his students would
complete the task on time (maybe because the program would still be running!).
#The problem
What is the 1000000th number that is not divisble by any prime greater than 20?
#Acknowledgements
Thanks to /u/raluralu for this submission!
#NOTE
counting will start from 1. Meaning that the 1000000th number is the 1000000th number and not the 999999th number.
"""
def main():
pass
if __name__ == "__main__":
main()
|
9dbec4d1133da2b905f6a952f6df5f8248255947 | DayGitH/Python-Challenges | /DailyProgrammer/DP20151102A.py | 2,174 | 3.625 | 4 | """
[2015-11-02] Challenge #239 [Easy] A Game of Threes
https://www.reddit.com/r/dailyprogrammer/comments/3r7wxz/20151102_challenge_239_easy_a_game_of_threes/
# Background
Back in middle school, I had a peculiar way of dealing with super boring classes. I would take my handy pocket
calculator and play a "Game of Threes". Here's how you play it:
First, you mash in a random large number to start with. Then, repeatedly do the following:
* If the number is divisible by 3, divide it by 3.
* If it's not, either add 1 or subtract 1 (to make it divisible by 3), then divide it by 3.
The game stops when you reach "1".
While the game was originally a race against myself in order to hone quick math reflexes, it also poses an opportunity
for some interesting programming challenges. Today, the challenge is to create a program that "plays" the Game of
Threes.
# Challenge Description
The input is a single number: the number at which the game starts. Write a program that plays the Threes game, and
outputs a valid sequence of steps you need to take to get to 1. Each step should be output as the number you start at,
followed by either -1 or 1 (if you are adding/subtracting 1 before dividing), or 0 (if you are just dividing). The last
line should simply be 1.
# Input Description
The input is a single number: the number at which the game starts.
100
# Output Description
The output is a list of valid steps that must be taken to play the game. Each step is represented by the number you
start at, followed by either -1 or 1 (if you are adding/subtracting 1 before dividing), or 0 (if you are just
dividing). The last line should simply be 1.
100 -1
33 0
11 1
4 -1
1
# Challenge Input
31337357
# Fluff
Hi everyone! I am /u/Blackshell, one of the new moderators for this sub. I am very happy to meet everyone and
contribute to the community (and to give /u/jnazario a little bit of a break). If you have any feedback for me, I would
be happy to hear it. Lastly, as always, remember if you would like to propose a challenge to be posted, head over to
/r/dailyprogrammer_ideas.
"""
def main():
pass
if __name__ == "__main__":
main()
|
47d2c0703237402d0fd293c70078af9f4b3554b4 | DayGitH/Python-Challenges | /DailyProgrammer/DP20150626C.py | 3,776 | 3.8125 | 4 | """
[2015-06-26] Challenge #220 [Hard] Substitution Cryptanalysis
https://www.reddit.com/r/dailyprogrammer/comments/3b668g/20150626_challenge_220_hard_substitution/
# [](#HardIcon) _(Hard)_: Substitution Cryptanalysis
A [substitution cipher](https://en.wikipedia.org/?title=Substitution_cipher) is one where each letter in the alphabet
is substituted for another letter. It's like a Caesar shift cipher, but where every letter is ciphered independently.
For example, look at the two rows below.
abcdefghijklmnopqrstuvwxyz
YOJHZKNEALPBRMCQDVGUSITFXW
To encode something, find the letter on the top row, and swap it with the letter on the bottom row - and vice versa.
For example, the plaintext:
hello world
Becomes:
EZBBC TCVBH
Now, how would you go about decrypting something like this? Let's take another example, with a different key.
IAL FTNHPL PDDI DR RDNP WF IUD
You're also given the following hints: `A` is ciphered to `H` and `O` is ciphered to `D`. You know the text was in
English, so you could plausibly use a word list to rule out impossible decrypted texts - for example, in the third
words `PDDI`, there is a double-O in the middle, so the first letter rules out P being the letter Q, as Q is always
followed by a U.
Your challenge is to decrypt a cipher-text into a list of possible original texts using a few letters of the
substitution key, and whichever means you have at your disposal.
# Formal Inputs and Outputs
## Input Description
On the first line of input you will be given the ciphertext. Then, you're given a number **N**. Finally, on the next
**N** lines, you're given pairs of letters, which are pieces of the key. For example, to represent our situation above:
IAL FTNHPL PDDI DR RDNP WF IUD
2
aH
oD
Nothing is case-sensitive. You may assume all plain-texts are in English. Punctuation is preserved, including spaces.
## Output Description
Output a list of possible plain-texts. Sometimes this may only be one, if your input is specific enough. In this case:
the square root of four is two
You don't need to output the entire substitution key. In fact, it may not even be possible to do so, if the original
text isn't a pangram.
# Sample Inputs and Outputs
## Sample 1
### Input
LBH'ER ABG PBBXVAT CBEX PUBC FNAQJVPURF
2
rE
wJ
### Output
you're not cooking pork chop sandwiches
you're nob cooking pork chop sandwiches
Obviously we can guess which output is valid.
## Sample 2
### Input
This case will check your word list validator.
ABCDEF
2
aC
zF
### Output
quartz
## Sample 3
### Input
WRKZ DG ZRDG D AOX'Z VQVX
2
wW
sG
### Output
what is this i don't even
whet is this i can't ulun
(what's a ulun? I need a better word list!)
## Sample 4
### Input
JNOH MALAJJGJ SLNOGQ JSOGX
1
sX
### Output
long parallel ironed lines
# Notes
There's a handy word-list [here](https://gist.githubusercontent.com/Quackmatic/512736d51d84277594f2/raw/words) or you
could check out [this thread](/r/dailyprogrammer/comments/2nluof/) talking about word lists.
You could also *in*validate words, rather than just validating them - check out [this list of impossible two-letter
combinations](http://linguistics.stackexchange.com/questions/4082/impossible-bigrams-in-the-english-language). If
you're using multiple systems, perhaps you could use a weighted scoring system to find the correct decrypted text.
There's an [example solver](http://quipqiup.com/) for this type of challenge, which will try to solve it, but it has a
really weird word-list and ignores punctuation so it may not be awfully useful.
Got any cool challenge ideas? Post them to /r/DailyProgrammer_Ideas!
"""
def main():
pass
if __name__ == "__main__":
main()
|
679d823627f1fc41e7027d234a4ae51b9ba3868d | DayGitH/Python-Challenges | /ProjectEuler/pr0019.py | 1,393 | 4.15625 | 4 | """
You are given the following information, but you may prefer to do some research for yourself.
* 1 Jan 1900 was a Monday.
* Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
* A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
"""
MONTHS = 12
m_dict = {1:31,2:28,3:31,4:30,5:31,6:30,7:31,8:31,9:30,10:31,11:30,12:31}
year = 1900
day = 1
sun_count = 0
# loop through years
while year < 2001:
# loop through months
for m in range(1,MONTHS+1):
# get number of days in month from dictionary
DAYS = m_dict[m]
# make adjustment for leap years
if m == 2:
if year%400 == 0:
DAYS += 1
elif year%100 == 0:
pass
elif year%4 == 0:
DAYS += 1
#loop through days
for n in range(1,DAYS+1):
# count for first sunday of a month
if n == 1 and day == 7 and year > 1900:
sun_count += 1
# day of the week count
day = day + 1 if day < 7 else 1
year += 1
print(sun_count) |
90235fc4d5cb7fb5095d8d21808a2166454234ef | DayGitH/Python-Challenges | /DailyProgrammer/DP20150415B.py | 3,981 | 3.609375 | 4 | """
[2015-04-15] Challenge #210 [Intermediate] Drawing a gradient
https://www.reddit.com/r/dailyprogrammer/comments/32o5je/20150415_challenge_210_intermediate_drawing_a/
#Description
One of the most basic tools in graphic design toolbox is the "gradient": a smooth transtion from one color to another.
They are remarkably useful and are available in virtually every graphic design program and graphic programming library,
and even natively in design languages like CSS and SVG.
Your task today is to make a program that can generate these wonderful gradients, and then either draw it to the screen
or save it as an image file. You will get as inputs pixel dimensions for the size of the gradient, and the two colors
that the gradient should transition between.
**NOTE:** As I said, there are many imaging libraries that provide this functionality for you, usually in some function
called `drawGradient()` or something similar. You are *strongly encouraged* not to use functions like this, the spirit
of this challenge is that you should figure out how to calculate the gradient (and thus the individual pixel colors)
yourself.
This isn't an ironclad rule, and if you really can't think of any way to do this yourself, then it's fine to submit
your solution using one of these functions. I encourage you to try, though.
It is, however, perfectly acceptable to use a library to save your pixels in whatever format you like.
#Formal Inputs & Outputs
##Input description
Your input will consist of three lines. The first line contains two numbers which is the width and the height of the
resulting gradient. The other two lines consist of three numbers between 0 and 255 representing the colors that
the gradient should transition between. The first color should be on the left edge of the image, the second color
should be on the right edge of the image.
So, for instance, the input
500 100
255 255 0
0 0 255
means that you should draw a 500x100 gradient that transitions from yellow on the left side to blue on the right side.
##Output description
You can either choose to draw your gradient to the screen or save it as an image file. You can choose whatever image
format you want, though it should preferably a lossless format like PNG.
If you don't wish to tangle with libraries that output PNG images, I recommend checking out the
[Netpbm](http://en.wikipedia.org/wiki/Netpbm) format, which is a very easy format to output images in. There's even a
[dailyprogrammer challenge](https://www.reddit.com/r/dailyprogrammer/comments/2ba3g3/7212014_challenge_172_easy/) that
can help you out.
Regardless of your chosen method of output, I highly encourage you to upload your resulting images to
[imgur](http://imgur.com) so that the rest of us can see the product of your hard work! If you chose to output your
image to the screen, you can take a screenshot and crop the gradient out.
#Example inputs & outputs
#Input
500 100
255 255 0
0 0 255
#Output
[This image](http://i.imgur.com/LNBRYhr.png)
#Challenge inputs
1000 100
204 119 34
1 66 37
Those two colors are Ochre and British Racing Green, my two favorite colors. Use those as a challenge input, or pick
your own two favorite colors!
#Bonus
We often see people solving these problems in weird languages here at /r/dailyprogrammer, and this bonus is for all you
crazy people:
Solve this problem in [brainfuck](http://en.wikipedia.org/wiki/Brainfuck). You don't have to read the values from
input, you can "hard-code" the colors and dimensions in your program. You can pick whatever colors and dimensions you
like, as long as both the width and the height is larger than 100 pixels. You can also output the image in whatever
format you want (I imagine that one of the binary Netpbm formats will be the easiest). Good luck!
#Finally
Have a good challenge idea?
Consider submitting it to /r/dailyprogrammer_ideas
"""
def main():
pass
if __name__ == "__main__":
main()
|
af89dc719535ca89d2bd27e9ca476b048a376d03 | DayGitH/Python-Challenges | /ProjectEuler/pr0007.py | 547 | 3.734375 | 4 | """
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
"""
prime = []
for i in range(2,1000000):
prime.append(i)
p = 0
for i in range(10001):
p_hold = prime
prime = []
for j in range(len(p_hold)):
if p_hold[j] == p_hold[p]:
prime.append(p_hold[j])
elif p_hold[j] % p_hold[p] == 0:
pass
else:
prime.append(p_hold[j])
print(p_hold[p])
p += 1
x=1
x=2 |
bdd280fdbe78f8e99334d500a57772cf37cfd0d5 | DayGitH/Python-Challenges | /DailyProgrammer/DP20170911A.py | 2,361 | 3.65625 | 4 | """
[2017-09-11] Challenge #331 [Easy] The Adding Calculator
https://www.reddit.com/r/dailyprogrammer/comments/6ze9z0/20170911_challenge_331_easy_the_adding_calculator/
#**Description**
Make a calculator that lets the user add, subtract, multiply and divide integers. It should allow exponents too. The
user can only enter integers and must expect the result to be integers. The twist is that YOU, the programmer, can only
let the program calculate expressions using addition. Only addition. The user can enter 3*2 however you cannot
calculate it using multiplication.
Basically, the programmer is not allowed to multiply, divide and subtract using the operations provided by a
programming language. To the programmer, the only accessible *direct* operation is addition.
Your calculator should be able to handle addition, subtraction, division, multiplication and exponents. No modulo
operation (to obtain the remainder for two given operands) too.
Please note that
+ You are not allowed to use any functions (other than user-defined functions) to work with exponents. Basically, don't
cheat by allowing pre-defined functions from a library for the dirty work.
+ You can use logical operators.
+ The only binary arithmetic operator that you can use is \+ (addition).
+ The only unary operator that you can use is \+\+ (increment operator).
+ No bitwise operations are allowed.
#**Input description**
Allow the user to enter two integers and the operation symbol.
Let's use \^ for exponents i.e. 2\^3 = 2^3 = 8
#**Output description**
If the answer is an integer, display the answer. If the answer is not an integer, display a warning message. Handle
errors like 1/0 appropriately.
#**Challenge Inputs and Outputs**
Input | Output
:--| --:
12 + 25 | 37
-30 + 100 | 70
100 - 30 | 70
100 - -30 | 130
-25 - 29 | -54
-41 - -10 | -31
9 * 3 | 27
9 * -4 | -36
-4 * 8 | -32
-12 * -9 | 108
100 / 2 | 50
75 / -3 | -25
-75 / 3 | -25
7 / 3 | Non-integral answer
0 / 0 | Not-defined
5 ^ 3 | 125
-5 ^ 3 | -125
-8 ^ 3 | -512
-1 ^ 1 | -1
1 ^ 1 | 1
0 ^ 5 | 0
5 ^ 0 | 1
10 ^ -3 | Non-integral answer
#**Bonus**
Modify your program such that it works with decimals (except for \^ operation) with a minimum precision of 1 decimal
place.
----
Submit to /r/dailyprogrammer_ideas if you have any cool ideas!
"""
def main():
pass
if __name__ == "__main__":
main()
|
dca128ba4183ba191a980e31fbe857280b70450f | DayGitH/Python-Challenges | /DailyProgrammer/20120331A.py | 502 | 4.125 | 4 | """
A very basic challenge:
In this challenge, the
input is are : 3 numbers as arguments
output: the sum of the squares of the two larger numbers.
Your task is to write the indicated challenge.
"""
"""
NOTE: This script requires three input arguments!!!
"""
import sys
arguments = len(sys.argv)
if arguments != 4:
print('Invalid number of arguments:\t{}'.format(arguments - 1))
print('Required number of arguments:\t3')
else:
l = sorted(list(map(int, sys.argv[1:])))
print(sum(l[1:])) |
3cb5639cb47499b5ccb10a6c81ef215d291f4cac | DayGitH/Python-Challenges | /DailyProgrammer/DP20161104C.py | 2,292 | 3.625 | 4 | """
[2016-11-04] Challenge #290 [Hard] Gophers and Robot Dogs
https://www.reddit.com/r/dailyprogrammer/comments/5b5fc8/20161104_challenge_290_hard_gophers_and_robot_dogs/
# Description
You're a farmer in the future. Due to some freak accident, all dogs were wiped out but gophers have multiplied and
they're causing havoc in your fields. To combat this, you bought a robot dog. Only one problem - you have to program it
to chase the gophers.
The robot dogs can run faster than the natural gophers. Assuming that the gopher starts running when it's been spotted
by the dog, the gopher will run in as straight a line as it can towards the nearest hole. The dog can catch the little
rascal by cutting off the gopher before it reaches the hole. Assume that if the dog is within a square of the gopher,
it's got it capture (e.g. the dog may beat the gopher to a position, but it'll be able to snag it). If the gopher sees
the dog waiting the gopher will change direction, so it will have to grab it on the run.
Your task today is to write a program that identifies the best route to run to catch the gopher. Remember - the gopher
will run to the nearest hole in a straight line. The dog will run in a straight line, too, you just have to tell it
where to go.
# Input Description
You'll be given several lines. The first line tells you the dog's position and speed (in units per second) as three
numbers: the x and y coordinates then the speed. The next line tells you the gopher's position as an x and y coordinate
position and its speed (in units per second). The next line tells you how many additional lines *N* to read, these are
the gopher holes. Each of the *N* lines tells you a gopher hole as an x and y coordinate. Example:
10 10 1.0
1 10 0.25
2
0 0
10 0
# Output Description
Your program should emit the position the dog should run in a straight line to catch the gopher. Example:
1 7
The gopher will run to the hole at (0,0). The dog should run to position (1,7) to catch the gopher.
# Challenge Input
5 3 1.2
2 8 0.5
3
10 1
11 7
10 9
# Notes
Added clarification that the dog will only catch the gopher on the run.
This challenge was inspired by a conversation with former moderator XenophonOfAthens.
"""
def main():
pass
if __name__ == "__main__":
main()
|
036b8b85dadb10cf663d178105c4b0415c1d2db3 | DayGitH/Python-Challenges | /DailyProgrammer/DP20180129A.py | 2,013 | 4.09375 | 4 | """
[2018-01-29] Challenge #349 [Easy] Change Calculator
https://www.reddit.com/r/dailyprogrammer/comments/7ttiq5/20180129_challenge_349_easy_change_calculator/
# Description
You own a nice tiny mini-market that sells candies to children. You need to know if you'll be able to give the change
back to those little cute creatures and it happens you don't know basic math because when you were a child you were
always eating candies and did not study very well. So you need some help from a little tool that tell you if you can.
# Input Description
On the line beginning "Input:" be given a single number that tells you how much change to produce, and then a list of
coins you own. The next line, beginning with "Output:", tells you the number of coins to give back to achieve the
change you need to give back (bounded by the number of coins you have). Here's one that says "give the customer 3 or
fewer coins". Example:
Input: 10 5 5 2 2 1
Output: n <= 3
# Output Description
Your progam should emit the coins you would give back to yield the correct value of change, if possible. Multiple
solutions may be possible. If no solution is possible, state that. Example:
5 5
# Challenge Input
Input: 150 100 50 50 50 50
Output: n < 5
Input: 130 100 20 18 12 5 5
Output: n < 6
Input: 200 50 50 20 20 10
Output: n >= 5
# Bonus
Output the minimum number of coins needed:
Input: 150 100 50 50 50 50
Output: 2
Input: 130 100 20 18 12 5 5
Output: 3
# Challenge
Input: 150 1 1 ... 1 (1 repeated 10000 times)
Output: 150
# Note
This is the subset sum problem with a twist, a classic computational complexity problem which poses fun questions about
efficient calculation and lower bounds of complexity.
# Credit
This challenge was suggested by use /u/Scara95, many thanks. If you have a challenge idea, please share it on
/r/dailyprogrammer_ideas and there's a good chance we'll use it.
"""
def main():
pass
if __name__ == "__main__":
main()
|
7d6088c5b27834e9b49c1c7b3c9d3aa5da6b5830 | DayGitH/Python-Challenges | /DailyProgrammer/DP20130510C.py | 7,377 | 3.9375 | 4 | """
[05/10/13] Challenge #123 [Hard] Robot Jousting
https://www.reddit.com/r/dailyprogrammer/comments/1ej32w/051013_challenge_123_hard_robot_jousting/
# [](#HardIcon) *(Hard)*: Robot Jousting
You are an expert in the new and exciting field of *Robot Jousting*! Yes, you read that right: robots that charge one
another to see who wins and who gets destroyed. Your job has been to work on a simulation of the joust matches and
compute *when* there is a collision between the two robots and *which* robot would win (the robot with the higher
velocity), thus preventing the destruction of very expensive hardware.
Let's define the actual behavior of the jousting event and how the robots work: the event takes place in a long
hallway. Robots are placed initially in the center on the far left or far right of the hallway. When robots start, they
choose a given starting angle, and keep moving forward until they hit a wall. Once a robot hits a wall, they stop
movement, and rotate back to the angle in which they came into the wall. Basically robots "reflect" themselves off the
wall at the angle in which they hit it. For every wall-hit event, the robot loses 10% of its speed, thus robots will
slow down over time (but never stop until there is a collision).
[Check out these two images as examples of the described scene](http://imgur.com/a/NSzpY). Note that the actual robot
geometry you want to simulate is a perfect circle, where the radius is 0.25 meters, or 25 centimeters.
# Formal Inputs & Outputs
## Input Description
You will be given three separate lines of information: the first has data describing the hallway that the robots will
joust in, and then the second and third represent information on the left and right robots, respectively.
The first line will contain two integers: how long and wide the hallway is in meters. As an example, given the line "10
2", then you should know that the length of the hallway is 10 meters, while the width is just 2 meters.
The second and third lines also contain two integers: the first is the initial angle the robot will move towards (in
degrees, as a signed number, where degree 0 always points to the center of the hallway, negative points to the left,
and positive points to the right). The second integer is the speed that the robot will initially move at, as defined in
millimeters per second. As an example, given the two lines "45 5" and "-45 2", we know that the left robot will launch
at 45 degrees to its left, and that the second robot will launch 45 degrees to its left (really try to understand the
angle standard we use). The left robot starts with an initial speed of 5 mm/s with the right robot starting at 2 mm/s.
Assume that the robot radius will always be a quarter of a meter (25 centimeters).
## Output Description
Simply print "Left robot wins at X seconds." or "Right robot wins at X seconds." whenever the robots collide: make sure
that the variable X is the number of seconds elapsed since start, and that the winning robot is whichever robot had the
higher velocity. In case the robots never hit each other during a simulation, simply print "No winner found".
# Sample Inputs & Outputs
## Sample Input
10 2
30 5
-10 4
## Sample Output
*Please note that this is FAKE data; I've yet to write my own simulation...*
Left robot wins at 32.5 seconds.
# Challenge Note
Make sure to keep your simulation as precise as possible! Any cool tricks with a focus on precision management will get
bonus awards! This is also a very open-ended challenge question, so feel free to ask question and discuss in the
comments section.
"""
def main():
pass
if __name__ == "__main__":
main()
"""
[05/10/13] Challenge #122 [Hard] Subset Sum Insanity
https://www.reddit.com/r/dailyprogrammer/comments/1e2rcx/051013_challenge_122_hard_subset_sum_insanity/
# [](#HardIcon) *(Hard)*: Subset Sum
The [subset sum](http://en.wikipedia.org/wiki/Subset_sum_problem) problem is a classic computer science challenge:
though it may appear trivial on its surface, there is no known solution that runs in [deterministic polynomial
time](http://en.wikipedia.org/wiki/P_(complexity)) (basically this is an
[NP-complete](http://en.wikipedia.org/wiki/Subset_sum_problem) problem). To make this challenge more "fun" (in the same
way that losing in Dwarf Fortress is "fun"), we will be solving this problem in a three-dimensional matrix and define a
subset as a set of integers that are directly adjacent!
**Don't forget our [previous
week-long](http://www.reddit.com/r/dailyprogrammer/comments/1dk7c7/05213_challenge_121_hard_medal_management/) [Hard]
challenge competition ends today!**
# Formal Inputs & Outputs
## Input Description
You will be given three integers `(U, V, W)` on the first line of data, where each is the length of the matrices'
respective dimensions (meaning U is the number of elements in the X dimension, V is the number of elements in the Y
dimension, and W is the number of elements in the Z dimension). After the initial line of input, you will be given a
series of space-delimited integers that makes up the 3D matrix. Integers are ordered first in the X dimension, then Y,
and then Z ( [the coordinate system is clarified here](http://i.imgur.com/nxChpUZ.png) ).
## Output Description
Simply print all sets of integers that sum to 0, if this set is of directly-adjacent integers (meaning a set that
travels vertically or horizontally, but never diagonally). If there are no such sets, simply print "No subsets sum to
0".
# Sample Inputs & Outputs
## Sample Input
2 2 3
-1 2 3 4 1 3 4 5 4 6 8 10
## Sample Output
-1 1
*Note:* This is set of positions (0, 0, 0), and (0, 0, 1).
# Challenge Input
8 8 8
-7 0 -10 -4 -1 -9 4 3 -9 -1 2 4 -6 3 3 -9 9 0 -7 3 -7 -10 -9 4 -6 1 5 -1 -8 9 1 -9 6 -1 1 -8 -6 -5 -3 5 10 6 -1 2
-2 -7 4 -4 5 2 -10 -8 9 7 7 9 -7 2 2 9 2 6 6 -3 8 -4 -6 0 -2 -8 6 3 8 10 -5 8 8 8 8 0 -1 4 -5 9 -7 -10 1 -7 6 1 -10 8 8
-8 -9 6 -3 -3 -9 1 4 -9 2 5 -2 -10 8 3 3 -1 0 -2 4 -5 -2 8 -8 9 2 7 9 -10 4 9 10 -6 5 -3 -5 5 1 -1 -3 2 3 2 -8 -9 10 4
10 -4 2 -5 0 -4 4 6 -1 9 1 3 -7 6 -3 -3 -9 6 10 8 -3 -5 5 2 6 -1 2 5 10 1 -3 3 -10 6 -6 9 -3 -9 9 -10 6 7 7 10 -6 0 6 8
-10 6 4 -4 -1 7 4 -9 -3 -10 0 -6 7 10 1 -9 1 9 5 7 -2 9 -8 10 -8 -7 0 -10 -7 5 3 2 0 0 -1 10 3 3 -7 8 7 5 9 -7 3 10 7
10 0 -10 10 7 5 6 -6 6 -9 -1 -8 9 -2 8 -7 -6 -8 5 -2 1 -9 -8 2 9 -9 3 3 -8 1 -3 9 1 3 6 -6 9 -2 5 8 2 -6 -9 -9 1 1 -9 5
-4 -9 6 -10 10 -1 8 -2 -6 8 -9 9 0 8 0 4 8 -7 -9 5 -4 0 -9 -8 2 -1 5 -6 -5 5 9 -8 3 8 -3 -1 -10 10 -9 -10 3 -1 1 -1 5
-7 -8 -5 -10 1 7 -3 -6 5 5 2 6 3 -8 9 1 -5 8 5 1 4 -8 7 1 3 -5 10 -9 -2 4 -5 -7 8 8 -8 -7 9 1 6 6 3 4 5 6 -3 -7 2 -2 7
-1 2 2 2 5 10 0 9 6 10 -4 9 7 -10 -9 -6 0 -1 9 -3 -9 -7 0 8 -5 -7 -10 10 4 4 7 3 -5 3 7 6 3 -1 9 -5 4 -9 -8 -2 7 10 -1
-10 -10 -3 4 -7 5 -5 -3 9 7 -3 10 -8 -9 3 9 3 10 -10 -8 6 0 0 8 1 -7 -8 -6 7 8 -1 -4 0 -1 1 -4 4 9 0 1 -6 -5 2 5 -1 2 7
-8 5 -7 7 -7 9 -8 -10 -4 10 6 -1 -4 -5 0 -2 -3 1 -1 -3 4 -4 -6 4 5 7 5 -6 -6 4 -10 -3 -4 -4 -2 6 0 1 2 1 -7
# Challenge Note
Like any challenge of this complexity class, you are somewhat constrained to solving the problem with brute-force (sum
all possible sub-sets). We really want to encourage any and all new ideas, so really go wild and absolutely do whatever
you think could solve this problem quickly!
"""
def main():
pass
if __name__ == "__main__":
main()
|
ff0d12abcd0f3b346d1da0bb9b0ac5aa0c25f473 | DayGitH/Python-Challenges | /DailyProgrammer/20120216C.py | 975 | 4.125 | 4 | '''
Write a program that will take coordinates, and tell you the corresponding number in pascals triangle. For example:
Input: 1, 1
output:1
input: 4, 2
output: 3
input: 1, 19
output: error/nonexistent/whatever
the format should be "line number, integer number"
for extra credit, add a function to simply print the triangle, for the extra credit to count, it must print at least
15 lines.
'''
old_list = []
new_list = [1]
print('Line number?')
line_number = int(input('> '))
print('Integer number?')
int_number = int(input('> '))
# print(new_list)
#generates a pascal triangle tier in each loop
for i in range(line_number - 1):
new_list, old_list = [], new_list
new_list.append(1)
if i > 0:
for e in range(0,len(old_list)-1):
new_list.append(old_list[e] + old_list[e + 1])
new_list.append(1)
# print(new_list)
try:
print('The integer is: {}'.format(new_list[int_number - 1]))
except IndexError:
print('Nonexistent!!!') |
cbba0ab3d131440d47fdef8f7d07547336af3907 | DayGitH/Python-Challenges | /DailyProgrammer/DP20120725A.py | 2,279 | 3.875 | 4 | """
[7/25/2012] Challenge #81 [easy] (Numerical Calculus I)
https://www.reddit.com/r/dailyprogrammer/comments/x538d/7252012_challenge_81_easy_numerical_calculus_i/
For a lot of the questions today we are going to be doing some simple numerical calculus. Don't worry, its not too
terrifying.
For the easy problem, write a function that can take in a list of y-values that represents a function sampled on some
domain. The domain can be specified as a list of x-values or two values for the x-minimum and x-maximum (the
x-coordinates of the endpoints)
This function should output another list of values that represents the derivative of that function over the same domain.
Python example:
print derivative(xmin=-1,xmax=1,y=[-1.0,-.5,0,.5,1.0])
outputs:
[1.0,1.0,1.0,1.0,1.0]
Bonus 1) Write the same function but for the indefinite integral.
Bonus 2) This is sort-of an alternate version of the problem... if your language supports first-order functions (that
is, functions as data), then write a function that takes a function A as an argument and returns a function A'.
When A' is evaluated at x, it computes an approximation of the derivative at x
EDIT: devil's assassin gave a decently good explaination of the problem, I'm stealing it here and modifying it a bit.
>for those of you who don't know, the derivative can be defined as the slope of the tangent line at a particular point.
I'm assuming he wants a numerical derivative, making this a programming exercise and not a math one. We need to
interpolate those values into a derivative. If you have some set of numbers N = {a1,a2,a3,a4,...,an} and some domain
set S={b1,b2,...,bn} you can find the slope between two points on this line. Now this is a /bad/ approximation, but it
can be made better through limiting the step size.
>Basically, here is the formula:
>f'(x) = lim h->0(f(x+h) - f(x))/h
>the "lim" part, means that this only works when h is REALLY small (pretty much 0, but without being exactly 0 so there
is no dividing by 0). So you can modify this:
>f'(x) ~= f(x+h)-f(x)/h
Basically, what you do here is use compute the slope between the current point and the next point for each point. Use
the slope equation from two points.
"""
def main():
pass
if __name__ == "__main__":
main()
|
da1c9b2309bcb28b19380e16562cc6d9fa61ac93 | DayGitH/Python-Challenges | /DailyProgrammer/20120211A.py | 838 | 4.03125 | 4 | '''
Welcome to cipher day!
write a program that can encrypt texts with an alphabetical caesar cipher. This cipher can ignore numbers, symbols, and whitespace.
for extra credit, add a "decrypt" function to your program!
'''
import sys
alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
print('Input the text for encryption,')
inp = input('> ').upper()
print('Shift left or right? (L/R)')
dir = input('> ')
if dir not in 'LR':
sys.exit('Bad input. Please input L or R.')
print('Input the number of letters to shift by')
shift = int(input('> '))
output = ''
if dir == 'L':
shift = 26 - shift
for i in inp:
if i in alphabet:
shifted = (alphabet.index(i) + shift) % 26
print(i, alphabet.index(i)+1, shifted+1, alphabet[shifted])
output += alphabet[shifted]
else:
output += i
print(inp, ' ', output) |
bf074df36ff312a7b616a70d03d6582f6e163521 | DayGitH/Python-Challenges | /DailyProgrammer/20120425C.py | 2,160 | 3.921875 | 4 | """
Write a function that takes two arguments a and b, and finds all primes that are between a and a + b (specifically,
find all primes p such that a ? p < a + b). So for instance, for a = 1234 and b = 100, it should return the following
15 primes:
1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321, 1327
The sum of those primes are 19339. The number of primes for a = 9! and b = 8! is 3124 and the sum of those primes is
1196464560.
How many primes are there for a = 16! and b = 10!, and what is their sum?
Note 1: In this problem, n! refers to the factorial [http://en.wikipedia.org/wiki/Factorial] of n, 1*2*3*...*(n-1)*n,
so 9! is equal to 362880.
Note 2: All numbers and solutions in this problem fit into 64-bit integers.
EDIT: changed some incorrect numbers, thanks ixid!
"""
import random
def is_prime(n):
"""https://stackoverflow.com/questions/15285534/isprime-function-for-python-language"""
if n == 2 or n == 3: return True
if n < 2 or n%2 == 0: return False
if n < 9: return True
if n%3 == 0: return False
r = int(n**0.5)
f = 5
while f <= r:
if n%f == 0: return False
if n%(f+2) == 0: return False
f +=6
return True
def eratosthene(n1, n2):
"""from another project"""
L1 = [i for i in range(2, n2+1) if i%2!=0 or i%3!=0 or i%5!=0]
i = 0
while L1[i]**2 <= L1[-1]:
L2 = [a for a in L1 if a%L1[i] != 0 or a <= L1[i]]
L1 = L2 # avoid assignment issues between L1 and L2
i += 1
return [i for i in L1 if i > n1]
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
if __name__ == "__main__":
"""is_prime solution too slow for inp1=16! inp2=10!
eratosthene soluution runs out of memory
"""
inp1 = factorial(16)
inp2 = factorial(10)
# inp1 = 1234
# inp2 = 100
p_list = eratosthene(inp1, inp1+inp2)
print(p_list)
# print(len(p_list), sum(p_list))
# count = 0
# summ = 0
# for i in range(inp1+1, inp1+inp2, 2):
# if is_prime(i):
# count += 1
# summ += i
# print(count, summ)
|
68c014d313a049966da48f75f56b279e980bfb58 | DayGitH/Python-Challenges | /DailyProgrammer/20120423B.py | 3,851 | 4.03125 | 4 | """
We have it easy nowadays when it comes to numbers. It's so simple to add them and subtract them that we don't even
consider that it wasn't always so. Even multiplication is not that tough! And you can represent very large numbers very
easily, if you want to write down a million, you just write "1000000". That's only seven digits!
It wasn't so easy for the Romans. They had to make due with their clumsy Roman numerals. Think how hard it is to add
Roman numerals together. If you wanted to add XXVIII with LXXXII, you would have to smush them together to form
LXXXXXVIIIII, then you would have to realize that XXXXX is equal to L and IIIII is equal to V, and turn it to LLVV, and
then you'd have to shorten that to CX. Look how much work to just add 28 and 82! And just imagine trying to write a
million with Roman numerals: you'd literally have to write down one thousand copies of M!
But Roman numerals aren't without advantages: they at least look very pretty. I think we can all agree that Rocky V
looks way cooler than Rocky 5.
So in this challenge, we honor the romans. Your task is to write a function that can add together two Roman numerals
supplied as strings. Example: roman_addition("XXVIII", "LXXXII") returns "CX".
The easiest way to do this would obviously be to just to convert the roman numerals to integers and then convert the
sum of those integers back to a Roman numeral. But since the Romans couldn't do that, you can't either! Write the
function so that it performs the task similarly to how it might have been done in ancient Rome, either with the
"smushing together" method I described above, or another method of your choosing (don't worry about efficiency). But
at no point shall you convert the numerals to decimal or binary integers! Imagine if you lived in ancient Rome and
decimal numbers hadn't been invented yet, how would you do it?
The output of this function should as "minimal" as possible. I.e. if the answer is XVII, it should output XVII, not
XIIIIIII or VVVII.
Real Roman numerals sometimes uses a trick to make the numbers shorter: you put a smaller numeral in front of a larger
numeral to represent the difference between the two. So for instance, 4 would be written as "IV", 9 as "IX" or 1949 as
"MCMIL". For the purposes of this problem, lets ignore that. 4 is "IIII", 9 is "VIIII" and 1949 is "MDCCCCXXXXVIIII".
The numbers become longer this way, but it makes much more sense if all the numerals are "in order". Also, the exact
rules for how this trick worked was never rigorous, and changed over time.
For reference, here's the different single numerals and their value:
I = 1
V = 5 = IIIII
X = 10 = VV
L = 50 = XXXXX
C = 100 = LL
D = 500 = CCCCC
M = 1000 = DD
Bonus 1: Write a function that does subtraction. Example: roman_subtraction("CX", "LXXXII") returns "XXVIII"
Bonus 2: Write a function that performs multiplication with Roman numerals, again without ever converting them to
regular integers. Example: roman_multiplication("XVI", "VII") returns "CXII".
"""
sort = {"M": 1,
"D": 2,
"C": 3,
"L": 4,
"X": 5,
"V": 6,
"I": 7
}
ref1 = {"DD": "M",
"CCCCC": "D",
"LL": "C",
"XXXXX": "L",
"VV": "X",
"IIIII": "V"
}
ref2 = {"CM": "DCCCC",
"CD": "CCCC",
"XC": "LXXXX",
"XL": "XXXX",
"IX": "VIIII",
"IV": "IIII"
}
inp = "XC LXXXII"
inp = inp.split()
for i in range(len(inp)):
while True:
old = inp[i]
for a in ref2:
inp[i] = inp[i].replace(a, ref2[a])
if inp[i] == old:
break
work = sorted(''.join(inp), key=lambda x:sort[x[0]])
out = ''.join(work)
while True:
old = out
for a in ref1:
out = out.replace(a, ref1[a])
if out == old:
break
print(out)
|
ec8b3baa135800c1fc1b0564018f824a3cd44540 | DayGitH/Python-Challenges | /ProjectEuler/pr0024.py | 972 | 3.640625 | 4 | """
A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits
1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order.
The lexicographic permutations of 0, 1 and 2 are:
012 021 102 120 201 210
What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?
"""
from time import time
startTime = time()
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
index = 1000000
C = 10
fact = factorial(C)
print(index)
total_pos = [i for i in range(C)]
print(total_pos)
answer = ''
for n in range(C,1,-1):
if fact != 2:
fact = int(fact/n)
div = int((index-1)/fact)
else:
div = int((index)/fact)
answer += str(total_pos[div])
total_pos.pop(div)
index -= (div * fact)
answer += str(total_pos[0])
print(answer)
print(time() - startTime) |
b458bc61c6a7741fb6015238ce41c712897c544b | DayGitH/Python-Challenges | /DailyProgrammer/DP20160902C.py | 2,163 | 3.515625 | 4 | """
[2016-09-02] Challenge #281 [Hard] Minesweeper Solver
https://www.reddit.com/r/dailyprogrammer/comments/50s3ax/20160902_challenge_281_hard_minesweeper_solver/
#Description
In this challenge you will come up with an algorithm to solve the classic game of
[Minesweeper](http://minesweeperonline.com/).
The brute force approach is impractical since the search space size is anywhere around 10^20 to 10^100 depending on the
situation, you'll have to come up with something clever.
#Formal Inputs & Outputs
##Input description
The current field state where each character represents one field. Flags will not be used.
Hidden/unknown fields are denoted with a '?'.
'Zero-fields' with no mines around are denoted with a space.
Example for a 9x9 board:
1????
1????
111??
1??
1211 1??
???21 1??
????211??
?????????
?????????
##Output description
A list of zero-based row and column coordinates for the fields that you have determined to be **SAFE**. For the above
input example this would be:
0 5
1 6
1 7
2 7
3 7
5 1
5 7
6 2
6 7
The list does not need to be ordered.
##Challenge input
As suggested by /u/wutaki, this input is a greater challenge then the original input
??????
???2??
???4??
?2??2?
?2222?
?1 1?
#Notes/Hints
If you have no idea where to start I suggest you play the game for a while and try to formalize your strategy.
Minesweeper is a game of both logic and luck. [Sometimes it is impossible](http://i.imgur.com/yLhxzrl.jpg) to find free
fields through logic. The right output would then be an empty list. Your algorithm does not need to guess.
#Bonus
Extra hard mode: Make a closed-loop bot. It should take a screenshot, parse the board state from the pixels, run the
algorithm and manipulate the cursor to execute the clicks.
*Note: If this idea is selected for submission I'll be able to provide lots of input/output examples using my own
solution.*
#Finally
Have a good challenge idea like /u/janismac did?
Consider submitting it to /r/dailyprogrammer_ideas
"""
def main():
pass
if __name__ == "__main__":
main()
|
839e72987bf0d6d3c5a1682de13afc4ae40e6435 | DayGitH/Python-Challenges | /DailyProgrammer/DP20130102C.py | 3,989 | 3.75 | 4 | """
[1/2/2013] Challenge #115 [Difficult] Pack-o-Tron 5000
https://www.reddit.com/r/dailyprogrammer/comments/15uohz/122013_challenge_115_difficult_packotron_5000/
**Description:**
Overdrive Mega-Corporation is coming out with a new and brilliant commercial electronic device that packs your bags for
you! It is named "Pack-o-Tron 5000": an automated box-packing solution. Moving to a new home? Traveling overseas? Going
on a business trip? No matter what, this device will help you pack your boxes optimally, reducing empty space and
fitting more objects in less area!
As the lead engineer, you are tasked with designing the code that generates the "optimal placement" of items in a given
area. Fortunately for you, the "Pack-o-Tron 5000" only works with very specific definitions of "items" and "areas".
(Shh, don't tell the customers that, marketing is still working on it).
An "area" is an empty 2D grid, where the length and width are integers representing inches. As an example, a suitcase
could be defined as a 36-inch by 48-inch grid. An "item" is a 2D object, whose length and width are integers
representing inches. As an example, a tooth-brush item can be 1-inch in width, and 3-inches long.
Your goal is to place all given items in a given area as optimally as possible. "Optimally" is defined as having the
smallest minimum-rectangle that spans your set of items.
Note that the "area" is defined as a grid where the origin is in the top-left and X+ grows to the right, with Y+
growing to the bottom. An item's origin is in the top-left, with X+ growing to the right, and Y+ growing to the bottom.
A minimum-rectangle that spans your set of items is a rectangle on the grid that includes all items placed, and is
either equal to or smaller than the given area. Your goal is to make this minimum-span as small as possible. You are
allowed to place your objects in any position, as long as it is in the grid. You are also allowed to rotate your
objects by 90 degrees.
[Here is an album of several examples of how objects are placed, and how they can be moved and rotated to minimized the
minimum-span rectangle.](http://imgur.com/a/M3MNk)
**Formal Inputs & Outputs:**
*Input Description:*
You will first be given two integers: the width and height of your starting (empty) grid. After, you will be given
another integer representing the number of following items you are to place in this grid. For each item, you will be
given two integers: the width and height of the object. All of this is done through standard input. (i.e. console).
*Output Description:*
Once you have optimally placed the given items in the given grid such that it as the smallest minimum-span possible,
you must print each item's x and y coordinate (as an integer), and the object's size (to show us if there has been any
rotations).
**Sample Inputs & Outputs:**
[Take a look at the example images here.](http://imgur.com/a/M3MNk) For all images that have the two 1x3 items, you
would be given the following sample input:
8 8
2
1 3
1 3
The most optimal result (the last image) is a 2x3 minimum-span, which can be described in the following:
0 0 1 3
1 0 1 3
For those who are keen observers, an equivalent solution is the same pair of objects, but mirrored on the diagonal axis:
0 0 3 1
0 1 3 1
*Note:*
This is essentially a clean version of the [Packing Problem](http://en.wikipedia.org/wiki/Packing_problem). Since the
packing problem is in the computational complexity class of NP-hard, there is no known algorithm to run in P-time
(...yet! Maybe there is! But that's the whole P-NP relationship problem, isn't it? :P). Instead, look into heuristic
algorithm designs, and try to avoid brute-force solutions.
Us mods are putting together an achievement system - those who give us a good solution will get some sort of cool title
in their user-flare, since this challenge is frankly very *very* difficult.
"""
def main():
pass
if __name__ == "__main__":
main()
|
155d9e1fae2d2739a92f65466b0596c7a0765285 | DayGitH/Python-Challenges | /DailyProgrammer/DP20120718A.py | 2,771 | 3.59375 | 4 | """
This one is inspired by an actual problem my friend had to deal with recently. Unfortunately, its a little bit
keyboard-locale specific, so if you don't happen to use a us-EN layout keyboard you might want to get a picture of one.
The en-us keyboard layout pictured here [http://en.wikipedia.org/wiki/File:KB_United_States-NoAltGr.svg] is one common
layout for keys. There are character-generating keys such as '1' and 'q', as well as modifier keys like 'ctrl' and
'shift', and 'caps-lock'
If one were to press every one of the character-generating keys in order from top to bottom left-to-right, you would get
the following string:
`1234567890-=qwertyuiop[]\asdfghjkl;'zxcvbnm,./
plus the whitespace characters TAB,RETURN,SPACE.
Your job is to write a function that takes in a character representing a keypress, as well as a boolean for each
'modifier' key like ctrl,alt,shift,and caps lock, and converts it properly into the ascii character for which the key
gets output.
For example, my python implementation keytochar(key='a',caps=True) returns 'A'. However,
keytochar(key='a',caps=True,shift=True) returns 'a'.
BONUS: Read in a string containing a record of keypresses and output them to the correct string. A status key change is
indicated by a ^ character..if a ^ character is detected, then the next character is either an 's' or 'S' for shift
pressed or shift released, respectively, a 'c' or 'C' for caps on or caps off respectively, and a 't' 'T' for control
down or up, and 'a' 'A' for alt down or up.
For example on the bonus, given the input
^sm^Sy e-mail address ^s9^Sto send the ^s444^S to^s0^S is ^cfake^s2^Sgmail.com^C
you should output
My e-mail address (to send the $$$ to) is FAKE@GMAIL.COM
"""
def key_to_char(key, caps=False, shift=False):
key_dict = {'`': '~', '1': '!', '2': '@', '3': '#', '4': '$', '5': '%', '6': '^',
'7': '&', '8': '*', '9': '(', '0': ')', '-': '_', '=': '+', '[': '{',
']': '}', '\\': '|', ';': ':', "'": '"', ',': '<', '.': '>', '/': '?'}
if shift and key in key_dict:
return key_dict[key]
if shift ^ caps:
return key.capitalize()
else:
return key
def keyboard_printer(string):
caps = False
shift = False
mod = False
for s in string:
if s == '^':
mod = True
continue
if mod:
if s.lower() == 's':
shift = not shift
elif s.lower() == 'c':
caps = not caps
mod = False
continue
print(key_to_char(s, caps=caps, shift=shift), end='')
def main():
keyboard_printer("^sm^Sy e-mail address ^s9^Sto send the ^s444^S to^s0^S is ^cfake^s2^Sgmail.com^C")
if __name__ == "__main__":
main()
|
938569821ca0c1bc75975804d21afc968b709ca1 | DayGitH/Python-Challenges | /DailyProgrammer/DP20140604B.py | 4,215 | 3.765625 | 4 | """
[6/4/2014] Challenge #165 [Intermediate] ASCII Maze Master
https://www.reddit.com/r/dailyprogrammer/comments/278ptv/642014_challenge_165_intermediate_ascii_maze/
# [](#IntermediateIcon) _(Intermediate)_: ASCII Maze Master
We're going to have a slightly more logical puzzle today. We're going to write a program that will find a path through
a simple maze.
A simple maze in this context is a maze where all of the walls are connected to each other. Take this example maze
segment.
# # ### #
# #
# ### B #
# # B #
# B # B #
# B B #
# BBBBB #
# #
#########
See how the wall drawn with `B`s isn't connected to any other walls? That's called a floating wall. A simple maze
contains no floating walls - ie. there are no loops in the maze.
# Formal Inputs and Outputs
## Input Description
You will be given two numbers **X** and **Y**. After that you will be given a textual ASCII grid, **X** wide and **Y**
tall, of walls `#` and spaces. In the maze there will be exactly one letter `S` and exactly one letter `E`. There will
be no spaces leading to the outside of the maze - ie. it will be fully walled in.
## Output Description
You must print out the maze. Within the maze there should be a path drawn with askerisks `*` leading from the letter
`S` to the letter `E`. Try to minimise the length of the path if possible - don't just fill all of the spaces with `*`!
# Sample Inputs & Output
## Sample Input
15 15
###############
#S # #
### ### ### # #
# # # # #
# ##### ##### #
# # # #
# ### # ### ###
# # # # # #
# # ### # ### #
# # # # # # #
### # # # # # #
# # # # # #
# ####### # # #
# #E#
###############
## Sample Output
###############
#S** # #
###*### ### # #
#***# # # #
#*##### ##### #
#*****# # #
# ###*# ### ###
# #***# # # #
# #*### # ### #
# #*# # # #***#
###*# # # #*#*#
#***# # #*#*#
#*####### #*#*#
#***********#E#
###############
# Challenge
## Challenge Input
41 41
#########################################
# # # # # #
# # # ### # # ### # ####### ### ####### #
# #S# # # # # # # # #
# ##### # ######### # # ############# # #
# # # # # # # # # #
# # ##### # ######### ##### # # # # ### #
# # # # # # # # # # # # #
# ##### ######### # ##### ### # # # # # #
# # # # # # # # # #
# ### ######### # ### ##### ### # ##### #
# # # # # # # # # #
# # ### # ### # ### ### ####### ####### #
# # # # # # # # # # #
# ####### # ########### # # ##### # ### #
# # # # # # # # # # #
##### # ##### # ##### ### # ### # #######
# # # # # # # # # # # #
# ### ### ### ### # ### ### # ####### # #
# # # # # # # # # # #
### ##### # ### ### ### # ### # ### ### #
# # # # # # # # # # # # #
# ####### ### # # ### ### # ### # #######
# # # # # # # # #
# ##### ### ##### # # # ##### ### ### ###
# # # # # # # # # # # #
### # # # ### # ##### # ### # # ####### #
# # # # # # # # # # # # #
# ### ##### ### # ##### ### # # # ### # #
# # # # # # # # # # # #
# # ######### ### # # ### ### # ### #####
# # # # # # # # # # # # #
# ##### # # # # # ### # ### # ######### #
# # # # # # # # # # # #
# # # # # # # # ### ### # ############# #
# # # # # # # # # # #
# ######### # # # ### ### ##### # #######
# # # # # # # # # # #
# ### ####### ### # ### ### ##### # ### #
# # # # # #E #
#########################################
# Notes
One easy way to solve simple mazes is to always follow the wall to your left or right. You will eventually arrive at
the end.
"""
def main():
pass
if __name__ == "__main__":
main()
|
ef7b5cbc0cd0523144d721544483329e68675b47 | DayGitH/Python-Challenges | /DailyProgrammer/DP20140730B.py | 2,960 | 3.984375 | 4 | """
[7/30/2014] Challenge #173 [Intermediate] Advanced Langton's Ant
https://www.reddit.com/r/dailyprogrammer/comments/2c4ka3/7302014_challenge_173_intermediate_advanced/
# [](#IntermediateIcon) _(Intermediate)_: Advanced Langton's Ant
If you've done any work or research onto cellular automata, you may have heard of [Langton's
Ant](http://en.wikipedia.org/wiki/Langton%27s_ant). It starts with a grid similar to that of [Conway's Game of
Life](http://www.reddit.com/r/dailyprogrammer/comments/271xyp/) where a grid cell can be black or white, however this
time we have an 'ant' on it. This little metaphorical ant will follow these four rules at every 'step':
* If the current square is white, turn the ant 90' clockwise
* If the current square is black, turn the ant 90' anticlockwise
* Flip the colour of the current square
* Move forward (from the ant's perspective) one cell
With the following starting conditions:
* All cells start white
* The ant starts pointing north
However, being /r/DailyProgrammer, we don't do things the easy way. Why only have 2 colours, black or white? Why not as
many colours as you want, where you choose whether ant turns left or right at each colour? Today's challenge is to
create an emulator for such a modifiable ant.
If you have more than 2 colours, of course, there is no way to just 'flip' the colour. Whenever the ant lands on a
square, it is to change the colour of the current square to the next possible colour, going back to the first one at
the end - eg. red, green, blue, red, green, blue, etc. In these cases, at the start of the simulation, all of the cells
will start with the first colour/character.
## Input Description
You will be given one line of text consisting of the characters 'L' and 'R', such as:
LRLRR
This means that there are 5 possible colours (or characters, if you're drawing the grid ASCII style - choose the
colours or characters yourself!) for this ant.
In this case, I could choose 5 colours to correspond to the LRLRR:
* White, turn left (anticlockwise)
* Black, turn right (clockwise)
* Red, turn left (anticlockwise)
* Green, turn right (clockwise)
* Blue, turn right (clockwise)
You could also choose characters, eg. `' '`, `'#'`, `'%'`, `'*'`, `'@'` instead of colours if you're ASCII-ing the
grid. You will then be given another line of text with a number **N** on it - this is the number of 'steps' to simulate.
## Output Description
You have some flexibility here. The bare minimum would be to output the current grid ASCII style. You could also draw
the grid to an image file, in which case you would have to choose colours rather than ASCII characters. I know there
are some people who do these sorts of challenges with C/C++ curses or even more complex systems.
# Notes
[More info on Langton's Ant with multiple
colours.](http://en.wikipedia.org/wiki/Langton%27s_ant#Extension_to_multiple_colors)
"""
def main():
pass
if __name__ == "__main__":
main()
|
e468767ef3ec92629303e5c294e393f29ae6ee83 | DayGitH/Python-Challenges | /DailyProgrammer/20120218A.py | 906 | 4.34375 | 4 | '''
The exercise today asks you to validate a telephone number, as if written on an input form. Telephone numbers can be
written as ten digits, or with dashes, spaces, or dots between the three segments, or with the area code parenthesized;
both the area code and any white space between segments are optional.
Thus, all of the following are valid telephone numbers: 1234567890, 123-456-7890, 123.456.7890, (123)456-7890,
(123) 456-7890 (note the white space following the area code), and 456-7890.
The following are not valid telephone numbers: 123-45-6789, 123:4567890, and 123/456-7890.
source: programmingpraxis.com
'''
import re
l = ['1234567890', '123-456-7890', '123.456.7890', '(123)456-7890', '(123) 456-7890', '456-7890', '123-45-6789',
'123:4567890', '123/456-7890']
s = re.compile('(([(]*)([0-9]{3})([)]*)([.-]*)([ ]*))*([0-9]{3})([.-]*)([0-9]{4})')
for a in l:
print(s.match(a)) |
b7a8823590f4459788d5d7d25cd8b4150e102b2a | DayGitH/Python-Challenges | /DailyProgrammer/20120602C.py | 2,504 | 3.96875 | 4 | """
Two strings A and B are said to have a common substring called C, if C is embedded somewhere in both A and B. For
instance, "ble" is a common substring for "Double, double, toil and trouble" and "Fire burn and cauldron bubble"
(because, as you can see, "ble" is part of both "Double" and "Bubble"). It is, however, not the longest common
substring, the longest common substring is " and " (5 characters long for vs. 3 characters long for "ble").
Define two pseudo-random number generators, P(N) and Q(N), like this:
P(0) = 123456789
P(N) = (22695477 * P(N-1) + 12345) mod 1073741824
Q(0) = 987654321
Q(N) = (22695477 * Q(N-1) + 12345) mod 1073741824
Thus, they're basically the same except for having different seed values. Now, define SP(N) to be the first N values of
P concatenated together and made into a string. Similarly, define SQ(N) as the first N values of Q concatenated
together and made into a string. So, for instance:
SP(4) = "123456789752880530826085747576968456"
SQ(4) = "987654321858507998535614511204763124"
The longest common substring for SP(30) and SQ(30) is "65693".
Find the longest common substring of SP(200) and SQ(200)
BONUS: Find the longest common substring of SP(4000) and SQ(4000).
"""
import numpy as np
def get_string(N, P, Q):
P, Q = [P], [Q]
for i in range(N - 1):
P.append((22695477 * P[-1] + 12345) % 1073741824)
Q.append((22695477 * Q[-1] + 12345) % 1073741824)
SP = ''.join(map(str, P))
SQ = ''.join(map(str, Q))
return SP, SQ
def longest_common_substring(str1, str2):
l1 = len(str1)
l2 = len(str2)
if l2 < l1:
l1, l2 = l2, l1
str1, str2 = str2, str1
L = np.zeros((l1, l2))
z = 0
ret = []
""" based on pseudocode from wikipedia """
for i in range(l1):
for j in range(l2):
if str1[i] == str2[j]:
if i == 0 or j == 0:
L[i, j] = 1
else:
L[i, j] = L[i-1, j-1] + 1
if L[i, j] > z:
z = int(L[i, j])
ret = [str1[i-z+1:i+1]]
elif L[i, j] == z:
ret.append(str1[i-z+1:i+1])
else:
L[i, j] = 0
if len(ret) == 1:
return ret[0]
else:
return ret
def main():
N = 200
P_init, Q_init = 123456789, 987654321
SP, SQ = get_string(N, P_init, Q_init)
print(longest_common_substring(SP, SQ))
if __name__ == "__main__":
main()
|
c07680eceb44d85d5f341a0fe68f9f522a6a723e | DayGitH/Python-Challenges | /DailyProgrammer/DP20161010W.py | 1,065 | 3.96875 | 4 | """
Weekly #26 - Mini Challenges
https://www.reddit.com/r/dailyprogrammer/comments/56mfgz/weekly_26_mini_challenges/
So this week, let's do some mini challenges. Too small for an easy but great for a mini challenge. Here is your chance
to post some good warm up mini challenges. How it works. Start a new main thread in here.
if you post a challenge, here's a template from /u/lengau for anyone wanting to post challenges (you can copy/paste
this text rather than having to get the source):
`**[CHALLENGE NAME]** - [CHALLENGE DESCRIPTION]`
` `
`**Given:** [INPUT DESCRIPTION]`
` `
`**Output:** [EXPECTED OUTPUT DESCRIPTION]`
` `
`**Special:** [ANY POSSIBLE SPECIAL INSTRUCTIONS]`
` `
`**Challenge input:** [SAMPLE INPUT]`
` `
If you want to solve a mini challenge you reply in that thread. Simple. Keep checking back all week as people will keep
posting challenges and solve the ones you want.
Please check other mini challenges before posting one to avoid duplications within a certain reason.
"""
def main():
pass
if __name__ == "__main__":
main()
|
f1d2f920c551650c468ce2db140b2a45bd44bbf7 | DayGitH/Python-Challenges | /DailyProgrammer/DP20141231B.py | 1,290 | 4.09375 | 4 | """
[2014-12-31] Challenge #195 [Intermediate] Math Dice
https://www.reddit.com/r/dailyprogrammer/comments/2qxrtk/20141231_challenge_195_intermediate_math_dice/
#Description:
Math Dice is a game where you use dice and number combinations to score. It's a neat way for kids to get mathematical
dexterity. In the game, you first roll the 12-sided Target Die to get your target number, then roll the five 6-sided
Scoring Dice. Using addition and/or subtraction, combine the Scoring Dice to match the target number. The number of
dice you used to achieve the target number is your score for that round. For more information, see the product page for
the game: (http://www.thinkfun.com/mathdice)
#Input:
You'll be given the dimensions of the dice as NdX where N is the number of dice to roll and X is the size of the dice.
In standard Math Dice Jr you have 1d12 and 5d6.
#Output:
You should emit the dice you rolled and then the equation with the dice combined. E.g.
9, 1 3 1 3 5
3 + 3 + 5 - 1 - 1 = 9
#Challenge Inputs:
1d12 5d6
1d20 10d6
1d100 50d6
#Challenge Credit:
Thanks to /u/jnazario for his idea -- posted in /r/dailyprogrammer_ideas
#New year:
Happy New Year to everyone!! Welcome to Y2k+15
"""
def main():
pass
if __name__ == "__main__":
main()
|
2634fb7abcbbe518b8e6687c1ce1537ff77603a2 | DayGitH/Python-Challenges | /DailyProgrammer/DP20150306C.py | 4,412 | 3.6875 | 4 | """
[2015-03-06] Challenge #204 [Hard] Addition chains
https://www.reddit.com/r/dailyprogrammer/comments/2y5ziw/20150306_challenge_204_hard_addition_chains/
#Description
An "addition chain" is a sequence of numbers that starts with 1 and where each number is the sum of two previous
numbers (or the same number taken twice), and that ends at some predetermined value.
An example will make this clearer: the sequence [1, 2, 3, 5, 10, 11, 21, 42, 84] is an addition chain for the number
84. This is because it starts with 1 and ends with 84, and each number is the sum of two previous numbers. To
demonstrate:
(chain starts as [1])
1 + 1 = 2 (chain is now [1, 2])
1 + 2 = 3 (chain is now [1, 2, 3])
2 + 3 = 5 (chain is now [1, 2, 3, 5])
5 + 5 = 10 (chain is now [1, 2, 3, 5, 10])
1 + 10 = 11 (chain is now [1, 2, 3, 5, 10, 11])
10 + 11 = 21 (chain is now [1, 2, 3, 5, 10, 11, 21])
21 + 21 = 42 (chain is now [1, 2, 3, 5, 10, 11, 21, 42])
42 + 42 = 84 (chain is now [1, 2, 3, 5, 10, 11, 21, 42, 84])
Notice that the right hand side of the equations make up the chain, and left hand side of all the equations is a sum of
two numbers that occur earlier in the chain (sometimes the same number twice).
We say that this chain is of length 8, because it took 8 additions to generate it (this is one less than the total
amount of numbers in the chain).
There are a several different addition chains of length 8 for the number 84 (another one is [1, 2, 4, 8, 16, 32, 64,
68, 84], for instance), but there are no shorter ones. This is as short as we can get.
Your task today is to try and generate addition chains of a given length and last number.
(by the way, you may think this looks similar to the Fibonacci sequence, but it's not, there's a crucial difference:
you don't just add the last two numbers of the chain to get the next number, you can add *any* two previous numbers to
get the next number. The challenge is figuring out, for each step, which two numbers to add)
#Formal inputs & outputs
##Input description
You will be given one line with two numbers on it. The first number will be the length of the addition chain you are to
generate, and the second the final number.
Just to remind you: the length of the addition chain is equal to the number of additions it took to generate it, which
is the same as **one less** than the total amount of numbers in it.
##Output description
You will output the entire addition chain, one number per line. There will be several different addition chains of the
given length, but you only need to output one of them.
Note that going by the strict definition of addition chains, they don't necessarily have to be strictly increasing.
However, any addition chain that is not strictly increasing can be reordered into one that is, so you can safely assume
that all addition chains are increasing. In fact, making this assumption is probably a very good idea!
#Examples
##Input 1
7 43
##Output 1
(one of several possible outputs)
1
2
3
5
10
20
40
43
##Input 2
9 95
##Output 2
(one of several possible outputs)
1
2
3
5
7
14
19
38
57
95
#Challenge inputs
##Input 1
10 127
##Input 2
13 743
#Bonus
19 123456
If you want *even more* of a challenge than that input, consider this: when I, your humble moderator, was developing
this challenge, my code would not be able to calculate the answer to this input in any reasonable time (even though
solutions exist):
25 1234567
If you can solve that input, you will officially have written a much better program than me!
#Notes
I would like to note that while this challenge looks very "mathy", you don't need any higher level training in
mathematics in order to solve it (at least not any more than is needed to understand the problem). There's not some
secret formula that you have to figure out. It's still not super-easy though, and a good working knowledge of
programming techniques will certainly be helpful!
In other words, in order to solve this problem (and especially the bonus), you need to be clever, but you don't need to
be a mathematician.
As always, if you have any suggestions for problems, hop on over to /r/dailyprogrammer_ideas and let us know!
"""
def main():
pass
if __name__ == "__main__":
main()
|
6f63d47fa84e4f61d0873976b9df8b40b1cbad9b | DayGitH/Python-Challenges | /DailyProgrammer/DP20171129B.py | 3,286 | 3.65625 | 4 | """
[2017-11-29] Challenge #342 [Intermediate] ASCII85 Encoding and Decoding
https://www.reddit.com/r/dailyprogrammer/comments/7gdsy4/20171129_challenge_342_intermediate_ascii85/
# Description
The basic need for a binary-to-text encoding comes from a need to communicate arbitrary binary data over preexisting
communications protocols that were designed to carry only English language human-readable text. This is why we have
things like Base64 encoded email and Usenet attachments - those media were designed only for text.
Multiple competing proposals appeared during the net's explosive growth days, before many standards emerged either by
consensus or committee. Unlike the well known Base64 algorithm, [ASCII85](https://en.wikipedia.org/wiki/Ascii85)
inflates the size of the original data by only 25%, as opposed to the 33% that Base64 does.
When encoding, each group of 4 bytes is taken as a 32-bit binary number, most significant byte first (Ascii85 uses a
big-endian convention). This is converted, by repeatedly dividing by 85 and taking the remainder, into 5 radix-85
digits. Then each digit (again, most significant first) is encoded as an ASCII printable character by adding 33 to it,
giving the ASCII characters 33 ("!") through 117 ("u").
Take the following example word "sure". Encoding using the above method looks like this:
| Text | s | u | r | e ||
|:------------|---|---|---|---|-|
| **ASCII value** | 115 | 117 | 114 | 101 ||
| **Binary value** | 01110011 | 01110101 | 01110010 | 01100101 ||
| **Concatenate** | 01110011011101010111001001100101 |
| **32 bit value** | 1,937,076,837 |
| **Decomposed by 85** | 37x85^4 | 9x85^3 | 17x85^2 | 44x85^1 | 22 |
| **Add 33** | 70 | 42 | 50 | 77 | 55 |
| **ASCII character** | F | * | 2 | M | 7 |
So in ASCII85 "sure" becomes "F*2M7". To decode, you reverse this process. Null bytes are used in standard ASCII85 to
pad it to a multiple of four characters as input if needed.
Your challenge today is to implement your own routines (not using built-in libraries, for example Python 3 has
a85encode and a85decode) to encode and decode ASCII85.
(Edited after posting, a column had been dropped in the above table going from four bytes of input to five bytes of
output. Fixed.)
# Challenge Input
You'll be given an input string per line. The first character of the line tells your to encode (`e`) or decode (`d`)
the inputs.
e Attack at dawn
d 87cURD_*#TDfTZ)+T
d 06/^V@;0P'E,ol0Ea`g%AT@
d 7W3Ei+EM%2Eb-A%DIal2AThX&+F.O,EcW@3B5\\nF/hR
e Mom, send dollars!
d 6#:?H$@-Q4EX`@b@<5ud@V'@oDJ'8tD[CQ-+T
# Challenge Output
6$.3W@r!2qF<G+&GA[
Hello, world!
/r/dailyprogrammer
Four score and seven years ago ...
9lFl"+EM+3A0>E$Ci!O#F!1
All\r\nyour\r\nbase\tbelong\tto\tus!
(That last one has embedded control characters for newlines, returns, and tabs - normally nonprintable. Those are not
literal backslashes.)
# Credit
Thank you to user /u/JakDrako who suggested this in a [recent
discussion](https://www.reddit.com/r/dailyprogrammer_ideas/comments/7df2dx/intermediate_base64_encodedecode/). If you
have a challenge idea, please share it at /r/dailyprogrammer_ideas and there's a chance we'll use it.
"""
def main():
pass
if __name__ == "__main__":
main()
|
e15d2492854c84deb355a3a6cdf689275604d114 | DayGitH/Python-Challenges | /DailyProgrammer/DP20160511B.py | 3,005 | 3.59375 | 4 | """
[2016-05-11] Challenge #266 [Intermediate] Graph Radius and Diameter
https://www.reddit.com/r/dailyprogrammer/comments/4iut1x/20160511_challenge_266_intermediate_graph_radius/
This week I'll be posting a series of challenges on graph theory. I picked a series of challenges that can help
introduce you to the concepts and terminology, I hope you find it interesting and useful.
# Description
Graph theory has a relatively straightforward way to calculate the *size* of a graph, using a few definitions:
* The eccentricity *ecc(v)* of vertex (aka node) *v* in graph *G* is the greatest distance from *v* to any other node.
* The radius *rad(G)* of *G* is the value of the smallest eccentricity.
* The diameter *diam(G)* of *G* is the value of the greatest eccentricity.
* The center of *G* is the set of nodes *v* such that *ecc(v)*=*rad(G)*
So, given a graph, we can calculate its size.
# Input Description
You'll be given a single integer on a line telling you how many lines to read, then a list of *n* lines telling you
nodes of a *directed* graph as a pair of integers. Each integer pair is the source and destination of an edge. The node
IDs will be stable. Example:
3
1 2
1 3
2 1
# Output Description
Your program should emit the radius and diameter of the graph. Example:
Radius: 1
Diameter: 2
# Challenge Input
147
10 2
28 2
2 10
2 4
2 29
2 15
23 24
23 29
15 29
15 14
15 34
7 4
7 24
14 2
14 7
14 29
14 11
14 9
14 15
34 15
34 14
34 29
34 24
34 11
34 33
34 20
29 23
29 7
29 2
29 18
29 27
29 4
29 13
29 24
29 11
29 20
29 9
29 34
29 14
29 15
18 27
18 13
18 11
18 29
27 18
27 4
27 24
4 2
4 27
4 13
4 35
4 24
4 20
4 29
13 18
13 16
13 30
13 20
13 29
13 4
13 2
24 4
24 30
24 5
24 19
24 21
24 20
24 11
24 29
24 7
11 18
11 24
11 30
11 33
11 20
11 34
11 14
20 29
20 11
20 4
20 24
20 13
20 33
20 21
20 26
20 22
20 34
22 34
22 11
22 20
9 29
9 20
21 9
21 20
21 19
21 6
33 24
33 35
33 20
33 34
33 14
33 11
35 33
35 4
35 30
35 16
35 19
35 12
35 26
30 13
30 19
30 35
30 11
30 24
16 36
16 19
16 35
16 13
36 16
31 16
31 19
5 19
19 30
19 16
19 5
19 35
19 33
19 24
12 33
12 35
12 3
12 26
26 21
26 35
6 21
6 19
1 6
8 3
8 6
3 8
3 6
3 12
3 35
33 29
29 33
14 33
29 21
# Challenge Output
Radius: 3
Diameter: 6
** NOTE ** I had mistakenly computed this for an _undirected_ graph which gave the wrong diameter. It should be 6.
"""
def main():
pass
if __name__ == "__main__":
main()
|
41f8ff8934bbb83431e4bfa998653ec20e00df3f | DayGitH/Python-Challenges | /DailyProgrammer/DP20150708B.py | 1,553 | 3.671875 | 4 | """
[2015-07-08] Challenge #222 [Intermediate] Simple Stream Cipher
https://www.reddit.com/r/dailyprogrammer/comments/3chvxy/20150708_challenge_222_intermediate_simple_stream/
# Description
Stream ciphers like [RC4](https://en.wikipedia.org/wiki/RC4) operate very simply: they have a strong psuedo-random
number generator that takes a key and produces a sequence of psuedo-random bytes as long as the message to be encoded,
which is then XORed against the plaintext to provide the cipher text. The strength of the cipher then depends on the
strength of the generated stream of bytes - its randomness (or lack thereof) can lead to the text being recoverable.
# Challenge Inputs and Outputs
Your program should have the following components:
* A psuedo-random number generator which takes a key and produces a consistent stream of psuedo-random bytes. A very
simple one to implement is the [linear congruential generator
(LCG).](https://en.wikipedia.org/wiki/Linear_congruential_generator)
* An "encrypt" function (or method) that takes a key and a plaintext and returns a ciphertext.
* A "decrypt" function (or method) that takes a key and the ciphertext and returns the plaintext.
An example use of this API might look like this (in Python):
key = 31337
msg = "Attack at dawn"
ciphertext = enc(msg, key)
# send to a recipient
# this is on a recipient's side
plaintext = dec(ciphertext, key)
At this point, `plaintext` should equal the original `msg` value.
"""
def main():
pass
if __name__ == "__main__":
main()
|
448674ed57d15065f2780c9596f4b25917a87644 | DayGitH/Python-Challenges | /DailyProgrammer/DP20180110B.py | 3,191 | 4.1875 | 4 | """
[2018-01-10] Challenge #346 [Intermediate] Fermat's little theorem
https://www.reddit.com/r/dailyprogrammer/comments/7pmt9c/20180110_challenge_346_intermediate_fermats/
#Description
Most introductionary implementations for testing the primality of a number have a time complexity of`O(n**0.5)`.
For large numbers this is not a feasible strategy, for example testing a
[400](https://en.wikipedia.org/wiki/Largest_known_prime_number) digit number.
Fermat's little theorem states:
> If p is a prime number, then for any integer a, the number `a**p − a` is an integer multiple of p.
This can also be stated as `(a**p) % p = a`
If n is not prime, then, in general, most of the numbers a < n will not satisfy the above relation. This leads to the
following algorithm for testing primality: Given a number n, pick a random number a < n and compute the remainder of
a**n modulo n. If the result is not equal to a, then n is certainly not prime. If it is a, then chances are good that n
is prime. Now pick another random number a and test it with the same method. If it also satisfies the equation, then we
can be even more confident that n is prime. By trying more and more values of a, we can increase our confidence in the
result. This algorithm is known as the Fermat test.
If n passes the test for some random choice of a, the chances are better than even that n is prime. If n passes the
test for two random choices of a, the chances are better than 3 out of 4 that n is prime. By running the test with more
and more randomly chosen values of a we can make the probability of error as small as we like.
Create a program to do Fermat's test on a number, given a required certainty. Let the power of the modulo guide you.
#Formal Inputs & Outputs
##Input description
Each line a number to test, and the required certainty.
##Output description
Return True or False
#Bonus
There do exist numbers that fool the Fermat test: numbers n that are not prime and yet have the property that a**n is
congruent to a modulo n for all integers a < n. Such numbers are extremely rare, so the Fermat test is quite reliable
in practice. Numbers that fool the Fermat test are called Carmichael numbers, and little is known about them other than
that they are extremely rare. There are 255 Carmichael numbers below 100,000,000.
There are variants of the Fermat test that cannot be fooled by these. Implement one.
# Challange
29497513910652490397 0.9
29497513910652490399 0.9
95647806479275528135733781266203904794419584591201 0.99
95647806479275528135733781266203904794419563064407 0.99
2367495770217142995264827948666809233066409497699870112003149352380375124855230064891220101264893169 0.999
2367495770217142995264827948666809233066409497699870112003149352380375124855230068487109373226251983 0.999
#Bonus Challange
2887 0.9
2821 0.9
#Futher reading
[SICP](https://mitpress.mit.edu/sicp/toc/toc.html) 1.2.6 (Testing for Primality)
[Wiki](https://en.wikipedia.org/wiki/Modular_exponentiation) Modular exponentiation
#Finally
Have a good challenge idea?
Consider submitting it to /r/dailyprogrammer_ideas
"""
def main():
pass
if __name__ == "__main__":
main()
|
45f4274945cd2b65da5e58de856f9462a1b9c48a | DayGitH/Python-Challenges | /DailyProgrammer/DP20150311B.py | 1,609 | 4.03125 | 4 | """
[2015-03-11] Challenge #205 [Intermediate] RPN
https://www.reddit.com/r/dailyprogrammer/comments/2yquvm/20150311_challenge_205_intermediate_rpn/
#Description:
My father owned a very old HP calculator. It was in reverse polish notation (RPN). He would hand me his calculator and
tell me "Go ahead and use it". Of course I did not know RPN so everytime I tried I failed.
So for this challenge we will help out young coder_d00d. We will take a normal math equation and convert it into RPN.
Next week we will work on the time machine to be able to send back the RPN of the math equation to past me so I can use
the calculator correctly.
#Input:
A string that represents a math equation to be solved. We will allow the 4 functions, use of () for ordering and thats
it. Note white space between characters could be inconsistent.
* Number is a number
* "+" add
* "-" subtract
* "/" divide
* "x" or "*" for multiply
* "(" with a matching ")" for ordering our operations
#Output:
The RPN (reverse polish notation) of the math equation.
#Challenge inputs:
Note: "" marks the limit of string and not meant to be parsed.
"0+1"
"20-18"
" 3 x 1 "
" 100 / 25"
" 5000 / ((1+1) / 2) * 1000"
" 10 * 6 x 10 / 100"
" (1 + 7 x 7) / 5 - 3 "
"10000 / ( 9 x 9 + 20 -1)-92"
"4+5 * (333x3 / 9-110 )"
" 0 x (2000 / 4 * 5 / 1 * (1 x 10))"
#Additional Challenge:
Since you already got RPN - solve the equations.
"""
def main():
pass
if __name__ == "__main__":
main()
|
b66a7ce77896bee173702cfa36b244a059777a7d | DayGitH/Python-Challenges | /DailyProgrammer/DP20151019A.py | 1,309 | 3.625 | 4 | """
[2015-10-19] Challenge #237 [Easy] Broken Keyboard
https://www.reddit.com/r/dailyprogrammer/comments/3pcb3i/20151019_challenge_237_easy_broken_keyboard/
# Description
Help! My keyboard is broken, only a few keys work any more. If I tell you what keys work, can you tell me what words I
can write?
(You should use the trusty [enable1.txt](http://norvig.com/ngrams/enable1.txt) file, or `/usr/share/dict/words` to
chose your valid English words from.)
# Input Description
You'll be given a line with a single integer on it, telling you how many lines to read. Then you'll be given that many
lines, each line a list of letters representing the keys that work on my keyboard. Example:
3
abcd
qwer
hjklo
# Output Description
Your program should emit the longest valid English language word you can make for each keyboard configuration.
abcd = bacaba
qwer = ewerer
hjklo = kolokolo
# Challenge Input
4
edcf
bnik
poil
vybu
# Challenge Output
edcf = deedeed
bnik = bikini
poil = pililloo
vybu = bubby
# Credit
This challenge was inspired by /u/ThinkinWithSand, many thanks! If you have any ideas, please share them on
/r/dailyprogrammer_ideas and there's a chance we'll use it.
"""
def main():
pass
if __name__ == "__main__":
main()
|
f8ce35aa7a18e0b7a6febbd227e0b7a16f2fd832 | DayGitH/Python-Challenges | /DailyProgrammer/DP20120629B.py | 1,232 | 4.25 | 4 | """
Implement the hyperoperator [http://en.wikipedia.org/wiki/Hyperoperation#Definition] as a function hyper(n, a, b), for
non-negative integers n, a, b.
hyper(1, a, b) = a + b, hyper(2, a, b) = a * b, hyper(3, a, b) = a ^ b, etc.
Bonus points for efficient implementations.
thanks to noodl for the challenge at /r/dailyprogrammer_ideas ! .. If you think yo have a challenge worthy for our
sub, do not hesitate to submit it there!
Request: Please take your time in browsing /r/dailyprogrammer_ideas and helping in the correcting and giving suggestions
to the problems given by other users. It will really help us in giving quality challenges!
Thank you!
"""
def hyper(n, a, b, cache):
# expect n >= 0
args = list(map(str, [n, a, b]))
if ','.join(args) in cache:
return cache[','.join(args)]
if not n:
answer = b + 1
elif n == 1:
answer = a + b
elif n == 2:
answer = a * b
elif n == 3:
answer = a ** b
elif not b:
answer = 1
else:
answer = hyper(n-1, a, hyper(n, a, b-1, cache), cache)
cache[','.join(args)] = answer
return answer
def main():
print(hyper(5, 3, 2, {}))
if __name__ == "__main__":
main()
|
5d4844d3e48faf34857dca70c6dde00d9bc948c9 | DayGitH/Python-Challenges | /DailyProgrammer/DP20170113C.py | 6,250 | 3.65625 | 4 | """
[2017-01-13] Challenge #299 [Hard] Functional Graph solving
https://www.reddit.com/r/dailyprogrammer/comments/5nr86m/20170113_challenge_299_hard_functional_graph/
This is the same problem as
[monday's](https://www.reddit.com/r/dailyprogrammer/comments/5mzr6x/20170109_challenge_298_hard_functional_maze/),
except the input format instead of being a 2d maze, is a graph of nodes and paths to their nearest neighbours.
For parsing ease, the graph is represented as one node per row, together with all of the neighbour nodes and their
distance (cost) to the anchor node. Format:
anchor node (row col) - [neighbour node (row col), distance to anchor]+
To the left of the separatting `-` are 2 numbers: the row and col indexes of an anchor/source node. To the right of
the `-` is a list that is a multiple of 3. The neighbours/destination/where-you-can-jump-from-source-to, with 3rd
number the distance/cost from source to destination.
The first 8 rows in the graph correspond to the positions of `01234567` in the original maze: The possible starts and
goals (**interests] points**) of path requests:
https://gist.github.com/Pascal-J/1fc96e62353b430eeb5f5f3d58861906
edit: oops forgot to paste this all along :(
**challenge:**
produce the length of shortest paths from every **interest point** (first 8 graph rows) to every other interest point.
You may omit the mirror path (ie. the path length from 0 to 1 is the same as 1 to 0), and omit the path to self (path
length from 2 to 2 is 0).
**sample output:**
┌─┬────────────────────────┐
│0│28 44 220 184 144 208 76│
├─┼────────────────────────┤
│1│60 212 176 136 200 92 │
├─┼────────────────────────┤
│2│252 216 176 240 36 │
├─┼────────────────────────┤
│3│48 84 64 276 │
├─┼────────────────────────┤
│4│48 40 240 │
├─┼────────────────────────┤
│5│72 200 │
├─┼────────────────────────┤
│6│264 │
└─┴────────────────────────┘
**explanation:** each row in output corresponds to the path **from** node labelled with the first column. The 2nd
column contains the lengths of paths to all destinations with index higher than **from**. The last row lists the path
length from `6` to `7`. The 2nd last row lists path length from `5` to `6 7`
These are the same answers as monday's challenge. It is not the number of "graph hops", it is the total cost (sum of
3rd column) in the graph hops.
# bonus
list the shortest path walked from node 0 (row index 0 in input gist: map index `23 141`) to node 1 (row index 1 in
input gist: maze index `35 133`). (all nodes passed through)
#bonus 2
Create a universal function (or class constructor) that can solve all of this week's challenges. This is the same as
monday's bonus, but with the benefit of hindsight, there are some important corrections to Monday's guidance:
[Djikstra](https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm) rather than Astar is the better reference algorithm.
The higher order function should produce a function that accepts as input `start, goal, reference (maze or graph)` but
it is too much to ask to create such a function that does any manipulation of those inputs. ie. The function caller
is repsonsible for providing nodes and reference in format suitable to the generated function (such as node indexes
instead of an item to look up in reference)
extra bonus: goal (and possibly start) should be possible to be lists rather than a single node.
I find the following function inputs are sufficient to solve all of this week's challenges.
1. neighbour function: from a given node, what are all of the possible valid neighbours. (for maze, this is NESW
directions that are not walls. For graph, lookup of destinations in source row)
2. distance function: The cost from going from previous node to this node. (for maze, this is constant 1 function.
For graph, it is the lookup of source and destination cost field)
3. solved function: boolean function that flags whether a path has reached a goal.
4. while function: condition to stop (or continue) search (boolean function). For monday's challenge, first solved
path is guaranteed to be shortest with djikstra due to constant distance/cost function. For wednesday's challenge,
there was no stop condition other than exhausting all directions, and excluding from further search any paths that
reach solved state. For this challenge, the first solved path is not guaranteed to have the smallest cost (even if it
has the fewest hops). More hops can possibly have a lower cummulative cost/distance.
5. return function: function that maps the final state to an output value. For this and monday's challenge, extract
the length of the solved path. For wednesday's challenge, list the goal node and its path length. For bonus 1, walk
the path backwards from goal to start.
Useful internal states for the function are to keep a "table" of node paths that include "fields" for `current node,
previous node, visited/"frontier" status` for sure, and optionally "cached" solved and path length states.
Caching length is controversial and may or may not be faster. Unlike Monday's challenge, Today's challenge can
"invalidate previously cached" costs as a longer hop but shorter cummulative cost path can replace a previously found
path. Caching may be slower (though simpler), but needs a "reupdate all costs" internal function for today's
challenge.
I suspect that caching is slower overall, and if you do bonus 1, the only time you ever need to calculate lengths are
at the end (return function), or when a collision occurs (to pick the shortest path "collided node".)
"""
def main():
pass
if __name__ == "__main__":
main()
|
8201a53e8222c3600ea8fdd966d6774386900de2 | DayGitH/Python-Challenges | /DailyProgrammer/DP20140716W.py | 647 | 3.734375 | 4 | """
[Weekly #2] Pre-coding Work
https://www.reddit.com/r/dailyprogrammer/comments/2ao9y3/weekly_2_precoding_work/
#Weekly Topic #2:
What work do you do before coding your solution? What kind of planning or design work if any do you do? How do you do
it? Paper and pencil? Draw a picture? Any online/web based tools?
Give some examples of your approach to handling the dailyprogrammer challenges and your process that occurs before you
start coding.
#Last week's Topic:
[Weekly Topic #1] (http://www.reddit.com/r/dailyprogrammer/comments/2a3pzl/weekly_1_handling_console_input/)
"""
def main():
pass
if __name__ == "__main__":
main()
|
681f48bac28f52729f440c3f2d54740d4ccac33a | DayGitH/Python-Challenges | /DailyProgrammer/DP20121018C.py | 1,694 | 3.5 | 4 | """
[10/18/2012] Challenge #104 [Hard] (Stack Attack)
https://www.reddit.com/r/dailyprogrammer/comments/11pas4/10182012_challenge_104_hard_stack_attack/
**Description:**
You are a devilish engineer designing a new programming language titled D++, which stands for a "Dijkstra++", named
after your favorite computer scientist. You are currently working on the math-operations parsing component of your
interpreter: though the language only supports [infix-notation](http://en.wikipedia.org/wiki/Infix_notation) (such as
"1 + 2 * 3"), your interpreter internals require you to represent all math strings in [reverse polish
notation](http://en.wikipedia.org/wiki/Reverse_Polish_notation) (for easier, stack-based, computing). Your goal is to
simply take a guaranteed valid infix-notation string of math operations and generate (printing it out) an equivalent
and valid reverse polish notation string.
**Formal Inputs & Outputs:**
*Input Description:*
string MathOperations - A valid string of infix math notation.
*Output Description:*
Print the converted RPN form of the given math operations string.
**Sample Inputs & Outputs:**
"1 + 2" should be printed as "1 2 +". "(1+2)*3" should be printed as "3 2 1 + *". "(6 (7 – 2)) / 3 + 9 * 4" should be
printed as "6 7 2 - * 3 / 9 4 * +".
**Notes:**
Do not get trapped in overly-complex solutions; there are formal solutions, though many ways of solving for this
problem. Check out the [Shunting Yard Algorithm](http://en.wikipedia.org/wiki/Shunting_yard_algorithm) for details on
how to convert math-operation strings (a stack of tokens) from one notation system to another.
"""
def main():
pass
if __name__ == "__main__":
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.