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
d1d844be30625c6e2038e0596b19c05cf9a489fa
DarioBernardo/hackerrank_exercises
/recursion/num_decodings.py
2,241
4.28125
4
""" HARD https://leetcode.com/problems/decode-ways/submissions/ A message containing letters from A-Z can be encoded into numbers using the following mapping: 'A' -> "1" 'B' -> "2" ... 'Z' -> "26" To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into: "AAJF" with the grouping (1 1 10 6) "KJF" with the grouping (11 10 6) Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06". Given a string s containing only digits, return the number of ways to decode it. The answer is guaranteed to fit in a 32-bit integer. Example 1: Input: s = "12" Output: 2 Explanation: "12" could be decoded as "AB" (1 2) or "L" (12). Example 2: Input: s = "226" Output: 3 Explanation: "226" could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6). Example 3: Input: s = "0" Output: 0 Explanation: There is no character that is mapped to a number starting with 0. The only valid mappings with 0 are 'J' -> "10" and 'T' -> "20", neither of which start with 0. Hence, there are no valid ways to decode this since all digits need to be mapped. Example 4: Input: s = "06" Output: 0 Explanation: "06" cannot be mapped to "F" because of the leading zero ("6" is different from "06"). """ from functools import lru_cache def num_decodings(s: str): @lru_cache(maxsize=None) # This automatically implement memoisation def recursive(s: str, index=0): if index == len(s): return 1 # If the string starts with a zero, it can't be decoded if s[index] == '0': return 0 if index == len(s) - 1: return 1 answer = recursive(s, index + 1) if int(s[index: index + 2]) <= 26: answer += recursive(s, index + 2) return answer return recursive(s, 0) din = [ "234", "2101", "1201234" ] dout = [ 2, 1, 3 ] for data_in, expected_result in zip(din, dout): actual_result = num_decodings(data_in) print(f"Expected: {expected_result} Actual: {actual_result}") assert expected_result == actual_result
668c5cda04ba409fcad5811fbbe85594be6b3c57
elenaborisova/Softuniada-Hackathon
/softuniada_2021/06_the_game.py
573
4.0625
4
def get_minimum_operations(first, second): count = 0 i = len(first) - 1 j = i while i >= 0: while i >= 0 and not first[i] == second[j]: i -= 1 count += 1 i -= 1 j -= 1 return count shuffled_name = input() name = input() if not len(shuffled_name) == len(name): print('The name cannot be transformed!') else: min_operations = get_minimum_operations(shuffled_name, name) print(f'The minimum operations required to convert "{shuffled_name}" ' f'to "{name}" are {min_operations}')
a58d108cc4b7729d8345250fb6b3fbc7e067b38b
srushti-maladkar/python_methods
/lists.py
342
3.71875
4
# import __hello__ li = [1, 2, 3, 4, 5, 6,"S"] li.append(7) #takes 1 value to append print(li) li.append((8, 9, 10)) print(li) li.clear() print(li) li = [1, 2, 3, 4, 5, 6] li2 = li.copy() li.append(6) print(li, li2) print(li.count(6)) print(li.index(4)) li.insert(2, 22) print(li) li.pop(1) print(li) li.remove(22) print(li)
5d792080e230b43aa25835367606510d0bb63af7
feynmanliang/Monte-Carlo-Pi
/MonteCarloPi.py
1,197
4.21875
4
# MonteCarloPi.py # November 15, 2011 # By: Feynman Liang <[email protected]> from random import random def main(): printIntro() n = getInput() pi = simulate(n) printResults(pi, n) def printIntro(): print "This program will use Monte Carlo techniques to generate an" print "experimental value for Pi. A circle of radius 1 will be" print "inscribed in a square with side length 2. Random points" print "will be selected. Since Pi is the constant of proportionality" print "between a square and its inscribed circle, Pi should be" print "equal to 2*2*(points inside circle/points total)" def getInput(): n = input("Enter number of trials: ") return n def simulate(n): hit = 0 for i in range(n): result = simulateOne() if result == 1: hit = hit + 1 pi = 4 * float(hit) / n return pi def simulateOne(): x = genCoord() y = genCoord() distance = x*x + y*y if distance <= 1: return 1 else: return 0 def genCoord(): coord = 2*random()-1 return coord def printResults(pi, n): print "After", n, "simulations, pi was calculated to be: ", pi if __name__ == "__main__": main()
5251c5a37c2fbd8d4298810bf4b1ecb818fcda07
jambompeople/jambompeople.github.io
/pythonclass.py
238
3.859375
4
class people: def __init__(self, name, age): self.name = name self.age = age def print(self): print(self.name,self.age) Jackson = people("Jackson", 13) Jackson.name = "JD" Jackson.age = 12 Jackson.print()
119122c529770f37325bd9e50a3c7e5a9bfa4004
saridha11/python
/count sapce beg.py
112
3.71875
4
string =input() count = 0 for a in string: if (a.isspace()) == True: count+=1 print(count)
a7a45dbf67baf4b430ff38fbb50854ab8f01fa75
saridha11/python
/interval.positive.py
123
3.671875
4
def main(): a=7 b=9 for num in range(a,b+1): if num%2==0: print(num,end=" ") main()
c38ad0e4f85157fae49fbc5e86efde52e8542dbe
saridha11/python
/anagrampro.py
160
3.90625
4
def check(str1,str2): if(sorted(str1)==sorted(str2)): print("yes") else: print("no") str1=input() str2=input() check(str1,str2)
fb2117ab2600331a2f94a09c5b3c3412bcdb0cb3
saridha11/python
/swap ch.py
130
3.671875
4
def swap(): s = 'abcd' t = list(s) t[::2], t[1::2] = t[1::2], t[::2] x=''.join(t) print("badc") swap()
b52bb5f53ee3842e205131242bb3ef13df5fc8d6
shuklaham/spojpractice
/ALICESIE.py
155
3.671875
4
def main(): tc = int(raw_input()) for i in range(tc): num = int(raw_input()) if num%2 ==0: print num//2 else: print (num+1)//2 main()
5db532b280a6b04d302432c29e7d83f76c75e485
shuklaham/spojpractice
/samer08f.py
271
3.5625
4
#spoj solutions known = {1:1} def nsquares(n): if n in known: return known[n] else: c = n**2 + nsquares(n-1) known[n] = c return known[n] num = int(raw_input()) while num != 0: print nsquares(num) num = int(raw_input())
dcb748b79f6f897f88430352c0a53b873592435b
ztwu/python-demo
/classdemo.py
261
3.578125
4
class ztwu: p = 0 def __init__(self,p1): ztwu.p = p1 return def m1(self): print("m1",ztwu.p) return def m2(self, p1, p2): print(p1+p2) return def m3(self): print("m3") return
876d3e79b2c05a6e0495a27b24268d966784018d
Drishti-Jain/ai_exp
/exp1 toy problem.py
318
3.5
4
x=int(input("No. of bananas at the beginning: ")) y=int(input("Distance to be covered: ")) z=int(input("Max capacity of camel: ")) lost=0 start=x for i in range(y): while start>0: start=start-z if start==1: lost=lost-1 lost=lost+2 lost=lost-1 start=x-lost if start==0: break print(start)
83c601b56a12f48a2ad1c73646eab2f9a9c71a03
c2lyh/leetcode
/longest_common_prefix.py
843
4.0625
4
''' Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". Example 1: Input: ["flower","flow","flight"] Output: "fl" Example 2: Input: ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings. ''' class Solution: def longestCommonPrefix(self, strs) -> str: if strs == []: return '' min_str = min([len(i) for i in strs]) prefix = '' for index in range(min_str): if len(set([j[index] for j in strs])) == 1: prefix += strs[0][index] else: break print(prefix) return prefix if __name__ == '__main__': b = ["flower", "flow", "flight"] a = Solution() a.longestCommonPrefix(b)
cbfd4dde0f5203f05c73fc790b93d7c4a10edcd6
jsbarbosa/MonitoriaMetodosComputacionales
/Ejercicios/derivadas.py
2,668
3.765625
4
# -*- coding: utf-8 -*- """ Created on Wed Aug 17 19:43:58 2016 @author: Juan """ # imports required modules import matplotlib.pyplot as plt import numpy as np # sets the functions and their derivatives functions = [np.cos, np.exp] # example functions derivatives = [np.sin, np.exp] # exact derivatives, minus sign in sine will later be introduced functions_labels = ["$\cos x$", "$e^x$"] # LaTex representation of the functions # sets the positions to be evaluated, differents widths and method used positions = [0.1, 10, 100] widths = [10**(-i) for i in range(1, 12)] methods = ["Forward", "Central"] def differentiation(method, function, position, width): """ Method that calculates a derivative using central or forward differences formula. """ def central(f, t, h): return (f(t+h/2.) - f(t-h/2.))/h def forward(f, t, h): return (f(t+h)-f(t))/h if method == "Forward": return forward(function, position, width) elif method == "Central": return central(function, position, width) fig = plt.figure(figsize=(10, 5)) # creates figure ax = fig.add_axes([0.1, 0.1, 0.55, 0.8]) # makes up enough space for legend for method in methods: for (function, derivative, f_label) in zip(functions, derivatives, functions_labels): # usefull to interate over various elements of different lists, arrays, tuples, etc for position in positions: log_error = [] # sets up a buffer to store values for width in widths: result = differentiation(method, function, position, width) # calculates derivative exact = derivative(position) if f_label == "$\cos x$": # includes minus sign of sine derivative exact *= -1 error = abs((result-exact)/exact) error = np.log10(error) log_error.append(error) # stores the value text = method + " " + f_label + r", $x=" + str(position) + r"$" # sets the text to be shown at the legend # plots different lines depending on the method used if method == "Forward": style = "-" else: style = "--" ax.plot(np.log10(widths), log_error, style, label = text) # makes the plot # additional plot data ax.legend(loc='upper left', bbox_to_anchor=(1.02, 1)) ax.set_xlabel("$\log_{10}h$") ax.set_ylabel("$\log_{10}\epsilon$") plt.grid() # includes a grid plt.show() # shows the plot
adf1a8f9da44ef3590068589a9e68d5413e354c9
karthikBalasubramanian/MapReduceDesignPatterns
/code/mapper_inverted_index.py
1,359
4.03125
4
#!/usr/bin/python # in Lesson 3. The dataset is more complicated and closer to what you might # see in the real world. It was generated by exporting data from a SQL database. # # The data in at least one of the fields (the body field) can include newline # characters, and all the fields are enclosed in double quotes. Therefore, we # will need to process the data file in a way other than using split(","). To do this, # we have provided sample code for using the csv module of Python. Each 'line' # will be a list that contains each field in sequential order. # # In this exercise, we are interested in the field 'body' (which is the 5th field, # line[4]). The objective is to count the number of forum nodes where 'body' either # contains none of the three punctuation marks: period ('.'), exclamation point ('!'), # question mark ('?'), or else 'body' contains exactly one such punctuation mark as the # last character. There is no need to parse the HTML inside 'body'. Also, do not pay # special attention to newline characters. import string import re import csv reader = csv.reader(sys.stdin, delimiter='\t') for line in reader: words = re.findall(r"[\w']+", line[4]) words = map(lambda x: x.lower(), words) # if "fantastically" in words: # writer.writerow(line) for word in words: print word, '\t', line[0]
9e7d64fbc8fd69a5d56e3f65a057a2a3ce08da27
revanth465/Algorithms
/Searching Algorithms.py
1,403
4.21875
4
# Linear Search | Time Complexity : O(n) import random def linearSearch(numbers, find): for i in numbers: if(i==find): return "Found" return "Not Found" numbers = [1,3,5,23,5,23,34,5,63] find = 23 print(linearSearch(numbers,find)) # Insertion Sort | Time Complexity : O(N^2) def insertionSort(numbers): i = 2 while(i <= len(numbers)): j = i-1 while( j > 0 ): if(numbers[j] < numbers[j-1]): temp = numbers[j-1] numbers[j-1] = numbers[j] numbers[j] = temp j -= 1 else: break i += 1 return numbers # Binary Search | Time Complexity : O(logN) | With Insertion Sort : O(N^2) def binarySearch(): # Let's build a list of random numbers and a random value to find in the list. numbers = [random.randint(1,21) for i in range(10)] find = random.randint(1,21) numbers = insertionSort(numbers) low = 0 high = len(numbers) -1 while(low <= high): middle = (low + high) /2 if(numbers[middle] == find): return "Number Found" elif(find < numbers[middle]): high = middle - 1 else: low = middle + 1 return "Number Not Found" print(binarySearch())
18d8ac2957545f1c72ddb30ce917fa52be6f3b81
OlegZhdanoff/python_basic_07_04_20
/lesson_1-1.py
553
3.9375
4
var_str = 'hello' var_int = 5 var_float = 3.2 print('String = ', var_str, '\nInteger = ', var_int, '\nFloat = ', var_float) random_str = input('Введите произвольную строку\n') random_int = input('Введите произвольное целое число\n') random_float = input('Введите произвольное дробное число\n') print('Ваша строка = ', random_str, '\nВаше целое число = ', int(random_int), '\nВаше дробное число = ', float(random_float))
b6125617c91172dc3fb3b4c784e30d03d472eaeb
OlegZhdanoff/python_basic_07_04_20
/lesson_7/lesson_7_3.py
1,963
3.515625
4
"""3. Реализовать программу работы с органическими клетками. Необходимо создать класс Клетка. В его конструкторе инициализировать параметр, соответствующий количеству клеток (целое число). В классе должны быть реализованы методы перегрузки арифметических операторов: сложение (add()), вычитание (sub()), умножение (mul()), деление (truediv( )).Данные методы должны применяться только к клеткам и выполнять увеличение, уменьшение, умножение и обычное (не целочисленное) деление клеток, соответственно. В методе деления должно осуществляться округление значения до целого числа. """ class Cell: def __init__(self, num: int): self.qty = num def __add__(self, other): return Cell(self.qty + other.qty) def __sub__(self, other): tmp = self.qty - other.qty if tmp > 0: return Cell(tmp) else: print('Клеток не может стать меньше нуля') return Cell(0) def __mul__(self, other): return Cell(self.qty * other.qty) def __truediv__(self, other): return Cell(round(self.qty / other.qty)) def make_order(self, num): tmp_str = '' for i in range(self.qty // num): tmp_str += '*' * num if i < (self.qty // num - 1): tmp_str += '\n' if self.qty % num: tmp_str += '\n' + ('*' * (self.qty % num)) return tmp_str c1 = Cell(8) c2 = Cell(3) c3 = c1 / c2 print(c1.make_order(3)) print(c3.qty)
e9c965347e640a3dc9c568f854d7840faa5ff31a
OlegZhdanoff/python_basic_07_04_20
/lesson_2_2.py
809
4.21875
4
""" 2. Для списка реализовать обмен значений соседних элементов, т.е. Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д. При нечетном количестве элементов последний сохранить на своем месте. Для заполнения списка элементов необходимо использовать функцию input(). """ my_list = [] el = 1 i = 0 while el: el = input('Введите элемент списка\n') if el: my_list.append(el) print('Ваш список: ', my_list) while i < len(my_list)-1: my_list[i], my_list[i+1] = my_list[i+1], my_list[i] i += 2 print('Результат: ', my_list)
a1e6886e32335718cb3de5274dc0380f28c01c0b
OlegZhdanoff/python_basic_07_04_20
/lesson_1_3.py
198
3.671875
4
n = int(input('Введите число n\n')) nn = int(str(n) + str(n)) nnn = int(str(n) + str(n) + str(n)) result = n + nn + nnn print('Сумма чисел', n, nn, nnn, 'равна', result)
d4488bb782387cd7a639961df403754416a1022f
MigrantJ/sea-c34-python
/students/MaryDickson/session04/exceptions.py
709
3.984375
4
# questions about the exceptions section in slides 4 list = [0, 1, 4, 8, 100, 1001] def printitem(list, num): """ Can I throw a warning message if number not in range? """ try: return list[num] except: return(u"oops not long enough") finally: list.append(34) print list print printitem(list, 2) print printitem(list, 10) print list def make_name_error(name): ''' say hello given a name (string) ''' try: print "Hello %s" % name except NameError: print "Oops, try that again with a string this time" finally: return "program finished" print make_name_error(Mary) # name error print make_name_error("Mary")
1fe9ccebdbd43d3542d2b84d40aff034a96eb035
danevd-TCD/leetcode
/Medium/2-Add Two Numbers.py
2,276
3.8125
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]: list1 = [] #array for linked list 1 list2 = [] #array for linled list 2 current1 = l1 current2 = l2 print(current1) #print(current.next) #current = current.next #print(current.val) #list 1 while current1.next != None: #print("Current val: " + str(current1.val)) list1.append(current1.val) current1 = current1.next list1.append(current1.val) #list 2 while current2.next != None: #print("Current val: " + str(current2.val)) list2.append(current2.val) current2 = current2.next list2.append(current2.val) #reverse list 1: end1 = len(list1) -1 str1 = "" for i in range(end1,-1,-1): str1 += str(list1[i]) #reverse list 2: end2 = len(list2) -1 str2 = "" for j in range(end2,-1,-1): str2 += str(list2[j]) #sum and convert sum to string outputSum = int(str1) + int(str2) outputString = str(outputSum) #reverse the outputString endStringLen = len(outputString) - 1 reversedOutput = "" for k in range(endStringLen, -1, -1): reversedOutput += str(outputString[k]) print(reversedOutput) #ListNode{val: 2, next: ListNode{val: 4, next: ListNode{val: 3, next: None}}} current = ListNode() for i in range(len(reversedOutput)): current = current.next current.val = reversedOutput[i] #this works #print(current.val) #as evidenced by this: 7, 0, 8 #issue is somewhere here current.next = ListNode() print(current) #create list
c31b9941a741feb5f72068044ec410b1ff11532e
KevinFrankhouser/PythonProjects
/Encapsulation.py
509
3.734375
4
class Car: def __init__(self, speed, color): self.__speed = speed self._color = color def set_speed(self, value): self.__speed = value def get_speed(self): return self.__speed def set_color(self, value): self._color = value def get_color(self): return self._color ford = Car(200, 'red') honda = Car(250, 'blue') audi = Car(300, 'black') ford.set_speed(300) print(ford.get_speed()) print(ford.get_color())
ed2837d7ad12ce569757025fbb8e849d5d9914bd
YoonKiBum/programmers
/Level1/68644.py
302
3.6875
4
from itertools import combinations def solution(numbers): answer = [] for combination in combinations(numbers, 2): x = int(combination[0]) y = int(combination[1]) answer.append(x+y) answer = set(answer) answer = list(answer) answer.sort() return answer
6265b2b09f6ce1fa39701aa34d95723dd69c310f
abhnvkmr/hackerRank
/algorithms/anagram.py
682
3.640625
4
# HackerRank - Algorithms - Strings # Anagrams def shifts_required(input_str): shifts = 0 if len(input_str) % 2: return -1 a, b = input_str[: len(input_str) // 2], input_str[len(input_str) // 2 :] dict = {} dicta = {} for i in b: if i in dict.keys(): dict[i] += 1 else: dict[i] = 1 dicta[i] = 0 for i in a: if i in dicta.keys(): dicta[i] += 1 else: dicta[i] = 1 for i in dict.keys(): if dict[i] > dicta[i]: shifts += dict[i] - dicta[i] return shifts t = int(input()) for _ in range(t): print(shifts_required(input()))
c7bb7446021d6d43b02e561dd4e663248e76f79a
abhinavchinna/complex--number-calculator
/code.py
1,802
3.5
4
# -------------- import pandas as pd import numpy as np import math #Code starts here class complex_numbers: def __init__(self,a,b): self.real=a self.imag=b def __repr__(self): if self.real == 0.0 and self.imag == 0.0: return "0.00" if self.real == 0: return "%.2fi" % self.imag if self.imag == 0: return "%.2f" % self.real return "%.2f %s %.2fi" % (self.real, "+" if self.imag >= 0 else "-", abs(self.imag)) def __add__(self,other): ans=complex_numbers((self.real+other.real),(self.imag+other.imag)) return ans def __sub__(self,other): ans=complex_numbers((self.real-other.real),(self.imag-other.imag)) return ans def __mul__(self,other): ans=complex_numbers((self.real*other.real-self.imag*other.imag),(self.imag*other.real+self.real*other.imag)) return ans def __truediv__(self,other): a1=self.real b1=self.imag a2=other.real b2=other.imag a=(a1*a2+b1*b2)/(a2**2 + b2**2) b=(b1*a2-a1*b2)/(a2**2 + b2**2) return complex_numbers(a,b) def absolute(self): ans=math.sqrt(self.real**2 + self.imag**2) return ans def argument(self): ans=math.degrees(math.atan2(self.imag,self.real)) return ans def conjugate(self): if self.imag<0: return complex_numbers(self.real,abs(self.imag)) return complex_numbers(self.real,-(self.imag)) comp_1=complex_numbers(3,5) comp_2=complex_numbers(4,4) comp_sum=comp_1+comp_2 comp_diff=comp_1-comp_2 comp_prod=comp_1*comp_2 comp_quot=comp_1/comp_2 comp_abs=comp_1.absolute() comp_conj=comp_1.conjugate() comp_arg=comp_1.argument()
6c82627929fa81cdd0998309ec049b8ef4d7bc86
Helen-Sk-2020/JtBr_Arithmetic_Exam_Application
/Arithmetic Exam Application/task/arithmetic.py
2,032
4.125
4
import random import math def check_input(): while True: print('''Which level do you want? Enter a number: 1 - simple operations with numbers 2-9 2 - integral squares of 11-29''') x = int(input()) if x == 1 or x == 2: return x break else: print('Incorrect format.') def check_answer(answer): while True: x = input() if x.strip('-').isdigit(): if int(x) == answer: print('Right!') return 'Right!' else: print('Wrong!') break else: print('Incorrect format.') def simple_operations(): total = 0 a = random.randint(2, 9) b = random.randint(2, 9) operator = random.choice('+-*') print(f"{a} {operator} {b}") if operator == "+": total = int(a) + int(b) elif operator == "-": total = int(a) - int(b) elif operator == "*": total = int(a) * int(b) return total def integral_squares(): num = random.randint(11, 29) print(num) square = math.pow(num, 2) return square def save_result(level, n): print("What is your name?") name = input() if level == 1: level_description = 'simple operations with numbers 2-9' elif level == 2: level_description = 'integral squares of 11-29' results = open('results.txt', 'a', encoding='utf-8') results.write(f'{name}: {n}/5 in level {level} ({level_description})') results.close() print('The results are saved in "results.txt".') level = check_input() counter = n = 0 while counter < 5: if level == 1: result = simple_operations() elif level == 2: result = integral_squares() if check_answer(result) == 'Right!': n += 1 counter += 1 print(f"Your mark is {n}/5. Would you like to save the result?") user_answer = str(input()) if user_answer.lower() == 'yes' or user_answer == 'y': save_result(level, n)
c123ff4f0b25cab5630f2b7fb6cb3243cd9abbe0
Helen-Sk-2020/JtBr_Arithmetic_Exam_Application
/Topics/Writing files/Theory/main.py
225
3.765625
4
names = ['Kate', 'Alexander', 'Oscar', 'Mary'] name_file = open('names.txt', 'w', encoding='utf-8') # write the names on separate lines for name in names: name_file.write(name + '\n') name_file.close() print(name_file)
f35a379b82ba3181da4dbfeda3df222ae24d1370
zenefits-brody/liaoxuefeng-python
/lambda-function.py
220
3.921875
4
""" https://www.liaoxuefeng.com/wiki/1016959663602400/1017451447842528 请用匿名函数改造下面的代码 """ def is_odd(n): return n % 2 == 1 L = list(filter(lambda x: x % 2 == 1, range(1, 20))) print(L)
fc09097d3be62c80b2072cba63db8e4fbb5650d3
Qasim-Habib/Rush-Hour
/rush_hour.py
27,924
3.828125
4
import sys from queue import PriorityQueue import copy import time def list_to_string(arr): #convert list to string str_node='' for i in range(0, Puzzle.size_table): for j in range(0, Puzzle.size_table): str_node += arr[i][j] return str_node def print_array(ar): #print the array in the form of matrix print('\n'.join([''.join(['{:5}'.format(item) for item in row]) for row in ar])) class Node: # constructor construct the node def __init__(self,state_of_puzzle,parent,depth,array_puzle,herstic_val,move): self.state_of_puzzle=state_of_puzzle #dictionary that save to every car thw location of the car in the array(puzle)and the type of the car and the type of the move self.parent=parent #save pionter to the parent self.depth=depth # save the depth self.array_puzle=array_puzle #save the array self.herstic_val=herstic_val self.move=move #save the last move that by this move we arrive to this node def __lt__(self, other): #the priorty quiue use this function to compare between the nodes that found in the quiue """ :param other: compare :return: 0 """ return 0 def goal_state(self): #if the red car found in the end of the third row so the red car can exit and we arrive to the solution return self.array_puzle[2][5]=='X' def score(self,herstic_id): #compute the f value of the node in according to the algortim we use it to find the solution if herstic_id=='iterative_deepning' or herstic_id=='DFS': return -self.depth elif herstic_id=='BFS': return self.depth elif herstic_id==9: return self.herstic_val elif herstic_id==3: return self.herstic_val-self.depth return self.depth+self.herstic_val #function that take the car that we want to move it and take the direction and the amount of move def create_new_node(self, cur_car, sum, direction,herstic_id): new_array_board = copy.deepcopy(self.array_puzle) #create a new array to the new node move=[] move.append(self.array_puzle[cur_car.index[0]][cur_car.index[1]]) move.append(direction) move.append(str(sum)) #save the last move new_dict_car = dict(self.state_of_puzzle) #create new dictionary index = cur_car.index new_location_car = self.array_puzle[index[0]][index[1]] if cur_car.type_of_move==0: #according to the direction we change the array and change the location of the car if direction=='L': for i in range(0,cur_car.type_of_car+2): new_array_board[index[0]][index[1]-sum+i]= new_array_board[index[0]][index[1]+i] new_array_board[index[0]][index[1] + i]='.' index=(index[0],index[1]-sum) elif direction=='R': for i in range(cur_car.type_of_car+1,-1,-1): new_array_board[index[0]][index[1]+sum+i]= new_array_board[index[0]][index[1]+i] new_array_board[index[0]][index[1] + i]='.' index = (index[0], index[1] + sum) else: if direction=='U': for i in range(0,cur_car.type_of_car+2): new_array_board[index[0]-sum+i][index[1]]= new_array_board[index[0]+i][index[1]] new_array_board[index[0]+i][index[1]]='.' index=(index[0]-sum,index[1]) else: for i in range(cur_car.type_of_car+1,-1,-1): new_array_board[index[0]+sum+i][index[1]]= new_array_board[index[0]+i][index[1]] new_array_board[index[0]+i][index[1]]='.' index=(index[0]+sum,index[1]) str_newarray=list_to_string(new_array_board) if herstic_id=='iterative_deepning': if str_newarray not in Iterative_deepning.visited: depth = self.depth + 1 car = Car(index, cur_car.type_of_car, cur_car.type_of_move) new_dict_car[new_location_car] = car new_parent = self new_node = Node(new_dict_car, new_parent, depth, new_array_board, None, move) new_node.herstic_val=0 Iterative_deepning.waiting_nodes.put((new_node.score('iterative_deepning'), new_node)) else: #if we visit the new node in the past so No need to go through it again if str_newarray not in Puzzle.visited: depth = self.depth + 1 #Puzzle.number_of_nodes += 1 car = Car(index, cur_car.type_of_car, cur_car.type_of_move) new_dict_car[new_location_car] = car new_parent = self new_node = Node(new_dict_car, new_parent, depth, new_array_board, None, move) if herstic_id==4: val_herstic = new_node.calc_herustic_valtemp() else: val_herstic = new_node.calc_herustic_val(herstic_id) new_node.herstic_val = val_herstic Puzzle.add_to_waitlist(new_node,herstic_id) def how_to_move(self,cars_can_move): #function that take the cars the can move and compute to every car can move the direction of the move mov_car = {} for key in cars_can_move: curent_car = self.state_of_puzzle[key] location = curent_car.index count = curent_car.type_of_car + 2 moves=(0,0) if curent_car.type_of_move == 0: #if the type of the move is horizontal if location[1] - 1 >= 0 and self.array_puzle[location[0]][location[1] - 1] == '.': moves=(1,moves[1]) #the car can move left L1 if location[1] + count< Puzzle.size_table and self.array_puzle[location[0]][location[1]+count]=='.': moves=(moves[0],1) #the car can move right R1 mov_car[key]=moves #save the move to this car in the dictionary (the key is the car ) elif curent_car.type_of_move==1:#if the type of the move is vertical if location[0] - 1 >= 0 and self.array_puzle[location[0]-1][location[1]] == '.': moves=(1,moves[1]) #the car can move up U1 if location[0] + count < Puzzle.size_table and self.array_puzle[location[0]+count][location[1]]=='.': moves=(moves[0],1)#the car can move down D1 mov_car[key]=moves return mov_car #return the dictionary the key is the cars and the values is the moves def calc_successors(self,herstic_id):#compute the children of the node succesors = [] for succ in self.state_of_puzzle: location = self.state_of_puzzle[succ].index suc_car = self.state_of_puzzle[succ] if suc_car.type_of_move == 0: # if no find space near the car so the car can't move so we don't save it in the list if location[1] % 6 == 0: if self.array_puzle[location[0]][location[1] + suc_car.type_of_car + 2] != '.': continue elif (location[1] + suc_car.type_of_car + 1) % 6 == 5: if self.array_puzle[location[0]][location[1] - 1] != '.': continue elif self.array_puzle[location[0]][location[1] + suc_car.type_of_car + 2] != '.' and \ self.array_puzle[location[0]][location[1] - 1] != '.': continue succesors.append(succ) else: if location[0] % 6==0: if self.array_puzle[location[0]+suc_car.type_of_car+2][location[1]] != '.': continue elif (location[0]+suc_car.type_of_car+1)%6==5: if self.array_puzle[location[0]-1][location[1]]!='.': continue elif self.array_puzle[location[0]+suc_car.type_of_car+2][location[1]] != '.' and self.array_puzle[location[0]-1][location[1]]!='.': continue succesors.append(succ) mov_car = self.how_to_move(succesors) for key in succesors: curent_car = self.state_of_puzzle[key] if curent_car.type_of_move==0: if mov_car[key][0]>0: self.create_new_node(curent_car, mov_car[key][0], 'L',herstic_id) if mov_car[key][1]>0: self.create_new_node(curent_car, mov_car[key][1], 'R',herstic_id) elif curent_car.type_of_move==1: if mov_car[key][0]>0: self.create_new_node(curent_car, mov_car[key][0], 'U',herstic_id) if mov_car[key][1]>0: self.create_new_node(curent_car, mov_car[key][1], 'D',herstic_id) def find_blocking_cars(self,blocking_cars,diff_locationcar):#function that take the cars that block the red car the cars that found in the third row after the red car #and the function finds if there are cars that block the path of the other cars that block the path of the red car if yes we save them and return them for key in diff_locationcar: if key=='X': continue move=diff_locationcar[key] cur_car=self.state_of_puzzle[key] for i in range(cur_car.index[0],cur_car.index[0]-move[0]-1): if i<0: break elif self.array_puzle[i][cur_car.index[1]] in blocking_cars or self.array_puzle[i][cur_car.index[1]]=='.': continue else: blocking_cars.append(self.array_puzle[i][cur_car.index[1]]) for i in range(cur_car.index[0],cur_car.index[0]+cur_car.type_of_car+2+move[1]): if i>Puzzle.size_table: break elif self.array_puzle[i][cur_car.index[1]] in blocking_cars or self.array_puzle[i][ cur_car.index[1]]=='.': continue else: blocking_cars.append(self.array_puzle[i][cur_car.index[1]]) return blocking_cars def calc_herustic_val(self,herstic_id): #the function compute the herstic value of the node index = self.state_of_puzzle['X'].index #save the location of the red car if index[0] == 2 and index[1] == Puzzle.size_table - 2: #if the red car found in the end of the third row so the red car can exit and return 0 return 0 new_location = [] diff_locationcar={} new_location.append('X') #we save the cars that block the path of the red car also the red car sum = Puzzle.size_table - 1 - index[1] - 1 for i in range(index[1],Puzzle.size_table): move=(0,0) if self.array_puzle[index[0]][i] not in new_location and self.array_puzle[index[0]][i]!='.': if self.array_puzle[index[0]][i]!='X'and self.state_of_puzzle[self.array_puzle[index[0]][i]].type_of_move==0: return sys.maxsize #faluire if there is car that move horizontal that found after the red car so the red car can't exit car=self.state_of_puzzle[self.array_puzle[index[0]][i]] diff = index[0] - car.index[0] num_down = car.type_of_car + 2 - abs(diff) - 1 if num_down + 1 <= car.index[0] % 6: #check if the car the block the path of the red car can move up and open the path to the red car move=(num_down+1,move[1]) diff_locationcar[self.array_puzle[index[0]][i]] = move num_up = car.type_of_car + 2 - num_down - 1 if num_up + 1 + car.index[0] + car.type_of_car + 1 <= Puzzle.size_table - 1:#check if the car the block the path of the red car can move down and open the path to the red move=(move[0],num_up+1) diff_locationcar[self.array_puzle[index[0]][i]] = move if move[0]<=move[1] and move[0]!=0: sum+=move[0] elif move[1]<move[0] and move[1]!=0: sum+=move[1] new_location.append(self.array_puzle[index[0]][i]) if herstic_id==1 or herstic_id==9: new_location=self.find_blocking_cars(new_location,diff_locationcar) if herstic_id==3: return sum return len(new_location) class Iterative_deepning:#class that run the algorthim iterative deepning visited = {} waiting_nodes = PriorityQueue() def iterative_deepning(root): size_table = 6 number_of_nodes=0 sum_herustic=0 start = time.time() for i in range(0,sys.maxsize): Iterative_deepning.waiting_nodes = PriorityQueue() Iterative_deepning.visited={} Iterative_deepning.waiting_nodes.put((root.score('iterative_deepning'), root)) while not Iterative_deepning.waiting_nodes.empty(): cur_node = Iterative_deepning.waiting_nodes.get()[1] str_node = list_to_string(cur_node.array_puzle) while str_node in Iterative_deepning.visited and not Iterative_deepning.waiting_nodes.empty(): cur_node = Iterative_deepning.waiting_nodes.get()[1] str_node = list_to_string(cur_node.array_puzle) if cur_node.depth>i: continue Iterative_deepning.visited[str_node] = 1 number_of_nodes += 1 sum_herustic += cur_node.score('iterative_deepning') if time.time() - start>80: print('failed') return number_of_nodes,herstic_id,0,sum_herustic/number_of_nodes,number_of_nodes**(1/cur_node.depth),cur_node.depth,cur_node.depth,cur_node.depth,80 elif cur_node.goal_state(): timeExe = time.time() - start print("Time of execution:", timeExe) if timeExe <= 80: temp_node = cur_node last_move = [] last_move.append('X') last_move.append('R') a = 2 last_move.append(str(a)) list_moves = [] count = 1 while temp_node.parent != None: str_move = temp_node.move if str_move[0] == last_move[0] and str_move[1] == last_move[1]: count += 1 else: str1 = last_move[0] + last_move[1] + str(count) list_moves.append(str1) count = 1 last_move = str_move temp_node = temp_node.parent if last_move != None: str1 = last_move[0] + last_move[1] + str(count) list_moves.append(str1) temp_node = cur_node max_depth = None min_depth = None size = 0 sum_depth = 0 while not Iterative_deepning.waiting_nodes.empty(): temp_node = Iterative_deepning.waiting_nodes.get()[1] size += 1 sum_depth += temp_node.depth if max_depth == None or max_depth < temp_node.depth: max_depth = temp_node.depth if min_depth == None or min_depth > temp_node.depth: min_depth = temp_node.depth avg_depth = 0 if size == 0: avg_depth = 0 min_depth=cur_node.depth max_depth=cur_node.depth else: avg_depth = sum_depth / size count = len(list_moves) for i in range(count - 1, -1, -1): print(list_moves[i], end=" ") print('\n number of visited nodes:', number_of_nodes) print(' Penetrance: ', cur_node.depth / number_of_nodes) print('avg H value: ', sum_herustic / number_of_nodes) print('EBF: ', number_of_nodes ** (1 / cur_node.depth)) print('Max depth: ', max_depth) print('Min depth: ', min_depth) print('Average depth: ', avg_depth) return number_of_nodes,'iterative_deepning',cur_node.depth/number_of_nodes,sum_herustic/number_of_nodes,number_of_nodes ** (1 / cur_node.depth),max_depth,min_depth,avg_depth,timeExe else: print('failed') else: cur_node.calc_successors('iterative_deepning') class Car: def __init__(self,index,type_of_car,type_of_move):#constructor that build the car self.index=index #the location of the car self.type_of_car=type_of_car # 1 if the car Occupying three slots and 0 if the car Occupying two slots self.type_of_move=type_of_move # 0 if the car move horizontal and 1 if the car move vertical class Puzzle: size_table = 6 number_of_nodes = 0 visited = {} sum_herustic=0 waiting_nodes = PriorityQueue() def search(self,herstic_id): start = time.time() while not self.waiting_nodes.empty(): cur_node = self.waiting_nodes.get()[1] str_node = list_to_string(cur_node.array_puzle) while str_node in self.visited and not self.waiting_nodes.empty(): cur_node = self.waiting_nodes.get()[1] str_node = list_to_string(cur_node.array_puzle) self.visited[str_node] = 1 self.number_of_nodes+=1 self.sum_herustic+=cur_node.herstic_val if cur_node.goal_state(): timeExe = time.time() - start print("Time of execution:", timeExe) if timeExe<=time_limit: temp_node=cur_node last_move=[] last_move.append('X') last_move.append('R') a=2 last_move.append(str(a)) list_moves=[] count=1 while temp_node.parent!= None: str_move=temp_node.move if str_move[0]==last_move[0] and str_move[1]==last_move[1]: count+=1 else: str1=last_move[0]+last_move[1]+str(count) list_moves.append(str1) count=1 last_move=str_move temp_node = temp_node.parent if last_move!=None: str1 = last_move[0] + last_move[1] + str(count) list_moves.append(str1) temp_node=cur_node max_depth=None min_depth=None size=0 sum_depth=0 while not self.waiting_nodes.empty(): temp_node = self.waiting_nodes.get()[1] size+=1 sum_depth+=temp_node.depth if max_depth==None or max_depth<temp_node.depth: max_depth=temp_node.depth if min_depth==None or min_depth>temp_node.depth: min_depth=temp_node.depth avg_depth=0 if size==0: avg_depth=0 max_depth=cur_node.depth min_depth=cur_node.depth else: avg_depth=sum_depth/size count=len(list_moves) temp_list=[] for i in range(count-1,-1,-1): print(list_moves[i], end=" ") temp_list.append(list_moves[i]) with open("solution.txt", "a") as my_file: my_file.write(" ".join(temp_list)+' ' ) my_file.write("\n") penetrance=cur_node.depth/self.number_of_nodes avg_h_value=self.sum_herustic/self.number_of_nodes ebf=self.number_of_nodes**(1/cur_node.depth) print('\n number of visited nodes:',self.number_of_nodes) print('herstic_id: ', herstic_id) print(' Penetrance: ',penetrance) print('avg H value: ',avg_h_value) print('EBF: ',ebf) print('Max depth: ',max_depth) print('Min depth: ', min_depth) print('Average depth: ',avg_depth) return self.number_of_nodes,herstic_id,penetrance,avg_h_value,ebf,max_depth,min_depth,avg_depth,timeExe else: with open("solution.txt", "a") as my_file: my_file.write("failed\n") print('failed') return self.number_of_nodes,herstic_id,0,self.sum_herustic/self.number_of_nodes,self.number_of_nodes**(1/cur_node.depth),cur_node.depth,cur_node.depth,cur_node.depth,10 else: cur_node.calc_successors(herstic_id) @staticmethod def add_to_waitlist(current_node,herstic_id): Puzzle.waiting_nodes.put((current_node.score(herstic_id), current_node)) def init_the_game(self, node_text,herstic_id): #create the init board the root cur_cars = {} array_board = list() for i in range(0, self.size_table): array_board.append(list(node_text[i * self.size_table:i * self.size_table + self.size_table])) for i in range(0, self.size_table): for j in range(0, self.size_table): if array_board[i][j] == '.': continue if ('A' <= array_board[i][j] <= 'K' or array_board[i][j] == 'X') and array_board[i][j] not in cur_cars: type_car = 0 if j == self.size_table - 1: type_move = 1 elif j < self.size_table - 1: if array_board[i][j] == array_board[i][j + 1]: type_move = 0 else: type_move = 1 elif 'O' <= array_board[i][j] <= 'R' and array_board[i][j] not in cur_cars: type_car = 1 if j >= self.size_table - 2: type_move = 1 elif j < self.size_table - 2: if array_board[i][j + 1] == array_board[i][j] and array_board[i][j] == array_board[i][j + 2]: type_move = 0 else: type_move = 1 if array_board[i][j] not in cur_cars: index = (i, j) car = Car(index, type_car, type_move) cur_cars[array_board[i][j]] = car # self.number_of_nodes += 1 current_node = Node(cur_cars, None, 0, array_board, None, None) print_array(array_board) if herstic_id==4: val_herstic = current_node.calc_herustic_valtemp() else: val_herstic = current_node.calc_herustic_val(herstic_id) current_node.herstic_val = val_herstic if herstic_id=='iterative_deepning': return Iterative_deepning.iterative_deepning(current_node) else: self.add_to_waitlist(current_node,herstic_id) return self.search(herstic_id) time_limit=4 if __name__ == "__main__": with open("rh.txt" ,"r") as f: fileData = f.read() data = fileData.split("--- RH-input ---") data = data[1] data = data.split("--- end RH-input ---") data = data[0] games = data.split("\n") games = games[1:] sum_N=0 sum_penetrance=0 sum_avg_h_value=0 sum_ebf=0 sum_max_depth=0 sum_min_depth=0 sum_avg_depth=0 sum_time_exe=0 levels_nodesnumber=[0,0,0,0] levels_time_exe=[0,0,0,0] levels_penetrance=[0,0,0,0] levels_avg_h=[0,0,0,0] levels_ebf=[0,0,0,0] levels_mindepth=[0,0,0,0] levels_avg_avgdepth=[0,0,0,0] levels_maxdepth=[0,0,0,0] size=len(games)-1 for i in range(0, size): print("-------------------------------------------------------------------------------------------------------") print("Problem:" ,str(i+1)) currentData =games[i] puzzle = Puzzle() if i+1==14: N, herstic_id, penetrance, avg_h_value, ebf, max_depth, min_depth, avg_depth, time_exe = puzzle.init_the_game(currentData, 3) else: N,herstic_id,penetrance,avg_h_value,ebf,max_depth,min_depth,avg_depth,time_exe=puzzle.init_the_game(currentData,9) j=int(i/10) levels_nodesnumber[j]+=N levels_time_exe[j]+=time_exe levels_penetrance[j]+=penetrance levels_ebf[j]+=ebf levels_avg_h[j]+=avg_h_value levels_mindepth[j]+=min_depth levels_avg_avgdepth[j]+=avg_depth levels_maxdepth[j]+=max_depth sum_N+=N sum_penetrance+=penetrance sum_avg_h_value+=avg_h_value sum_ebf+=ebf sum_max_depth+=max_depth sum_min_depth+=min_depth sum_avg_depth+=avg_depth sum_time_exe+=time_exe print("-------------------------------------------------------------------------------------------------------") print(herstic_id) print('average number of vistid nodes: ',sum_N/size) print('average time of execution: ',sum_time_exe/size) print('average penetrance: ',sum_penetrance/size) print('average ebf: ',sum_ebf/size) print('average H value: ', sum_avg_h_value/size) print('average max depth: ',sum_max_depth/size) print('average min depth: ',sum_min_depth/size) print('average of average depth: ',sum_avg_depth/size) print("-------------------------------------------------------------------------------------------------------") levels=['beginer','intermdate','advanced','expert'] for i in range(0,len(levels)): print('average number of vistid nodes for ',levels[i], 'is: ', levels_nodesnumber[i]/10) print('average time of execution for ', levels[i], 'is: ', levels_time_exe[i] / 10) print('average penetrance for ', levels[i], 'is: ', levels_penetrance[i] / 10) print('average ebf for ', levels[i], 'is: ', levels_ebf[i] / 10) print('average H value for ', levels[i], 'is: ', levels_avg_h[i] / 10) print('average min depth for ', levels[i], 'is: ', levels_mindepth[i] / 10) print('average of average depth for ', levels[i], 'is: ', levels_avg_avgdepth[i] / 10) print('average max depth for ', levels[i], 'is: ', levels_maxdepth[i] / 10)
b513eaa39db2de8aab8d3e3b99d2d4f342d26b14
Gi-lab/Mathematica-Python
/07-Mate.py
351
4.3125
4
lista_numeros = [] quantidade = int(input('Quantos numeros voce deseja inserir? ')) while len(lista_numeros) + 1 <= quantidade: numero = int(input('Digite um numero ')) lista_numeros.append(numero) maior_numero = max(lista_numeros) print(f'O maior número da lista é {maior_numero}') input('Digite uma tecla para fechar o programa')
0a52989a5efd0d95afbd0b5d2d213834ecbb3505
AnkitaPisal1510/dictionary
/dic_Q10.py
309
3.671875
4
# #q10 d={ "alex":["sub1","sub2","sub3"], "david":["sub1","sub2"] } # l=[] # for i in d: # # print(y[i]) # # print(len(y[i])) # j=len(d[i]) # l.append(j) # print(sum(l)) #second method list1=[] for i in d.values(): for j in i: list1.append(j) print(len(list1)) print(list1)
30437b421a5e77cea639d04f38b77d6e94c62c2f
AnkitaPisal1510/dictionary
/dic_Q7.py
273
3.5625
4
#q7 ["2","7",'9','5','1'] d=[ {"first":"1"}, {"second":"2"}, {"third":"1"}, {"four":"5"}, {"five":"5"}, {"six":"9"}, {"seven":"7"} ] # a=[] # for i in d: # for j in i: # if i[j] not in a: # a.append(i[j]) # print(a)
ad503eddaa5c4a00adab20760850c56e7710ee13
etallman/backend-numseq
/numseq/fib.py
307
4.03125
4
# Fibonacci '''Within the numseq package, creates a module named fib. Within the fib module, defines a function fib(n) that returns the nth Fibonacci number.''' def fib(n): fib_list = [0,1] for i in range(2, n+1): fib_list.append(fib_list[i-2] + fib_list[i-1]) return fib_list[n]
c3d6fa2e65ece7d2cc4c04e2aa815e142bf25306
Artengar/Drawbot
/Letters_overlay/Letters_overlay.py
396
3.984375
4
#This script put letters on top of each other, comparing which parts of the letters are similar in all typefaces installed on your computer presentFonts = installedFonts() fill(0, 0, 0, 0.2) for item in presentFonts: if item != item.endswith("egular"): print(type(item)) print(item) font(item, 450) text("f", (350, 400)) saveImage("~/Desktop/f.jpg")
760cff566ac1cf331b44d84a449fb5da9eb2b3e9
Artengar/Drawbot
/Rolling_eyes_3/Rolling_eyes_3.py
1,717
3.921875
4
#Rolling eyes on the number 3. #Free for use and modify, as long as a reference is provided. #created by Maarten Renckens ([email protected]) amountOfPages = 16 pageWidth = 1000 pageHeight = 1000 #information for drawing the circle: midpointX = 0 midpointY = 0 ratio = 1 singleAngle = 360/amountOfPages #Some default functions import random #Create the animation def drawCircle(page, singleAngle, amountOfCircling, midpointX, midpointY, ratio, color): fill(color) #Get the amount of movement currentAngle = singleAngle*page-90 correctX=random.randint(0,30) correctY=random.randint(0,30) oval(midpointX+(correctX)-ratio,midpointY+(correctY)-ratio,ratio*2,ratio*2) for page in range(amountOfPages): print("==================== Starting page %s ====================" %page) if page != 0: newPage(pageWidth, pageHeight) elif page ==0: size(pageWidth, pageHeight) #set the origin in the middle of the page translate(pageWidth/2, pageHeight/2) #create a background fill(1) rect(-pageWidth/2,-pageHeight/2,pageWidth, pageHeight) #first circle #black midpointX=0 midpointY=200 ratio=160 drawCircle(page, singleAngle, 0, midpointX, midpointY, ratio, 0) #second circle #black midpointX=0 midpointY=-100 ratio=230 drawCircle(page, singleAngle, 0, midpointX, midpointY, ratio, 0) #third circle #white midpointY=200 midpointX=-50 ratio=150 drawCircle(page, singleAngle, 40, midpointX, midpointY, ratio, 1) #fourth circle #white midpointY=-100 midpointX=-60 ratio=230 drawCircle(page, singleAngle, 50, midpointX, midpointY, ratio, 1) saveImage("~/Desktop/Rolling_eyes_3.gif")
bcc0887e2fc2dadab69e061cf0ebb7771acb7145
techmexdev/Networking
/tcp_client.py
663
3.53125
4
from socket import * server_name = 'localhost' server_port = 3000 # SOCK_STREAM = TCP while True: client_socket = socket(AF_INET, SOCK_STREAM) # connection must be established before sending data client_socket.connect((server_name, server_port)) message = input(f'\nSend letter to {server_name}:{server_port}\n') encoded_message = message.encode() client_socket.send(encoded_message) # 4096 is reccomended buffer size: https://docs.python.org/3/library/socket.html#socket.socket.recv reply = client_socket.recv(4096) print(f'received letter from {server_name}:{server_port}:\n{reply.decode()}') client_socket.close()
91c93f60046efb049315fb5bb439f0629e079325
dwightr/ud036_StarterCode
/media.py
1,186
3.609375
4
import webbrowser class Video(): """ Video Class provides a way to store video related information """ def __init__(self, trailer_youtube_url): # Initialize Video Class Instance Variables self.trailer_youtube_url = trailer_youtube_url class Movie(Video): """ Movie Class provides a way to store movie related information and will inherit Instance Variable from the Video class """ VALID_RATINGS = ["G", "PG", "PG-13", "R"] def __init__(self, title, movie_storyline, poster_image, trailer_youtube_url): """ Constructor method will initialize instance variables and variables inhertied from video class """ # Initialize Variables Inhertied From Video Class Video.__init__(self, trailer_youtube_url) # Initialize Movie Class Instance Variables self.title = title self.movie_storyline = movie_storyline self.poster_image_url = poster_image def show_trailer(self): # This Method Shows The Trailer Of The Instance It Is Called From webbrowser.open(self.trailer_youtube_url)
cedb0a8cbf50d11ab70ab10be53e0892ca290bd3
drsantos20/python-concurrency
/algorithms/test_binary_search.py
349
3.59375
4
import unittest from algorithms.binary_search import binary_search class TestBinarySearch(unittest.TestCase): def test_binary_search(self): array = [3, 4, 5, 6, 7, 8, 9] find = 8 result = binary_search(array, find, 0, len(array)-1) self.assertEqual(result, 1) if __name__ == '__main__': unittest.main()
8c81bbc51967ddf5ab6e0d6d40cdea1e0a2dfbd3
renanpaduac/LP_ATIVIDADE_4
/create_db.py
338
3.59375
4
# -*- coding: latin1 -*- import sqlite3 con = sqlite3.connect("imc_calc.db") cur = con.cursor() sql = "create table calc_imc (id integer primary key, " \ "nome varchar(100), " \ "peso float(10), " \ "altura float(10), " \ "resultado float(100))" cur.execute(sql) con.close() print ("DB Criada com Sucesso!")
129123b7825f07aa303dad36c1b93fd5c27329c6
forwardslash333/PythonPractice
/10. Add Pattern.py
398
3.9375
4
''' Write a Python program that accepts an integer (n) and computes the value of n+nn+nnn Sample value of n is 5 Expected Result : 615 ''' n = input ('Enter an integer\n') n1 = int('%s' % n) # single digit integer n2 = int('%s%s' % (n,n)) # second digit number n3 = int('%s%s%s' % (n,n,n)) # Three digit number print(n1+n2+n3)
b7d148d07dedf887d3b750bd29238f7852060f02
Yaraslau-Ilnitski/homework
/Class/Class7/7.08.py
323
3.65625
4
from math import sqrt def func(mean_type, *args): acc = 0 count = 0 if mean_type: for item in args: acc += item count += 1 return acc / count acc = 1 for item in args: acc += item count += 1 return acc ** (1 / count) func(False, 1, 2, 3)
54469d6f0b99a60f520db6c0b159891a8bddc45c
Yaraslau-Ilnitski/homework
/Homeworks/Homework1/task_1_3.py
198
3.59375
4
a = float(input("Ребро куба = ")) V_cube = a ** 3 V_cube_side = 4 * V_cube print('Площадь куба =', V_cube, 'Площадь боковой поверхности =', V_cube_side)
90e3af08fb0b5b7cc753583416b5a3927da92f5b
Yaraslau-Ilnitski/homework
/Class/Class3/3.07.py
189
3.9375
4
stroka = input("Введите предложение\n") if len(stroka) > 5 : print(stroka) elif len(stroka) < 5: print("Need more!") elif len(stroka) == 5: print("It is five")
e04141931c38d8747c39a4a00ff527725b6e6fa9
Yaraslau-Ilnitski/homework
/Homeworks/Homework3/task_3_1.py
250
3.578125
4
a = int(input("Введите число делящееся на 1000:\n")) while True: if a % 1000 == 0: print('millenium') break else: a = int(input("...\nВведите число делящееся на 1000:\n"))
af1751ce022c930e5b09ba0332f4eb16d39d9b02
Yaraslau-Ilnitski/homework
/Class/Class7/7.02.py
1,098
3.78125
4
from random import randint def create_matrix(length, height): rows = [] for i in range(length): tnp = [] for i in range(height): tnp.append(randint(0, 10)) rows.append(tnp) return rows matrix = create_matrix(2, 2) def view(matrix): for vert in matrix: for item in vert: print(item) # print(matrix) # view(matrix) def sum(matrix): s = 0 for valueList in matrix: for i in valueList: s += i return s # print(matrix) # print(sum(matrix)) def greatest(matrix): greatest = 0 for valueRows in matrix: for valueTNP in valueRows: if valueTNP > greatest: greatest = valueTNP return greatest # print(greatest(matrix)) def minimum(matrix): minimum = matrix[0][0] # берем значение как первый элемент матрицы for valueRows in matrix: for valueTNP in valueRows: if minimum > valueTNP: minimum = valueTNP return minimum print(matrix) print(minimum(matrix))
24a0de5ae6d529277c7770ba74537acf5ae23f3b
Yaraslau-Ilnitski/homework
/Class/Class11/Test.py
445
3.78125
4
class main: self.x = x self.y = y class Line: point_a = None point_b = None def __init__(self, a: Point, b: Point): self.point_a = a self.point_b = b def length(self): diff = self.point_a.y - self.point_b.y if diff < 0: diff = -diff return diff def points(): line = Line(Point(1,2),Point(1,6) print(line.length()) if __name__ == '__main__': points()
848b8f6dc9767fe4be22982f73a76e8e376bdbb9
wan-si/pythonLearning
/nowcoder/countUpper.py
252
3.78125
4
# 找出给定字符串中大写字符(即'A'-'Z')的个数 while True: try: string = input() count =0 for i in string: if i.isupper(): count+=1 print(count) except: break
7e2470a00ba8544adad824e27f443cf6aeea842a
wan-si/pythonLearning
/nowcoder/stepSquar 2.py
729
3.53125
4
# 描述 # 请计算n*m的棋盘格子(n为横向的格子数,m为竖向的格子数)沿着各自边缘线从左上角走到右下角,总共有多少种走法,要求不能走回头路,即:只能往右和往下走,不能往左和往上走。 # 本题含有多组样例输入。 # 输入描述: # 每组样例输入两个正整数n和m,用空格隔开。(1≤n,m≤8) # 输出描述: # 每组样例输出一行结果 # 示例1 # 输入: # 2 2 # 1 2 # 复制 # 输出: # 6 # 3 # 复制 def steps(n,m): if n==0 or m==0: return 1 else: return steps(m,n-1)+steps(n,m-1) while True: try: n,m = map(int,input().split()) print(steps(n,m)) except: break
875f5cfd880c495fd2daa4a4285492bbd9176681
chyko67/-
/200528p56.py
599
3.515625
4
import re def maketext(script): written_pattern = r':' match = re.findall(written_pattern, script) for writtenString in match: script = script.replace(writtenString, 'said,') return script s = """mother : My kids are waiting for me. What time is it? What time is it? What time is it, trees! trees : Eight O'clock, Eight O'clock, It's eight O'clock, Tic Tock mother : What time is it? What time is it? What time is it, birds! birds : Twelve O'clock, Twelve O'clock, It's Twelve O'clock, Tic Tock mother : It's so late!""" print(maketext(s))
832f2065b6df66978a435e81418a8458472ea4b8
ajwake97/Weather-App
/Weather Program.py
1,352
3.765625
4
import requests import json import time #This is the API Key API_KEY = "10b3ff178d347bb5e10cfee10deb2b63" #This is the base URL baseUrl = "https://api.openweathermap.org/data/2.5/weather?" #This prompts the user for the desired zipcdoe def zipInput(): zipCode = input("Enter the zipcode: ") #Sends a request to the openweathermaps.org and uses my API key and zipcode to return data response = requests.get((f'http://api.openweathermap.org/data/2.5/weather?zip={zipCode}&appid={API_KEY}')) #Prints the response and displays the returned data if response.status_code == 200: print('Connection Sucessful') time.sleep(2) print(json.dumps(response.json(), indent=1)) reRun() if response.status_code != 200: #Displays connection issue if true print('Connection Unsuccessful') print('Zipcode Not Valid') try: zipCode() #retries zipcode function except: print('Error handling Zipcode') time.sleep(1) print('Please Rerun Program') time.sleep(1) print('Program Ending') exit() #closes program def reRun(): #function allows user to rerun the program Y = input('\n\nWould you like to rerun this program? \nType "Yes" to input another zipcode. \ntype "Quit" to end program\n') while Y == "Yes": zipInput() while Y == "Quit": exit() zipInput() reRun()
b3fac7fac215201441c828afbecfd522e043a42c
shruti0/guvi-1
/leap.py
109
3.765625
4
year = int(input()) if ((year%4==0 and year%100 !=0) or (year%400 == 0)): print('yes') else: print('no')
f0b85958acc09ea92cbf9a995aa24311241efb09
Jrjh27CS/Python-Samples
/practice-python-web/listLessThanTen.py
735
4.0625
4
#Challenge given by https://www.practicepython.org #Jordan Jones Apr 16, 2019 #Challenge: Write a program that prints out all of the elements in given list a less than 5 a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] for x in a: if x < 10: print(x) #Extra 1: Instead of 1 by 1 print, make a new list that has all elements less than 5 and print new list b = [] for x in a: if x < 5: b.append(x) print(b) #Extra 2: Write this in one line of python print([x for x in a if x < 5]) #Extra 3: Ask user for num and return a list that contains only nums from a that are smaller than given number limiter = int(input("What number would you like all elements to be smaller than? Num:")) print([num for num in a if num < limiter])
0a6b38b73eea3f054edadbf5dc5f08ee4c524cb1
Jrjh27CS/Python-Samples
/practice-python-web/fibonacci.py
690
4.21875
4
#Challenge given by https://www.practicepython.org #Jordan Jones Apr 16, 2019 #Challenge: Write a program that asks the user how many Fibonnaci numbers to generate and then generates them. # Take this opportunity to think about how you can use functions. # Make sure to ask the user to enter the number of numbers in the sequence to generate. def fib(x): z = [] if x == 0: return z z.append(0) if x == 1: return z z.append(1) if x == 2: return z while len(z) != x: z.append(z[len(z)-1] + z[len(z)-2]) return z num = int(input("How many fibonacci numbers would you like starting from 0? Num:")) print(fib(num))
b87ed85c70fab6268ef65915778bbed612ba6f0a
C4st3ll4n/Cods_Py
/aleatorio/PouI.py
874
3.625
4
from random import randint as rr v = 0 d = 0 while True: jogador = int(input("Digite um valor: ")) pc = rr(0,11) t = jogador + pc tipo = ' ' while tipo not in 'PI': tipo = input("Par ou Impar? [P/I]\n ").strip().upper()[0] print(f'Deu {t}') if tipo == "P": if t % 2 == 0: print("YOU WIN !") v += 1 else: print("YOU LOOOOSE !") d += 1 if tipo == "I": if t % 2 == 1: v += 1 print("YOU WIN !") else: print("YOU LOOOOSE !") d += 1 print("Eae, vamos de novo ?!") resposta = input("[S/N]") if resposta.strip().upper()[0] == "S": continue else: print(f"Vitórias = {v}\nDerrotas = {d}") print("Tchau Tchau !") break print("\nFIM !")
d2e4e3492046a7fb161d10ee63db46deab2862d5
C4st3ll4n/Cods_Py
/aleatorio/ex62.py
532
3.8125
4
pri = int(input("Primeiro termo: ")) razao = int(input("Razão: ")) termo = pri cont = 1 total = 0 mais = 10 while mais != 0: total = total + mais while cont <= total: print(termo, " ", end="") termo = termo + razao cont += 1 print("\nWait for it....") decisao = input("Deseja mostrar algum número a mais ?\n[S/N] ") if decisao == "S": mais = int(input("Quantos ? ")) else: print("Total de termos: {}".format(total)) break print("Fim!")
38a1b18e152c1156560e74d62f3b826e04c1adbc
CarsonP25/sic_xe-assembler
/symtab.py
442
3.515625
4
class Symtab: """Symbol tables containing labels and addresses""" def __init__(self): """Init table""" self.table = {} def addSym(self, label, value): """Add an entry to the SYMTAB""" self.table[label] = value def searchSym(self, label): for name in self.table.keys(): if name == label: return True return False
3ec773ad3e28f8538c0d76a12d6062df0d30014e
mohan2005mona/python
/regularexpression 1.py
5,799
4.0625
4
import re email=input('enter valid email address') result=re.search(r'[\w\.-][email protected]',email) if result: print("its a valid google id") else: print('Your email id is invalid') result=re.sub(r'[\w\.-][email protected]','\2\[email protected]',email) print(result) import re str= '808-1234 #athis is my phone number dafdfafdafaf' result=re.sub(r'-',' ',re.sub(r'#.*','',str)) print(result) #program to replace the comments in the string and also the other charcters in the Phone number i.e,. hyphen(-) and Dollar($) import re str= '808-12-$34 #athis is my phone number dafdfafdafaf' result=re.sub(r'-',' ',re.sub(r'#.*','',str)) print(result) result=re.sub(r'\D',' ',re.sub(r'#.*','',str)) print(result) # Program to replace the string pattern with other pattern - here we are using multiple combination of pattern to search and replace with the string import re str= '''U.S. stock-index futures pointed to a solidly higher open on Monday, indicating that major benchmarks were poised to USA reboundfrom last week's sharp decline, \nwhich represented their biggest weekly drops in months.''' i=re.sub(r'USA|U.S.|US','United States',str) print(i) str= 'Dan has 3 snails. Mike has 4 cats. Alisa has 9 monkeys.' re.search('\d+',str).group() ------> str= 'Dan has 3 snails. Mike has 4 cats. Alisa has 9 monkeys.' i=re.search('\d+',str) # --> prints only 3 because search functions check all the strings and prints only the first occurance of the string i=re.findall('\d+',str) # --> this prints 3,4,9 as findall finds all the occurances print(i) #--------------------------------------------------------------------------------------------------------------------------- #this program is to square the numbers which are available in the strings and also used a function. import re def square(x): return (x ** 2) string= 'Dan has 3 snails. Mike has 4 cats. Alisa has 9 monkeys.' #x=re.sub('(\d+)',lambda x: str(x),string) --> this line finds the matching digit objects and again prints back the same thing. this is to illustrate about lamba x=re.sub('(\d+)',lambda x: str(square(int(x.group(0)))),string) print(x) import re input="eat 9laugh sleep study" final=re.sub('\w+',lambda m: str(m.group()) +'ing',input) print(final) #printing duplicate entries - \1 prints the duplicate strings which are in consecutive in nature txt=''' hello hello how are are how you bye bye ''' x=re.compile(r'(\w+) \1') print(x.findall(txt)) #backreferencing import re string="Merry Merry Christmas" x=re.sub(r'(\w+) \1',r'Happy \1',string) print(x) #Output : Happy Merry Christmas import re string="Merry Merry Christmas" x=re.sub(r'(\w+) \1',r'Happy',string) print(x) #Output : Happy Christmas #_--------------------------------------------------------------------------- import re txt=''' C:\Windows C:\Python C:\Windows\System32 ''' pattern=re.compile(input('enter the pattern you want to search')) #pattern=re.compile(r'C:\\Windows\\System32') print(pattern.search(txt)) #find all the matches for dog and dogs in the given text import re txt=''' I have 2 dogs. one dog is 1 year old and other one is 2 years old. Both dogs are very cute! ''' print(re.findall('dogs?',txt)) ## the regular expression can also be like this re.findall(dog|dogs)... but the output will not find dogs as complete string instead it will only find "dog" matching string ##first hence dogs will not be in the result.. the result set is [dog,dog,dog] instead of [dog,dogs,dog] #find all filenames starting with file and ending with .txt import re txt=''' file1.txt file_one.txt file.txt fil.txt file.xml ''' print(re.findall('file\w*\.txt',txt)) ##find all filenames starting with file and ending with .txt - plus(+) quantifiers import re txt=''' file1.txt file_one.txt fil89e.txt fil.txt file23.xml file.txt ''' print(re.findall('file\d+\.txt',txt)) #find years in the given text. import re txt=''' The first season of Indian Premiere League (IPL) was played in 2008. The second season was played in 2009 in South Africe. Last season was played in 2018 and won by Chennai Super Kings(CSK). CSL won the title in 2010 and 2011 as well. Mumbai Indians (MI) has also won the title 3 times in 2013, 2015 and 2017. ''' print(re.findall('[1-9]\d{3}',txt)) #In thegiven text,filter out all 4 or more digit numbers. import re txt=''' 123143 432 5657 4435 54 65111 ''' print(re.findall('\d{4,}',txt)) # in case if i have to filter the numbers which has maximum number 4. re.findall('\d{,4}) #In thegiven text,filter out all 4 or more digit numbers. import re txt=''' 123143 432 5657 4435 54 65111 ''' #print(re.findall('\d{4,}',txt)) print(re.findall('\d{1,4}',txt)) --> this is used list out 4 charcters excluding space otherwise it starts from 0 and treat space as separtae character #write a pattern to validate telephone numbers. #Telephone numbers can be of the form : 555-555-5555,555 555 5555 #5555555555 import re txt=''' 555-555-5555 555 555 5555 5555555555 ''' #print(re.findall('\d{4,}',txt)) print(re.findall('\d{3}[\s\-]?\d{3}[\s\-]?\d{4}',txt)) ##End of quantifiers. ##BELOW PROGRAM IS NOT WORKING ##Greedy Behaviour import re txt='''<html><head><title>Title</title>''' print(re.findall("<.*>"),txt) print(re.findall("<.*?>"),txt) # treat each match found as separate entity ##Bounday \b operations import re txt=''' you are trying to find all the and or the symbols in the text but the and or for band is theft by a former ''' print(re.findall('\\b(and|or|the)\\b',txt)) ## boundary matches ##consider a scenario where we want to find all the lines ##in the given text which start with the pattern. import re txt=''' Name: age: 0 Roll No :15 Grade : S Name: Ravi Age : -1 Roll No : 123 Name :ABC Grade : k Name: Ram Age : N/A Roll No : 1 Grade: G ''' print(re.findall('^Name:.*',txt,flags=re.M))
63b47daca4a17690bf29270996835298782b1659
Rodo2005/bucles_python
/ejemplos_clase.py
6,647
4.125
4
#!/usr/bin/env python ''' Bucles [Python] Ejemplos de clase --------------------------- Autor: Inove Coding School Version: 1.1 Descripcion: Programa creado para mostrar ejemplos prácticos de los visto durante la clase ''' __author__ = "Inove Coding School" __email__ = "[email protected]" __version__ = "1.1" valor_maximo = 5 def bucle_while(): # Ejemplos con bucle while "mientras" x = 0 # En este caso realizaremos un bucle mientras # x sea menor a 5 while x < valor_maximo: if x == 4: print('Bucle interrumpido en x=', x) break x_aux = x # Guardamos en una variable auxiliar (aux) el valor de x x += 1 # Incrementamos el valor de x para que el bucle avance # Si x es par, continuo el bucle sin terminarlo if (x_aux % 2) == 0: continue # Imprimimos en pantalla el valorde x_aux, # que era el valor de x antes de incrementarlo print(x_aux, 'es menor a', valor_maximo) while True: print('Ingrese un número distinto de cero!') numero = int(input()) if numero == 0: print('Se acabó el juego! numero={}'.format(numero)) break print('Número ingresado={}'.format(numero)) def bucle_for(): # Ejemplos con bucle for "para" # Realizaremos el mismo caso que el primer ejemplo de "while" # pero ahora con el bucle "for" # Este bucle "for" caso es el indicado para este tipo de acciones for x in range(5): if x == 4: print('Bucle interrumpido en x=', x) break # Si x es par, continuo el bucle sin terminarlo if (x % 2) == 0: continue print(x, 'es menor a', valor_maximo) # Ahora recorreremos (iterar) una lista de datos en donde # en los índices pares (0, 2, 4) se encuentran los nombres de los contactos # y en los índices impares (1, 3, 5) los números de los contacto # Es una lista mezclada de strings y números agenda = ['Claudia', 123, 'Roberto', 456, 'Inove', 789] agenda_len = len(agenda) for i in range(agenda_len): if (i % 2) == 0: # Índice par, imprimo nombre nombre = agenda[i] print("Nombre contacto:", nombre) else: # Índice impar, imprimo número numero = agenda[i] print("Número contacto:", numero) def contador(): # Ejemplo de como contar la cantidad de veces # que un elemento se repite o evento ocurre # En este ejemplo se contará cuantas veces se ingresa # un número par # El bucle finaliza al ingresar vacio # primero debo inicializar mi contador # Como vamos a "contar", el contador debe arrancar en "0" contador = 0 # Bandera que usamos para indicar que el bucle siga corriendo numero_valido = True print("Ingrese cualquier número entero mayor a cero") print("Ingrese número negativo para teriminar el programa") while numero_valido: numero = int(input()) if numero >= 0: if(numero % 2) == 0: # El número es par? contador += 1 # Incremento el contador print("Contador =", contador) else: numero_valido = False # Número negativo, numero_valido falso def sumatoria(): # Ejemplos de ecuaciones con bucles # Cuando queremos realizar la suma de una serie de números # la ecuación la escribiriamos de la siguiente forma: # sumatoria = numero_1 + numero_2 + numero_3 + .... + numero_10 # Que es equivalente a hacer un incremento de la variable sumatoria # por cada valor deseado a sumar # sumatoria += numero_1 # sumatoria += numero_2 # sumatoria += numero_3 # sumatoria += ..... # sumatoria += numero_10 # Esta operación se puede realizar con un bucle "for" # dado la lista de números numeros = [1, 2, 3, 4, 5] # Debo primero inicializar la variable donde almacenaré la sumatoria # Ya que es necesario que empiece con un valor conocido sumatoria = 0 for numero in numeros: sumatoria += numero # sumatoria = sumatoria + numero print("número = ", numero, "sumatoria =", sumatoria) def bucle_while_for(): # Ejemplos de bucles while + for # Como bien vimos, los bucles while "mientras" # se deben utilizar cuando no se conoce la secuencia que se recorrerá # Cuando se posee la secuencia se debe usar el bucle for "para" # El bucle while se utiliza mucho para hacer que un programa corra/funcione # indefinidamente hasta que una condición de salida ocurra # Ejemplificaremos esto junto al uso de un ejercicio con bucle for # El objetivo es pedir por consola un número y almacenarlo en un listado # para imprimirlo al final. # Además, se debe almacenar cual fue el máximo número ingresado # Se debe repetir este proceso hasta que se ingrese un número negativo # Solo se aceptan números positivos o cero maximo_numero = None lista_numeros = [] print("Ingrese un número mayor o igual a cero") while True: # Tomamos el valor de la consola numero = int(input()) # Verificamos si el número es negativo if numero < 0: print('Hasta acá llegamos!') break # Salgo del bucle! # Verifico si el número ingresado es mayor al # máximo número ingresado hasta el momento if (maximo_numero == None) or (numero > maximo_numero): maximo_numero = numero lista_numeros.append(numero) # Termino el bucle imprimo la lista de números: print("Lista: ", lista_numeros) # Imprimo el máximo número encontrado print("Máximo número = ", maximo_numero) # Imprimo el máximo número utilizando la función max de Python print("Máximo número con Python = ", max(lista_numeros)) # Imprimo el índice del máximo número en la lista print("Índice del máximo número en la lista = ", lista_numeros.index(maximo_numero)) # Imprimo cuantas veces se repite el máximo número en la lista print("Cantidad del máximo número en la lista = ", lista_numeros.count(maximo_numero)) if __name__ == '__main__': print("Bienvenidos a otra clase de Inove con Python") # bucle_while() # bucle_for() # contador() # sumatoria() # bucle_while_for()
99fb47e8d7b77982b52335e4d53ef5f5a05b6dc8
nicolascordoba1/PythonIntermedio
/hangman.py
943
3.5
4
from random import randint import os def run(): with open("./archivos/data.txt", "r", encoding= "utf-8") as f: contador = 0 palabras = [] for line in f: palabras.append(line.rstrip()) contador +=1 numero = randint(0, contador-1) palabra = palabras[numero] palabra = list(palabra) os.system("cls") print("Empieza el juego") #print(palabra) palabra_actual = list("_" * len(palabra)) cant_barraspiso = len(palabra_actual) print(palabra_actual) while cant_barraspiso > 0: #Mientras la cantidad de "_" sea mayor a 0 ejecutese letra = input("Adivina la palabra: ") for i in range(len(palabra)): if palabra[i] == letra: palabra_actual[i] = letra cant_barraspiso -= 1 print(palabra_actual) if __name__ == "__main__": run()
6bf2e38a0c09451811be3e0f0d17b5d172b839e5
Arselena/higher-school
/Level_0_8.py
662
3.71875
4
def SumOfThe(N, data): try: assert type(N) is int and N >= 2 and N == len(data) for i in range(len(data)): assert type(data[i]) is int # Проверяем Элемент массива DATA = list(data) SUM = None for i in range(1, N): if DATA[0] == sum(DATA[1:N]): SUM = DATA[0] break elif DATA[N-1] == sum(DATA[0:(N-1)]): SUM = DATA[N-1] else: DATA[0], DATA[i] = DATA[i], DATA[0] return SUM except AssertionError: pass print(SumOfThe(7, [100, -50, 10, -25, 90, -35, 90]))
66a860394ed31f2c6c821d93b5ccebefe40742be
Arselena/higher-school
/Level_0_11.py
474
3.875
4
def BigMinus(s1, s2): try: assert type(s1) is str and type(s2) is str assert s1 != '' and s2 != '' def modul(x): # Возвращает модуль x if x < 0: x = x * (-1) return x a = int(s1) b = int(s2) assert 0 <= a <= (10**16) and 0 <= b <= (10**16) s = modul(a - b) # или s = abs(a - b) return(str(s)) except AssertionError: pass
57d1ca01b8dde421ca7f9e9fc001725a516febb3
rdiazrincon/PytorchZeroToAll
/5_Linear_Regression.py
3,039
4.0625
4
import torch from torch import nn from torch import tensor # x_data is the number of hours studied x_data = tensor([[1.0], [2.0], [3.0], [4.0]]) # y_data is the number of points obtained y_data = tensor([[3.0], [5.0], [7.0], [9.0]]) # e.g: 1 hour of study -> 2 points. 2 hours of study -> 4 points usw # hours_of_study is the parameter we pass on. What we want to predict is our score hours_of_study = 5.0 # Steps to create a Neural Network # Step 1: Design the Model using classes # Step 2: Define a loss function and optimizer # Step 3: Train your model class Model(nn.Module): def __init__(self): """ In the constructor we instantiate two nn.Linear module """ # Initializing the Model with the class super(Model, self).__init__() # torch.nn.Linear applies a Linear transformation. The first parameter is the size of each input sample. The second is the size of the output sample self.linear = torch.nn.Linear(1, 1) def forward(self, x): """ In the forward function we accept a Variable of input data and we must return a Variable of output data. We can use Modules defined in the constructor as well as arbitrary operators on Variables. """ y_pred = self.linear(x) return y_pred # Our model model = Model() # Construct our loss function and an Optimizer. # The call to model.parameters() in the SGD constructor will contain the learnable parameters of the two # nn.Linear modules which are members of the model. loss_function = torch.nn.MSELoss(reduction='sum') optimizer = torch.optim.SGD(model.parameters(), lr=0.01) # for name in model.named_parameters(): # print (name) # Other optimizers: torch.optim.Adagrad, torch.optim.Adam, torch.optim.Adamax, torch.optim.ASGD, torch.optim.LBFGS, torch.optim.RMSprop, torch.optim.Rprop, torch.optim.SGD # Training loop for epoch in range(500): # 1) Forward pass: Compute predicted y by passing x to the model y_pred = model(x_data) # 2) Compute and print loss # Both y_pred and y_data are tensors loss = loss_function(y_pred, y_data) # print(f'Epoch: {epoch} | Loss: {loss.item()} ') # Inside the training loop, optimization happens in three steps: # Call optimizer.zero_grad() to reset the gradients of model parameters. Gradients by default add up; to prevent double-counting, we explicitly zero them at each iteration. optimizer.zero_grad() # Backpropagate the prediction loss with a call to loss.backwards(). PyTorch deposits the gradients of the loss w.r.t. each parameter. loss.backward() # Once we have our gradients, we call optimizer.step() to adjust the parameters by the gradients collected in the backward pass. optimizer.step() # What we are trying to do is predict the score or points we will get if we study hours_of_study hour_var = tensor([[hours_of_study]]) y_pred = model(hour_var) print(f'If we study {hours_of_study} hours we will get a score of {model(hour_var).data[0][0].item()}')
f7011fc9cd0a66c35e67f3440e67aff78ca813f6
LeoKnox/kanji_app_a
/tree.py
1,514
3.75
4
class Tree: def __init__(self, info): self.left = None self.right = None self.info = info def delNode(self, info): if self.info == info: print('equal') if not self.left and not self.right: print('a') self.left = None self.right = None self.info = None elif self.right: print('aa') self.left = None self.right = None self.info = None else: print('d') elif info <= self.info: print('e') self.left.delNode(self.info) elif info > self.info: print('f') self.delNode(self.info) def addNode(self, info): if self.info: if info < self.info: if self.left == None: self.left = Tree(info) else: self.left.addNode(info) elif info >= self.info: if self.right == None: self.right = Tree(info) else: self.right.addNode(info) def traceTree(self): if self.left: self.left.traceTree() print( self.info), if self.right: self.right.traceTree() t = Tree(7) t.addNode(8) t.addNode(3) t.traceTree() t.delNode(3) print('99999') t.traceTree()
5c9720ba0f06dc339f3d3054cc59a9ae573e8093
brammetjedv/PYTAchievements
/ifstatements.py
275
3.71875
4
varA = 6 if ( varA == 5 ): print("cool") elif ( varA > 5 ): print("kinda cool") elif ( varA == 69 ) pass else : print("not cool") varW = True varX = True varY = True varZ = True if ( (varW and varX) or (varY and varZ) ): print("flopje") print("end")
7620b60fd16105ff63f2738573db92dc2d8f3fd5
tegupta/fulltopractice
/OOPs/using_init_method.py
281
3.84375
4
class Emp(object): def __init__(self,name,salary): self.name=name self.salary=salary return None def display(self): print(f"The name is: {self.name}\nThe salary is:{self.salary}") return None emp1=Emp('Ramu', 54000) emp1.display()
61e3abf84388aa418bbbd5e32adbda69f0da9fb0
Pod5GS/CS5785-Applied-Machine-Learning
/HW0/iris_plot.py
2,920
3.59375
4
#!/usr/bin/env python """ This script read Iris dataset, and output the scatter plot of the dataset. Be sure the Iris dataset file is in the 'dataset' directory. """ from matplotlib import pyplot as plt import numpy # This function draw the labels def draw_label(fig, label, index): """ :param fig: The figure instance :param label: The text shown in the subplot :param index: The index of subplot """ ax = fig.add_subplot(4, 4, index) ax.set_xticks(()) # get rid of x axis ax.set_yticks(()) # get rid of y axis ax.text(0.5, # x coordinate, 0 leftmost positioned, 1 rightmost 0.5, # y coordinate, 0 topmost positioned, 1 bottommost label, # the text which will be printed horizontalalignment='center', # set horizontal alignment to center verticalalignment='center', # set vertical alignment to center fontsize=20, # set font size ) # This function read Iris dataset into arrays and draw the scatter plot def iris_plot(): attributes = [] # N * p array labels = [] # label of each line of data for line in open("F:\Cornell Tech\HW\CS5785-AML\HW0\dataset\iris.data.txt"): if not line.split(): continue attributes.append(line.split(',')[:4]) # first 4 elements are attributes labels.append(line.split(',')[-1].strip('\n')) # last element is label, strip the '\n' attributes = numpy.array(attributes) # convert N * p array to Numpy array for i in range(len(labels)): # assign colors for each label if labels[i] == 'Iris-setosa': labels[i] = 'r' elif labels[i] == 'Iris-versicolor': labels[i] = 'g' else: labels[i] = 'b' fig = plt.figure(figsize=(15., 15.)) # set figure size fig.suptitle('Iris Data(red=setosa, green=versicolor, blue=virginica)', fontsize=30) # set figure title count = 1 # variable used to track current sub figure to draw for x in range(4): for y in range(4): if x == y: # when x equal to y, draw label if x == 0: draw_label(fig, 'Sepal.Length', count) elif x == 1: draw_label(fig, 'Sepal.Width', count) elif x == 2: draw_label(fig, 'Petal.Length', count) elif x == 3: draw_label(fig, 'Petal.Width', count) else: # else draw the scatter plot of every 2 combinations of those 4 attributes xs = numpy.array(attributes.T[y]) ys = numpy.array(attributes.T[x]) ax = fig.add_subplot(4, 4, count) ax.scatter(xs, ys, c=labels) count += 1 fig.savefig('plot.png') # save the figure if __name__ == '__main__': iris_plot()
165c2222f7e8767fc1201b609da4a4c8aabfbc6b
knotriders/programarcadegame
/pt6.2.2.py
244
3.640625
4
n = int(input("How many eggs?:")) print("E.g. n: ",n) # n = 8 for i in range(n): for j in range(n*2): if i in (0 , n-1) or j in (0, 2*n-1): print("o", end = "") else: print(" ", end = "") print()
fbbe40dbd80fa0eb0af9a22c7c1f78775dca2dca
knotriders/programarcadegame
/test2.py
274
3.90625
4
done = False while not done: quit = input("Do you want to quit? ") if quit == "y": done = True else: attack = input("Does your elf attack the dragon? ") if attack == "y": print("Bad choice, you died.") done = True
8eae2a9c399ad80545c8ac7f3d4878fcfef4285e
hmcurt01/Ivy-Plus
/printdata.py
3,541
3.8125
4
from data import student_dict import pyperclip #convert student dict into text def printdict(value, grade): studentamt = 0 sortednames = {} for o in student_dict: if student_dict[o].grade == grade: sortednames[o] = student_dict[o].name if value == "stats": label = "NAME " + "|ACT |" + "C/RANK |" + "COGAT |" + "F/GEN |" + "GPA |" + "HOUSE |" +\ "L/I |" + "MINOR |" + "RACE |" datastring = "Class of " + grade + ": \n\n" + label + "\n\n" for i in sorted(sortednames.items(), key=lambda kv: (kv[1], kv[0])): i = i[0] if student_dict[i].grade == grade: studentamt += 1 if studentamt > 20: studentamt = 0 datastring = datastring + label + "\n\n" datastring = datastring + short_string(student_dict[i].name[:24], 25) for key, char in sorted(student_dict[i].__dict__.items()): if key == "act" or key == "classrank" or key == "cogat" or key == "firstgen" or key == "gpa"\ or key == "house" or key == "lowincome" or key == "minority" or key == "race": datastring = datastring + "|" + short_string(str(char), 8) datastring = datastring + "|" + "\n" + "\n" else: datastring = "Class of " + grade + ": \n\n" for i in sorted(sortednames.items(), key=lambda kv: (kv[1], kv[0])): i = i[0] if student_dict[i].grade == grade: datastring = datastring + student_dict[i].name + ": \n" for key, char in student_dict[i].__dict__.items(): if key != "act" and key != "classrank" and key != "cogat" and key != "firstgen" and key != "gpa" \ and key != "house" and key != "lowincome" and key != "minority" and key != "race" and key\ != "colleges" and key != "mentees" and key != "recs" and key != "name" and key != "grade"\ and key != "Class": if str(char).strip() == "Designate Class": char == "Undesignated" datastring = datastring + key.upper() + ": " + str(char) +"\n" if key == "colleges": datastring = datastring + "COLLEGES: " for p in student_dict[i].colleges: datastring = datastring + student_dict[i].colleges[p].name + ", " datastring = datastring + "\n" if key == "mentees": datastring = datastring + "MENTEES: " for p in student_dict[i].mentees: datastring = datastring + student_dict[i].mentees[p].name + ", " datastring = datastring + "\n" if key == "recs": datastring = datastring + "RECS: " for p in student_dict[i].recs: datastring = datastring + student_dict[i].recs[p].name + ", " datastring = datastring + "\n" datastring = datastring + "\n" pyperclip.copy(datastring) #add blank space to short string def short_string(str, length): if len(str) < length: while len(str) < length-1: str = str + " " return str return str
dcbe36488dc453401fb81abd4a01dd2fe29bcbbf
moribello/engine5_honor_roll
/tools/split_names.py
1,231
4.375
4
# Python script to split full names into "Last Name", "First Name" format #Note: this script will take a .csv file from the argument and create a new one with "_split" appended to the filename. The original file should have a single column labled "Full Name" import pandas as pd import sys def import_list(): while True: try: listname1 = sys.argv[1] list1 = pd.read_csv(listname1) break except: print(listname1) print("That doesn't appear to be a valid file. Please try again.") break return list1, listname1 def split_fullnames(df, listname): # new data frame with split value columns new = df["Full Name"].str.split(" ", n = 1, expand = True) # making separate first and last name columns from new data frame df["First Name"]= new[1] df["Last Name"]= new[0] df = df.drop(columns=['Full Name']) new_filename = listname[:-4] df.to_csv(new_filename+"_split.csv", index=False) print("Spaces removed. Changes written to file {}_split.csv.".format(new_filename)) def main(): list1, listname1 = import_list() split_fullnames(list1, listname1) if __name__ == "__main__": main()
6ac521f4fa27b32de1192e7f2b8367ac6b86f9ea
Meet00732/DataStructure_And_Algorithms
/Breath_First_Search/BFS.py
929
3.90625
4
import time graph = dict() visited = [] queue = [] n = int(input("enter number of nodes = ")) for i in range(n): node = input("enter node = ") edge = list(input("enter edges = ").split(",")) graph[node] = edge # print(graph) def bfs(visited, graph, n): queue.append(n) for node in queue: if node not in visited: visited.append(node) for value in graph[node]: if value not in queue: queue.append(value) for node in graph.keys(): if node not in visited: queue.append(node) visited.append(node) for value in graph[node]: if value not in queue: queue.append(value) print(visited) def give_time(start_time): print("Time taken = ", time.time() - start_time) start_time = time.time() bfs(visited, graph, 'u') give_time(start_time)
50d6496496531c365527290d9d12bcf4fb1f1c5f
DanilkaZanin/vsu_programming
/Time/Time.py
559
4.125
4
#Реализация класса Time (из 1 лекции этого года) class Time: def __init__(self, hours, minutes, seconds): self.hours = hours self.minutes = minutes self.seconds = seconds def time_input(self): self.hours = int(input('Hours: ')) self.minutes = int(input('Minutes: ')) self.seconds = int(input('Seconds: ')) def print_time(self): print(f'{self.hours}:{self.minutes}:{self.seconds}') time = Time(1 , 2 , 3) time.time_input() time.print_time()
77c1a636b346eb0a29ce7010a249a0d13c375fb6
shaikhul/scoring_engine
/parsers.py
716
3.75
4
import csv from custom_exceptions import ParseError class Parser(object): def __init__(self, file_path): self.file_path = file_path def parse(self): raise NotImplementedError('Parse method does not implemented') class CSVParser(Parser): def parse(self): with open(self.file_path, 'rb') as f: reader = csv.reader(f) rows = [] try: for row in reader: if len(row) != 3: raise ParseError('No of column mismatch, expected 3 got %d' % len(row)) rows.append(row) return rows except csv.Error as e: raise ParseError(str(e))
89de0d0d8b5680f76b8150da9a93320b89e6a41b
summerpenguin/learning-CS
/ex16-4.py
2,123
3.859375
4
#将参数调入模块 from sys import argv #在运行代码时需要输入的代码文件名称和需要调用的文件名称 script, filename = argv #打印”我们将要擦除文件,文件名为格式化字符%r带标点映射文件名“ print "We're goint to erase %r." % filename #打印”如果你不想这么做,可以按CERL-C键终止进程“ print "If you don't want that, hit CRTL-C (^C)." #打印”如果你想这么做,请点击RETURN键“ print "If you do want that, hit RETURN." #以”?“为提示符读取控制台的输入 raw_input("?") #打印#开启文件。。。# print "Opening the file..." #为变量target赋值为开启命令,开启对象是写入状态下的文件名 target = open(filename, 'w') #打印”正在清空文件。再见!“ print "Truncating the file. Goodbye!" #使变量target执行truncate命令 target.truncate() #打印”现在我将针对文本文件中的三行对你提问“ print "Now I'm going to ask you for three lines." #以”第一行:“为提示符读取控制台的输入,并将其赋值给变量line1 line1 = raw_input("line 1: ") #以”第二行:“为提示符读取控制台的输入,并将其赋值给变量line2 line2 = raw_input("line 2: ") #以”第三行:“为提示符读取控制台的输入,并将其赋值给变量line3 line3 = raw_input("line 3: ") #打印”我即将要将这些信息输入到文件中。“ print "I'm going to write these to the file." ,c #使变量target执行write命令,材料是变量line1的赋值 target.write(line1) #使变量target执行write命令,材料是分行符 target.write("\n") #使变量target执行write命令,材料是变量line2的赋值 target.write(line2) #使变量target执行write命令,材料是分行符 target.write("\n") #使变量target执行write命令,材料是变量line3的赋值 target.write(line3) #使变量target执行write命令,材料是分行符 target.write("\n") #打印“于是结束了,让我们关闭文件。” print "And finally, we close it." #使变量target执行close命令,关闭文档并保存 target.close()
fb43b06f60b0b73c57a7c99814e2ad1e2d6acf15
james-prior/python-asyncio-experiments
/mylog.py
899
3.8125
4
import datetime def format_time(t): return f'{t.seconds:2}.{t.microseconds:06}' def log(message): ''' prints a line with: elapsed time since this function was first called elapsed time since this function was previously called message Elapsed times are shown in seconds with microsecond resolution although one does not know what the accuracy is. ''' global time_of_first_call global time_of_previous_call now = datetime.datetime.now() try: time_of_first_call except NameError: time_of_first_call = now time_of_previous_call = now time_since_first_call = now - time_of_first_call time_since_previous_call = now - time_of_previous_call print( format_time(time_since_first_call), format_time(time_since_previous_call), message, ) time_of_previous_call = now
0ddd1c97e6e4b0b15dcfd7f5f09fdf19c822120a
james-prior/python-asyncio-experiments
/2-sequential-waits.py
474
3.78125
4
#!/usr/bin/env python3 ''' Awaiting on a coroutine. Print “hello” after waiting for 1 second, and then print “world” after waiting for another 2 seconds. Note that waits are sequential. ''' import asyncio from mylog import log async def say_after(delay, what): await asyncio.sleep(delay) log(what) async def main(): log('main starts') await say_after(1, 'hello') await say_after(2, 'world') log('main finishes') asyncio.run(main())
a31c0549965ec668c0009148d5a94db2bc70225f
taysemaia/basic_python
/conjuntos.py
437
3.734375
4
# coding: utf-8 # Programação 1, 2018.2 # Tayse de Oliveira Maia # Conjunto com mais elementos numero = [] soma = 0.0 while True: numeros = raw_input() if numeros == 'fim': break soma += 1 if int(numeros) < 0: numero.append(soma) soma = 0.0 for i in range(len(numero)): numero[i] = numero[i] - 1 maior = max(numero) indice = numero.index(maior) print "Conjunto %d - %d elemento(s)" % (indice + 1, numero[indice])
a9653885227248fd5605eb6b0fcc7ec6b2bb5cfc
taysemaia/basic_python
/avre.py
270
3.75
4
# coding: utf-8 # Programação 1, 2018.2 # Tayse de Oliveira Maia # Arvore Natal altura = int(raw_input()) larguramax = 2 * altura - 1 for alturas in range(altura + 1): print ' ' * (larguramax - ( 2 * alturas - 1) / 2), print 'o' * (2 * alturas - 1) print (larguramax + 1) * " " + "o"
0b48be2de52b543d189741a5c5300f995adf84f2
EssamQabel/Problem-Solving
/Codeforces/A/41A.py
200
3.71875
4
s = input() t = input() result_list = [] for i in range(len(s)): result_list.append(s[i]) result_list.reverse() s = ''.join(result_list) if s == t: print('YES') else: print('NO')
6d3af464bbf9f8e9cf52f751bb66d9fde3cfbace
manankhaneja/hep-da
/programs/main.py
2,607
3.609375
4
# -*- coding: utf-8 -*- """ Created on Fri Mar 23 18:50:07 2018 - constantly improving ever since @author: Manan Khaneja """ # Master program for data extraction without damaging file format # takes in input the directory in which all the files have to be analysed ( eg. a directory from which neutron data is extracted) #analyses all the files and names the txt file generated with those conditions. # asks for the path of the directory where you want to save that file (eg. I want to save my neutron.txt file in a directory named 'Particles', hence give path of 'Particles') #'variables.conditions' is accessing a list conditions in variable.py containing all the strings ( eg. neutron, DET0, protonInelastic etc.) # hence while entering variables.conditions take care of the format(case sensitive)/ spelling) import os import math import newoutfile import plot import variables def isSubset(words,conditions): for cond_index in range(0,len(conditions),1): word_index = 0 while word_index < len(words): if conditions[cond_index] == words[word_index]: break else: word_index = word_index + 1 if word_index == len(words): return 0 return 1 def dir_file_ext(): user_input = input("Enter the path of your directory where all the files are present: \n") assert os.path.isdir(user_input), "I did not find the directory" print("\n") all_files = os.listdir(user_input) print(all_files) count = 0 conditions = variables.conditions complete_name = variables.complete_name for file in all_files: f = open(user_input + "/" + file,"r+") k = open(complete_name, "a+") line = f.readline() while line: words = line.split() if isSubset(words,conditions): k.write(line) count += 1 line = f.readline() else: line=f.readline() f.close() k.close() print("The number of such particles is ", count) flag = int(input("Do you want to create the condensed file? \n0. NO \n1. YES\n")) if flag: newoutfile.newoutfile() old_del = int(input("Do you want to delete the originally created file ? \n0. NO \n1. YES\n")) if old_del: os.remove(complete_name) task = int(input("What do you want to do -\n0. Make a txt file with given conditions from a directory \n1. Call the plotting function\n")) if task: plot.plot() else: dir_file_ext()
b36872d55259a67b9b0ad8ef8ce8e26e30b75cc0
benkerns09/digital-crafts-lessons
/files/March8/phonebook.py
2,012
4.0625
4
class PhoneBook(object): def __init__(self, name, phone):#in it we have the name and phone number self.name = name self.phone = phone self.peopleList = []#I'm not sure what this is def phoneBookEmpty(self): if len(self.peopleList) == 0:#if the length of people list is zero...its finna print phonebook empty print "Phonebook empty" return False def lookUpEntry(self): name = raw_input("name to lookup: ")#user will input the name to lookup self.phoneBookEmpty()#i'm not sure why this is here for person in self.peopleList: if person.name == name: print (person.name, person.phone) def createContact(self): name = raw_input("input name: ") phone = raw_input("input phone: ") newContact = PhoneBook(name, phone) allContacts.peopleList.append(newContact) def delEntry(self): name = raw_input("name to delete: ") self.phoneBookEmpty() for i in range(len(self.peopleList)): person = self.peopleList[i] if person.name == name: del self.peopleList[i] def listAllEntries(self): self.phoneBookEmpty() for person in self.peopleList: print (person.name, person.phone) allContacts = PhoneBook("allContacts","null") def menu(): print """ Electronic Phone Book ===================== 1. Look up an entry 2. Set an entry 3. Delete an entry 4. List all entries 5. Quit""" def main(): while True: menu() answer = int(raw_input("What do you want to do (1-5)? ")) if answer == 1: allContacts.lookUpEntry() elif answer == 2: allContacts.createContact() elif answer == 3: allContacts.delEntry() elif answer == 4: allContacts.listAllEntries() elif answer == 5: print "Have a Good Day" return False main()
c6a3dc37f5d97438c3a9a3894cc82f65ec9ff35b
benkerns09/digital-crafts-lessons
/files/March6/mar307.py
666
3.828125
4
def drawtriangle(height, base): for row in range(1, height + 1): spaces = height - row print " " * spaces + "*" * (row * 2 - 1) drawtriangle(6, 4) def box(height, width): for row in range(height): if row in[0] or row in[(height-1)]: print("* " * (width)) else: print("*"+" "*(width-2)+" *") box(2, 7) def drawsquare(width, height): for row in range(height): if row == 0: print "*" * width elif row == height - 1: print "*" * width else: spaces = width - 2 print "*" + " " * spaces + "*" drawsquare(10, 5) drawsquare(50, 5)
6c51492aa5005099401d48ce50e6d84e41b59657
KhalidOmer/Exercises
/Work_Directory/Python/lottery.py
617
3.890625
4
import numpy as np """This is a simple common game that asks you to guess a number if you are lucky your number will match the computer's number""" def luck_game(): print("Hello, let's check if you're lucky!'") print("You are asked to guess a number between 0 and 10'") luck_number = int(np.random.uniform(0,11)) user_input = input("Enter your guess: ") if int(user_input) <= 10: if int(user_input) == luck_number: print("Wow! You're one of the luckiest people on the planet") else: print("Try again my friend the corret number is", luck_number,".") else: print("Invalid input") luck_game()
86773d8aa5d642f444192ecc1336560c86d718ca
siddu1998/sem6_labs
/Cloud Computing/Assignment 1/question9.py
218
4.40625
4
# Write a Python program to find whether a given number (accept from the user) # is even or odd, print out an appropriate message to the user. n=int(input("please enter the number")) print("even" if n%2==0 else "odd")
180256985bff15f54e150f1ff7a6cc4d86a1b365
siddu1998/sem6_labs
/Cloud Computing/Assignment 1/question10.py
250
3.984375
4
# Write a Python program to count the number 4 in a given list. length=int(input("Please enter the length")) list_with_fours=[] for i in range(0,length): list_with_fours.append(int(input())) print("number of 4's") print(list_with_fours.count(4))
f0501f677535546d870b4e28283048c78fb87771
zhh007/LearnPython
/2.List.py
619
4.0625
4
x = list('Hello') print(x) y = "".join(x) print(y) x = [1, 1, 1] x[1] = 2 print(x) names = ['Void', 'Alice', 'Jack'] del names[1] print(names) name = list('Perl') name[2:] = list('ar') print(name) list1 = [1, 2, 3] list1.append(4) print(list1) x = [1, 2, 1, 3] print(x.count(1)) a = [1, 2, 3] b = [4, 5] a.extend(b) print(a) a = ['love', 'for', 'good'] print(a.index('for')) a = [1, 2, 3] a.insert(1, 'b') print(a) x = [1, 2, 3] y = x.pop() print(y) x = ['to', 'be', 'or', 'not', 'to', 'be'] x.remove('be') print(x) x = [1, 2, 3] x.reverse() print(x) x = [4, 5, 8, 9, 2, 1, 7] x.sort() print(x)
891d590fe33896826dd3c5ce6c6e1bea06e5b980
pink-floyd-in-venice/pink-floyd-in-venice.github.io
/resources/functions/CsvTripleCreator/main.py
722
3.890625
4
import csv if __name__== "__main__": csv_name=input("Inserire nome file csv: ") if csv_name[-4:] !=".csv": csv_name += ".csv" with open(csv_name, "w", newline="") as csv_file: writer=csv.writer(csv_file, delimiter=' ', quotechar='|') writer.writerow(["Subject", "Predicate", "Object"]) while True: triple_string=input("Inserire tripla separata da un punto e virgola(;) o stop: ") if triple_string in"stopSTOP": break triple_list=list(triple_string.split(";")) if len(triple_list)!= 3: print("Errore nella definizione della tripla") continue writer.writerow(triple_list)
c03b3059a659730e6db51364c5dd5144bc5f64a6
SandeeraDS/FYP-Codes
/After 2019-08-25/python_string/stringTest.py
563
3.734375
4
import re name = " sande er " \ "dddsds sds sds sdd dsdsd ddsd dsds " name2 = " sande er " \ "dddsds sds sds sdd dsdsd ddsd dsdsa" name3 = " BCVFE | sande er " \ "dddsds sds sds sdd 2 .. 3 dsdsd ddsd ? dsdsA1" newString1 = "".join(name.split()) newString2 = "".join(name2.split()) newAlphabet = "".join(re.findall("[a-zA-Z]+", name3.lower())) # # print(newString1) # print(newString2) print(newAlphabet) # print(name.strip()) print(newAlphabet != newString2)
f0d2eef82b83a98f36f2a759f585c8cf03ad0327
SandeeraDS/FYP-Codes
/After 2019-08-25/encoding_test/test.py
1,093
3.53125
4
import re import nltk # to install contractions - pip install contractions from contractions import contractions_dict def expand_contractions(text, contractions_dict): contractions_pattern = re.compile('({})'.format('|'.join(contractions_dict.keys()))) def expand_match(contraction): # print(contraction) match = contraction.group(0) first_char = match[0] expanded_contraction = contractions_dict.get(match) \ if contractions_dict.get(match) \ else contractions_dict.get(match.lower()) expanded_contraction = expanded_contraction print(expanded_contraction) return expanded_contraction expanded_text = contractions_pattern.sub(expand_match, text) print(expanded_text) return expanded_text # for the transcript with open('2.txt', 'r', encoding="utf-8") as file: data = file.read() data = expand_contractions(data, contractions_dict) sentence = nltk.sent_tokenize(data) tokenized_sentences = [nltk.word_tokenize(sentences) for sentences in sentence] print(tokenized_sentences)
d3a2e416b3bd15607d71317808f17751667c9e0b
Jeremyreiner/DI_Bootcamp
/week5/Day4/exercise/exerciseXP.py
3,256
4.46875
4
# Exercise 1 – Random Sentence Generator # Instructions # Description: In this exercise we will create a random sentence generator. We will do this by asking the user how long the sentence should be and then printing the generated sentence. # Hint : The generated sentences do not have to make sense. # Download this word list # Save it in your development directory. # Ask the user how long they want the sentence to be. Acceptable values are: an integer between 2 and 20. Validate your data and test your validation! # If the user inputs incorrect data, print an error message and end the program. # If the user inputs correct data, run your code. # ----------------------------------------------------------------------------------------------- # import random # # Create a function called get_words_from_file. This function should read the file’s content and # # return the words as a collection. What is the correct data type to store the words? # def get_words_from_file(): # words = [] # with open('words.txt','r') as f: # for line in f: # words.append(line.rstrip('\n')) # f.close() # return words # # Create another function called get_random_sentence which takes a single parameter called length. # # The length parameter will be used to determine how many words the sentence should have. The function should: # # use the words list to get your random words. # # the amount of words should be the value of the length parameter. # def get_random_sentence(length): # sentence = '' # return_words = get_words_from_file() # random_words = random.choices(return_words, k = length) # for word in random_words: # sentence += word + ' ' # # Take the random words and create a sentence (using a python method), the sentence should be lower case. # print(sentence.lower) # def sent_length(): # num = int(input("Enter a number value for how long your sentence should be: ")) # if 2 <= num <= 20: # get_random_sentence(num) # else: # raise Exception("Incorrect value enterred") # # Create a function called main which will: # # Print a message explaining what the program does. # def main(): # print('this exercise we will create a random sentence generator') # print("Would you like to make a random sentence? (yes / no) ") # user_input = input() # if user_input == 'yes': # sent_length() # else: # print("Have a good day.") # main() # -------------------------------------------------------------------------- # Exercise 2: Working With JSON # Instructions import json # Access the nested “salary” key from the JSON-string above. # Add a key called “birth_date” to the JSON-string at the same level as the “name” key. # Save the dictionary as JSON to a file. # ---------------------------------------------------------------------------------------- with open('samplejson.json', 'r') as f: company = json.load(f) # print(company['company']['employee']['payable']['7000']) for key, values in company.items(): print(key, values['employee']['payable']['salary']) company['company']['empployee']['birthday'] = 24 with open('samplejson.json', 'w') as f: company = json.load(f)
316aa2bdc7e255944d154ce075592a157274c9bc
Jeremyreiner/DI_Bootcamp
/week5/Day3/daily_challenges/daily_challenge.py
2,874
4.28125
4
# Instructions : # The goal is to create a class that represents a simple circle. # A Circle can be defined by either specifying the radius or the diameter. # The user can query the circle for either its radius or diameter. # Other abilities of a Circle instance: # Compute the circle’s area # Print the circle and get something nice # Be able to add two circles together # Be able to compare two circles to see which is bigger # Be able to compare two circles and see if there are equal # Be able to put them in a list and sort them # ---------------------------------------------------------------- import math class Circle: def __init__(self, radius, ): self.radius = radius self.list = [] def area(self): return self.radius ** 2 * math.pi def perimeter(self): return 2*self.radius*math.pi def __le__(self, other): if self.radius <= other.radius: return True else: return False def __add__(self, other): if self.radius + other.radius: return self.radius + other.radius def add_circle(self): for item in self.list: if item not in self.list: self.list.append(item) def print_circle(self): return print(self.list) circle = Circle(50) circle_2 = Circle(7) print(circle.area()) Circle.add_circle(circle) Circle.add_circle(circle_2) print(Circle.print_circle(circle)) print(circle.perimeter()) print(circle.__le__(circle_2)) print(circle.__add__(circle_2)) # bigger_circle = n_circle.area + n_circle_2.area # print(bigger_circle.area()) # !class Racecar(): # def __init__(self, model, reg_no, top_speed=0, nitros=False): # self.model = model # self.reg_no = reg_no # self.top_speed = top_speed # self.nitros = nitros # if self.nitros: # self.top_speed += 50 # def __str__(self): # return self.model.capitalize() # def __repr__(self): # return f"This is a Racecar with registration: {self.reg_no}" # def __call__(self): # print(f"Vroom Vroom. The {self.model} Engines Started") # def __gt__(self, other): # if self.top_speed > other.top_speed: # return True # else: # return False # def drive(self, km): # print(f"You drove the {self.model} {km} km in {km / self.top_speed} hours.") # def race(self, other_car): # if self > other_car: # print(f"I am the winner") # else: # print(f"The {other_car.model} is the winner") # class PrintList(): # def __init__(self, my_list): # self.mylist = my_list # def __repr__(self): # return str(self.mylist) # car1 = Racecar("honda", "hello", 75, True) # car2 = Racecar("civic", "bingo", 55, True) # print(car1.__gt__(car2))
0cdc78355fca028bb19c771c343ae845b702f555
Jeremyreiner/DI_Bootcamp
/week5/Day1/Daily_challenge/daily_challenge.py
2,265
4.40625
4
# Instructions : Old MacDonald’s Farm # Take a look at the following code and output! # File: market.py # Create the code that is needed to recreate the code provided above. Below are a few questions to assist you with your code: # 1. Create a class called Farm. How should this be implemented? # 2. Does the Farm class need an __init__ method? If so, what parameters should it take? # 3. How many methods does the Farm class need? # 4. Do you notice anything interesting about the way we are calling the add_animal method? What parameters should this function have? How many…? # 5. Test your code and make sure you get the same results as the example above. # 6. Bonus: nicely line the text in columns as seen in the example above. Use string formatting. class Farm(): def __init__(self, name): self.name = name self.animals = [] self.sorted_animals = [] def add_animal(self, animal, amount = ""): if animal not in self.animals: added_animal = f"{animal} : {str(amount)}" self.animals.append(added_animal) def show_animals(self): # for animal in self.animals: print(f"These animals are currently in {self.name}'s farm: {self.animals}") # Expand The Farm # Add a method called get_animal_types to the Farm class. # This method should return a sorted list of all the animal types (names) in the farm. # With the example above, the list should be: ['cow', 'goat', 'sheep']. def get_animal_types(self): if __name__ == '__main__': sorted_by_name = sorted(self.animals, key=lambda x: x.animals) print(sorted_by_name) # Add another method to the Farm class called get_short_info. # This method should return the following string: “McDonald’s farm has cows, goats and sheep.”. # The method should call the get_animal_types function to get a list of the animals. macdonald = Farm("McDonald") macdonald.add_animal('cow', 5) macdonald.add_animal('sheep') macdonald.add_animal('sheep') macdonald.add_animal('goat', 12) macdonald.show_animals() all_animals = macdonald.animals macdonald.get_animal_types() # print(macdonald.get_info()) # McDonald's farm # cow : 5 # sheep : 2 # goat : 12 # E-I-E-I-0!
7a7c944b90acd5e775968c985c9f2b58789ed4a7
christopher-henderson/thesis
/writing.py
1,896
3.53125
4
''' Wikipedia sucks...unless it doesn't. This is the N-Queens problem implemented using the following general-form pseudocode. https://en.wikipedia.org/wiki/Backtracking#Pseudocode It is getting correct answers, although I am doing something wrong and also getting duplicates. ''' N = 8 def backtrack(P, root, accept, reject, first, next, output): if reject(P, root): return P.append(root) if accept(P): output(P) P.pop() return s = first(root) while s is not None: backtrack(P, s, accept, reject, first, next, output) s = next(s) P.pop() s = next(root) if s is not None: backtrack(P, s, accept, reject, first, next, output) def root(): # Return the partial candidate at the root of the search tree. # First spot on the board. return 1, 1 def reject(P, candidate): C, R = candidate for column, row in P: if (R == row or C == column or R + C == row + column or R - C == row - column): return True return False def accept(P): # Return true if c is a solution of P, and false otherwise. # The latest queen has been verified safe, so if we've placed N queens, we win. return len(P) == N def first(root): # Generate the first extension of candidate c. # That is, if we have a placed queen at 1, 1 (C, R) then this should return 2, 1. return None if root[0] >= N else (root[0] + 1, 1) def next(child): # generate the next alternative extension of a candidate, after the extension s. # So if first generated 2, 1 then this should produce 2, 2. return None if child[1] >= N else (child[0], child[1] + 1) def output(P): print(P) def more(R): return R < N if __name__ == "__main__": backtrack([], root(), accept, reject, first, next, output) print(derp)
69005c262433db7d85e18bf3b770ca093533c99f
christopher-henderson/thesis
/backtrack/01knapsack.py
1,681
3.8125
4
from backtrack import backtrack class KnapSack(object): WEIGHT = 50 ITEMS = ((10, 60), (20, 100), (30, 120)) MEMO = {} def __init__(self, item_number): self.item_number = item_number def first(self): return KnapSack(0) def next(self): if self.item_number >= len(self.ITEMS) - 1: return None return KnapSack(self.item_number + 1) @classmethod def reject(cls, P, candidate): weight = cls.total_weight(P) if weight + candidate.weight > cls.WEIGHT or weight in cls.MEMO: # It doesn't fill up the whole bag, but it IS a solution. cls.output(P) return True return False @classmethod def accept(cls, P): return cls.total_weight(P) == cls.WEIGHT @staticmethod def add(P, candidate): P.append(tuple([candidate.weight, candidate.value])) @staticmethod def remove(P): P.pop() @classmethod def output(cls, P): weight = cls.total_weight(P) if weight in cls.MEMO: if cls.total_value(P) > cls.total_value(cls.MEMO[weight]): cls.MEMO[weight] = tuple(P) else: cls.MEMO[weight] = tuple(P) # Three helpers @staticmethod def total_weight(P): return sum(item[0] for item in P) @staticmethod def total_value(P): return sum(item[1] for item in P) @property def weight(self): return self.ITEMS[self.item_number][0] @property def value(self): return self.ITEMS[self.item_number][1] if __name__ == '__main__': backtrack(KnapSack(0), KnapSack.first, KnapSack.next, KnapSack.reject, KnapSack.accept, KnapSack.add, KnapSack.remove, KnapSack.output) print("Max total is: {}\nUsing the solution: {}".format(KnapSack.total_value(KnapSack.MEMO[KnapSack.WEIGHT]), KnapSack.MEMO[KnapSack.WEIGHT]))
9c03b56ac31edf5d0163ec4cf3a9cab915a789a4
christopher-henderson/thesis
/nQueen0.py
2,178
3.75
4
import copy N = 8 NUM_FOUND = 0 derp = list() def backtrack(P, C, R): if reject(P, C, R): return # Not a part of the general form. Should it be in 'reject'? # That would be kinda odd, but it must appended before a call to output. P.append([C, R]) if accept(P): output(P) s = first(C) while s is not None: # Explicitly passing by value (deepcopy a list) is another addition of # mine. Is this mandatory? backtrack(copy.deepcopy(P), *s) s = next(*s) # The general form admits this case, although there can be a way around it. if R < N: P.pop() backtrack(copy.deepcopy(P), C, R + 1) def root(): # Return the partial candidate at the root of the search tree. # First spot on the board. return 1, 1 def reject(P, C, R): # Return true only if the partial candidate c is not worth completing. # c, in this case, is Column and Row together. for column, row in P: if (R == row or C == column or R + C == row + column or R - C == row - column): return True return False def accept(P): # Return true if c is a solution of P, and false otherwise. # The latest queen has been verified safe, so if we've placed N queens, we win. return len(P) == N def first(C): # Generate the first extension of candidate c. # That is, if we have a placed queen at 1, 1 (C, R) then this should return 2, 1. return None if C >= N else (C + 1, 1) def next(C, R): # generate the next alternative extension of a candidate, after the extension s. # So if first generated 2, 1 then this should produce 2, 2. return None if R >= N else (C, R + 1) def output(P): # use the solution c of P, as appropriate to the application. global NUM_FOUND NUM_FOUND += 1 derp.append(P) print(P) if __name__ == "__main__": backtrack([], *root()) dupes = 0 for index, i in enumerate(derp): for j in derp[index + 1::]: if i == j: dupes += 1 print(dupes) print("Found solutions: {NUM}".format(NUM=NUM_FOUND))
7ce103ab49574b9dcb251574c06934c9fb2b00e1
SvenLC/CESI-Algorithmique
/listes/triParSelection.py
439
3.828125
4
# Ecrire la procédure qui reçoit un tableau de taille N en entrée et qui réalise un tri par sélection exemple = [1, 3, 5, 6, 3, 2, 4, 5, 6] def triParSelection(tableau, n): for i in range(0, n): for j in range(i, n): if(tableau[i] > tableau[j]): min = tableau[j] tableau[j] = tableau[i] tableau[i] = min return tableau print(triParSelection(exemple, 9))
9693d52cc708aca038148b57c23f45976ef7ef01
SvenLC/CESI-Algorithmique
/boucles/exercice6.py
331
3.5625
4
# Écrire un algorithme qui demande un nombre de départ, et qui calcule la somme des entiers jusqu’à ce nombre, # par exemple, si on entre 5, on devrait afficher 1 + 2 + 3 + 4 + 5. def somme(nombre): total = 0 for i in range(0, nombre): total = total + i print(i) return total print(somme(10))
6438fc05212750bb32b2ca3aecbfb970f7568071
cran/excerptr
/inst/excerpts/excerpts/main.py
5,131
3.5625
4
#!/usr/bin/env python3 """ @file module functions """ from __future__ import print_function import re import os def extract(lines, comment_character, magic_character, allow_pep8=True): """ Extract Matching Lines Extract all itmes starting with a combination of comment_character and magic_character from a list. Kwargs: lines: A list containing the code lines. comment_character: The comment character of the language. magic_character: The magic character marking lines as excerpts. allow_pep8: Allow for a leading comment character and space to confrom to PEP 8 block comments. Returns: A list of strings containing the lines extracted. """ matching_lines = [] if allow_pep8: # allow for pep8 conforming block comments. markdown_regex = re.compile(r"\s*" + comment_character + "? ?" + comment_character + "+" + magic_character) else: markdown_regex = re.compile(r"\s*" + comment_character + "+" + magic_character) for line in lines: if markdown_regex.match(line): matching_lines.append(line) return matching_lines def convert(lines, comment_character, magic_character, allow_pep8=True): """ Convert Lines to Markdown Remove whitespace and magic characters from lines and output valid markdown. Kwargs: lines: The lines to be converted. comment_character: The comment character of the language. magic_character: The magic character marking lines as excerpts. allow_pep8: Allow for a leading comment character and space to confrom to PEP 8 block comments. Returns: A list of strings containing the lines converted. """ converted_lines = [] for line in lines: line = line.lstrip() if allow_pep8: # allow for pep8 conforming block comments. line = re.sub(comment_character + " ", "", line) # remove 7 or more heading levels. line = re.sub(comment_character + "{7,}", "", line) line = line.replace(comment_character, "#") if magic_character != "": # remove the first occurence of the magic_character only # (the header definition of pandoc's markdown uses the # percent sign, if that was the magic pattern, all pandoc # standard headers would end up to be simple text). line = re.sub(magic_character, "", line, count=1) # get rid of leading blanks line = re.sub(r"^\s*", "", line) # empty lines (ending markdown paragraphs) are not written by # file.write(), so we replace them by newlines. if line == " " or line == "": line = "\n" converted_lines.append(line) return converted_lines def excerpt(lines, comment_character, magic_character, allow_pep8=True): """ Extract and Convert Matching Lines Just a wrapper to extract() and convert(). Kwargs: lines: A list containing the code lines. comment_character: The comment character of the language. magic_character: The magic character marking lines as excerpts. allow_pep8: Allow for a leading comment character and space to confrom to PEP 8 block comments. Returns: A list of strings containing the lines extracted and converted. """ lines_matched = extract(lines=lines, comment_character=comment_character, magic_character=magic_character) converted_lines = convert(lines=lines_matched, comment_character=comment_character, magic_character=magic_character, allow_pep8=allow_pep8) return converted_lines def modify_path(file_name, postfix="", prefix="", output_path="", extension=None): """ Modify a Path Add a postfix and a prefix to the basename of a path and change it's extension. Kwargs: file_name: The file path to be modified. postfix: Set the output file postfix. prefix: Set the output file prefix. extension: Set a new file extension. output_path: Set a new file name or an output directory. If the path given is not an existing directory, it is assumed to be a file path and all other arguments are discarded. Returns: A string containing the modified path. """ if output_path != "" and not os.path.isdir(output_path): name = output_path else: base_name = os.path.basename(os.path.splitext(file_name)[0]) ext_base_name = prefix + base_name + postfix if extension is None: extension = os.path.splitext(file_name)[1] ext = extension.lstrip(".") if output_path == "": directory = os.path.dirname(file_name) else: directory = output_path name = os.path.join(directory, ext_base_name) + "." + ext return name