-
Notifications
You must be signed in to change notification settings - Fork 0
/
parth_coding.py
603 lines (435 loc) · 15.1 KB
/
parth_coding.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
###############################################################
# Here are some of my solutions to the project euler question
#
# Regarding time they can be optimized better but regarding
# readability I think I did a decent job.
#
# There are also questions here not from project euler
#
# If you are a beginner python developer... I would highly
# recommend you give these questions a chance and attempt them
# yourself.
#
###############################################################
# Q1 - n! means n × (n − 1) × ... × 3 × 2 × 1
# For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
# and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
# Find the sum of the digits in the number 100!
def factorial(num):
if num == 0:
return 1
else:
return num*(factorial(num-1))
def factorial_add(num):
total = 0
for char in str(factorial(num)):
intChar = int(char)
total+=intChar
print(total)
#Q2- The series, 11 + 22 + 33 + ... + 1010 = 10405071317.
# Find the last ten digits of the series, 11 + 22 + 33 + ... + 10001000.
def squaresOf(num1, num2):
sum=0
for i in range(num1, num2+1):
mul = 1
for j in range(0, i):
mul*=i
sum+=mul
sum2 = str(sum)
print(sum2[-10:])
# Q3 - The Fibonacci sequence is defined by the recurrence relation:
#Q3 Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.
# Hence the first 12 terms will be:
# F1 = 1
# F2 = 1
# F3 = 2
# F4 = 3
# F5 = 5
# F6 = 8
# F7 = 13
# F8 = 21
# F9 = 34
# F10 = 55
# F11 = 89
# F12 = 144
# The 12th term, F12, is the first term to contain three digits.
# What is the index of the first term in the Fibonacci sequence to contain 1000 digits?
def fibb_term():
fibbList = [1, 1]
term = 0
for i in range(0, 10000000000):
current = fibbList[i]
nexts = fibbList[i+1]
sum = current+nexts
sum_str = str(sum)
if len(sum_str) >= 1000:
break
term+=1
fibbList.append(sum)
print(term+3)
#Q4 Work out the first ten digits of the sum of the following one-hundred 50-digit numbers.
def max_sum(file):
f = open(file).read().replace('\n', '')
count = 0
start = 0
end = 50
total = 0
while(count !=100):
x = f[start:end]
intx = int(x)
total+=intx
# print(x)
start+=50
end+=50
count+=1
print(str(total)[:10])
#Q5 The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:
# 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
# Let us list the factors of the first seven triangle numbers:
# 1: 1
# 3: 1,3
# 6: 1,2,3,6
# 10: 1,2,5,10
# 15: 1,3,5,15
# 21: 1,3,7,21
# 28: 1,2,4,7,14,28
# We can see that 28 is the first triangle number to have over five divisors.
# What is the value of the first triangle number to have over five hundred divisors?
#COULD BE OPTAMIZED BETTER
import math, time
ti = time.time()
def triangle_th():
total = 0
i = 1
count=0
while (count*2 <= 500):
count=0
total+=i
i+=1
for num in range(1, int(math.sqrt(total)+1)):
if total%num==0:
count+=1
print(total)
print("Time taken(secs):",time.time()-ti)
#Q6 Pentagonal numbers are generated by the formula, Pn=n(3n−1)/2. The first ten pentagonal numbers are:
# 1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...
# It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference, 70 − 22 = 48, is not pentagonal.
# Find the pair of pentagonal numbers, Pj and Pk, for which their sum and difference are pentagonal and D = |Pk − Pj| is minimised; what is the value of D?
def binary_search(item_list,item):
first = 0
last = len(item_list)-1
found = False
while( first<=last and not found):
mid = (first + last)//2
if item_list[mid] == item :
found = True
else:
if item < item_list[mid]:
last = mid - 1
else:
first = mid + 1
return found
#Q7 A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
# a2 + b2 = c2
# For example, 32 + 42 = 9 + 16 = 25 = 52.
# There exists exactly one Pythagorean triplet for which a + b + c = 1000.
# Find the product abc.
import math, time
ti = time.time()
def pythagorean_triple():
counter=1
for i in range(counter, 500):
for j in range(counter, 500):
a_sqr = math.pow(i, 2)
b_sqr = math.pow(j, 2)
c = a_sqr+b_sqr
sqrt_c = math.sqrt(c)
sum = i+j+sqrt_c
if(sqrt_c.is_integer() and i<j and j<sqrt_c and i<sqrt_c and sum==1000):
print(i*j*sqrt_c)
counter+=1
print("Time taken(secs):",time.time()-ti)
# Q8 The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
# Find the sum of all the primes below two million.
import math, time
ti = time.time()
def ifPrime(num):
for x in range(2, int(math.sqrt(num)) + 1):
if (num % x) == 0:
return False
break
else:
return True
def sum_primes(num):
sum=0
for i in range(2, num):
if ifPrime(i):
sum+=i
print(sum)
print("Time taken(secs):",time.time()-ti)
#Q9 Consider all integer combinations of ab for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5:
# 22=4, 23=8, 24=16, 25=32
# 32=9, 33=27, 34=81, 35=243
# 42=16, 43=64, 44=256, 45=1024
# 52=25, 53=125, 54=625, 55=3125
# If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms:
# 4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125
# How many distinct terms are in the sequence generated by ab for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100?
def distinct_terms():
pow_list=[]
for i in range(2,101):
for j in range(2, 101):
pow_list.append(math.pow(i,j))
print(len(set(pow_list)))
#Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:
# 1634 = 1^4 + 6^4 + 3^4 + 4^4
# 8208 = 84 + 24 + 04 + 84
# 9474 = 94 + 44 + 74 + 44
# As 1 = 14 is not a sum it is not included.
# The sum of these numbers is 1634 + 8208 + 9474 = 19316.
# Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.
def pow_of_fours():
sum=0
for i in range(1, 1000000):
count=0
for j in str(i):
count+=math.pow(int(j),5)
if (int(count)==i and i!=1):
sum+=i
print(sum)
# q10: The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
# Find the sum of all the primes below two million.
import math
def prime(num):
for i in range(2, int(math.sqrt(num))):
if num%i==0:
return False
break
else:
return True
def sum_primes():
sum=0
for i in range(2,10):
if prime(i):
sum+=i
print(sum)
#Print frequency of characters within a string
#Google
#Output: G :2, 0:2, l:1, e:1
def CharCounter(str):
stringList = []
finalDict = {}
if len(str) < 1 : print("Sorry try again")
for i in str:
stringList.append(i)
for letter in stringList:
counted = stringList.count(letter)
finalDict[letter] = counted
print(finalDict)
# The decimal number, 585 = 10010010012 (binary), is palindromic in both bases.
# Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2.
# (Please note that the palindromic number, in either base, may not include leading zeros.)
def base10Pali(num):
divident = num
binaryList = []
final = ''
while(divident > 0):
remainder = divident % 2
divident = int(divident / 2)
strs = str(remainder)
final += strs
if final == final[::-1]:
return True
else:
return False
def SumOf():
sum = 0
for i in range(1, 1000000):
if str(i) == str(i)[::-1] and base10Pali(i):
sum += i
print(sum)
# Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.
# For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714.
# What is the total of all the name scores in the file p022_names.txt?
import string
finalList = []
def NamesOrder():
counter = 0
f = open("p022_names.txt")
cleanedNames = f.read().split(",")
cleanedNames.sort()
for name in cleanedNames:
total = 0
name = name.replace('"', '')
counter = counter + 1
for char in name:
lowerChar = char.lower()
charIndex = string.ascii_lowercase.index(lowerChar)+1
total += charIndex
finalList.append(total*counter)
print(sum(finalList))
# 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 2^1000?
import math
def Power(exponent):
addList = []
exp = math.pow(2, exponent)
exp = int(exp)
exp = str(exp)
for i in exp:
i = int(i)
addList.append(i)
print(sum(addList))
# The sum of the squares of the first ten natural numbers is,
# 12+22+...+102=385
# The square of the sum of the first ten natural numbers is,
# (1+2+...+10)2=552=3025
# Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025−385=2640.
# Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
import math
def SumOfSquares(num):
SumOf = []
addedSquare = []
for i in range(1, num+1):
sqared = math.pow(i, 2)
SumOf.append(sqared)
addedSquare.append(i)
total = sum(SumOf)
addedSum = sum(addedSquare)
sqaredSum = math.pow(addedSum, 2)
print(sqaredSum - total)
# The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832.
# Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product?
def LargestInSeries():
str = "731671765313306249192251196744265747423553491949349698352031277450632623957831801698480186947885184385861560789112949495459501737958331952853208805511125406987471585238630507156932909632952274430435576689664895044524452316173185640309871112172238311362229893423380308135336276614282806444486645238749303589072962904915604407723907138105158593079608667017242712188399879790879227492190169972088809377665727333001053367881220235421809751254540594752243525849077116705560136048395864467063244157221553975369781797784617406495514929086256932197846862248283972241375657056057490261407972968652414535100474821663704844031998900088952434506585412275886668811642717147992444292823086346567481391912316282458617866458359124566529476545682848912883142606900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450"
counter = 1
thirteenList = []
finalList = []
while(counter != len(str)):
thirteen = str[counter:13+counter]
thirteenList.append(thirteen)
counter += 1
for i in thirteenList:
total = 1
for j in i:
total *= int(j)
finalList.append(total)
print(max(finalList))
##############################################
#
# The Following coding def's are from other coding
# challenges! Not from project euler
# These questions are a bit easier in my opinion
# Great way to start with learning python
#
##############################################
# Write a Python program to get a string from a given string where all occurrences of its first char have been changed to '$', except the first char itself.
# Sample String : 'restart'
# Expected Result : 'resta$t'
def ReplaceString(str):
if len(str) < 1 : print("Too small of a string")
firstStr = str[0]
for char in str:
if char == firstStr:
replacedStr = str.replace(char, '$')
# print(char)
print(replacedStr.replace('$', firstStr, 1))
#Convert the given number to a binary
def BinaryConvert(num):
divident = num
binaryList = []
final = ''
while(divident > 0):
remainder = divident % 2
divident = int(divident / 2)
binaryList.append(remainder)
binaryList.reverse()
for num in binaryList:
final += str(num)
print(final)
# find if a string is palindorne or not
# I realized after writing this code.... has very simple solution
# By using [::-1] to reverse the string and checking
# str2 = str1[::-1]
# if str1 == str2: pallindrone
# surprisingly I used [::-1] in my code... foolish (young coding days)
import math
def Palindrone(str):
if len(str)<1 : return print("Try again")
if len(str) == 2:
if str[0] == str[1]:
return print("Palindrone")
else:
return print("Non-Palindrone")
lowerStr = str.lower()
cleanStr = lowerStr.replace(' ', '')
middle = math.ceil(len(cleanStr)/2)
firstHalf = cleanStr[0:middle]
secoundHalf = cleanStr[middle-1:len(cleanStr)][::-1]
if firstHalf == secoundHalf:
return print("Palindrone")
else:
return print("Non-Palindorne")
# Write a Python program to print all even numbers from a given numbers list in the same order and stop the printing if any numbers that come after 237 in the sequence.
# Sample numbers list :
numbers = [
386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345,
399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950, 626, 949, 687, 217,
815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81, 379, 843, 831, 445, 742, 717,
958,743, 527
]
def FindEven():
for num in numbers:
if num == 237:
print(num)
break
if num % 2 == 0:
print(num)
# With a given integral number n, write a program to generate a dictionary that contains (i, i*i) such that is an integral number between 1 and n (both included). and then the program should print the dictionary.
# Suppose the following input is supplied to the program:
# 8
# Then, the output should be:
# {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}
def ToDict(num):
dictAwn = {}
for i in range(1, num+1):
mul = i*i
dictAwn[i] = mul
print(dictAwn)
# The prime factors of 13195 are 5, 7, 13 and 29.
# What is the largest prime factor of the number 600851475143 ?
from math import sqrt
from math import ceil
finalList = []
def ifPrime(num):
for x in range(2, num):
if (num % x) == 0:
return False
break
else:
return True
def PrimeFactor(num):
primeFactors = []
for x in range(2, ceil(sqrt(num+1))):
if (num % x) == 0 and ifPrime(x):
finalList.append(x)
if finalList:
print(finalList[-1])
# A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
# Find the largest palindrome made from the product of two 3-digit numbers.
# FIXED my palindrone mistake here as seen eariler
def Palindrone(num):
strPali = str(num)
if strPali == strPali[::-1]:
return True
else:
return False
def PalindroneNum():
my_list = []
for i in range(100, 1000):
for j in range(100, 1000):
product = i * j
if str(product) == str(product)[::-1]:
my_list.append(product)
# max(my_list)
print(max(my_list))