blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
533b8da62de65025cbb71c981eade387bf694d68
chanshik/codewars
/dragon_curve.py
1,783
4.53125
5
""" The dragon's curve is a self-similar fractal which can be obtained by a recursive method. Starting with the string D0 = 'Fa', at each step simultaneously perform the following operations: replace 'a' with: 'aRbFR' replace 'b' with: 'LFaLb' For example (spaces added for more visibility) : 1st iteration: Fa -> F aRbF R 2nd iteration: FaRbFR -> F aRbFR R LFaLb FR After n iteration, remove 'a' and 'b'. You will have a string with 'R','L', and 'F'. This is a set of instruction. Starting at the origin of a grid looking in the (0,1) direction, 'F' means a step forward, 'L' and 'R' mean respectively turn left and right. After executing all instructions, the trajectory will give a beautiful self-replicating pattern called 'Dragon Curve' The goal of this kata is to code a function which takes one parameter n, the number of iterations needed and return the string of instruction as defined above. For example: n=0, should return: 'F' n=1, should return: 'FRFR' n=2, should return: 'FRFRRLFLFR' n should be a number and non-negative integer. All other case should return the empty string: ''. """ def Dragon(n): if not isinstance(n, int): return '' if n < 0: return '' s = 'Fa' for i in range(n): changed = list() for ch in s: if ch == 'a': changed.append('aRbFR') elif ch == 'b': changed.append('LFaLb') else: changed.append(ch) s = "".join(changed) return s.replace('a', '').replace('b', '') from unittest import TestCase class TestDragon(TestCase): def test_dragon(self): self.assertEquals('F', Dragon(0)) self.assertEquals('FRFR', Dragon(1)) self.assertEquals('FRFRRLFLFR', Dragon(2))
true
a56d602738b04e9e1aafc27f2aeff127da7a82a5
emretokk/codeforces
/800/word.py
719
4.15625
4
""" that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. ( tersine ) input : The first line contains a word s — it consists of uppercase and lowercase Latin letters and possesses the length from 1 to 100. ( sahip ) output : Print the corrected word s. If the given word s has strictly more uppercase letters, make the word written in the uppercase register, otherwise - in the lowercase one. """ s = str(input()) upcount = 0 lowcount = 0 for letter in s: if letter.isupper(): upcount+=1 else: lowcount+=1 if upcount>lowcount: print(s.upper()) else: print(s.lower())
true
8c093593ac10bc378c7c897fcfdf60d65cd7011c
Zzz-ww/Python-prac
/python_Project/Day_08/test_1.py
1,366
4.40625
4
""" 在Python中可以使用class关键字定义类, 然后在类中通过之前学习过的函数来定义方法, 这样就可以将对象的动态特征描述出来, 代码如下所示。 """ class Student(object): # __init__是一个特殊方法用于在创建对象时进行初始化操作 # 通过这个方法我们可以为学生对象绑定name和age两个属性 def __init__(self, name, age): self.name = name self.age = age def study(self, course_name): print('%s正在学习%s' % (self.name, course_name)) # PEP 8要求标识符的名字用全小写多个单词用下划线连接 # 但是部分程序员和公司更倾向于使用驼峰命名法(驼峰标识) def watch_movie(self): if self.age < 18: print('%s只能观看《熊出没》.' % self.name) else: print('%s正在观看岛国爱情大电影.' % self.name) # 当我们定义好一个类之后,可以通过下面的方式来创建对象并给对象发消息。 def main(): # 创建学生对象并指定姓名和年龄 stu_1 = Student('xiaoming', 19) # 给对象发study消息 stu_1.study('Python') # 给对象发watch_av消息 stu_1.watch_movie() stu_2 = Student('LYL', 17) stu_2.study('abc') stu_2.watch_movie() if __name__ == '__main__': main()
false
2a1fc488fef69bace682aa04094d77cd028fb993
vrednyydragon/ProjectEuler
/py_src/Problem001_2.py
815
4.25
4
class Sum(): def SumMultiplues(self, input_data): assert 0 < int(input_data), "Вводимые данные должны быть числами больше 0 числами и целыми!!!" numb = int(input_data) iterator=0 sum_ = 0 for i in range (numb): iterator=i if (iterator%3==0 or iterator%5==0): print("кратное 3 или 5: " + str(iterator)) sum_+=iterator print("сумма чисел кратных 3 и 5 : " + str(sum_)) return sum_ if __name__ == "__main__": n = Sum() print(n.SumMultiplues(1000)) '''iterator=0 sum_ = 0 for i in range (1000): iterator=i if (iterator%3==0 or iterator%5==0): print("кратное 3 или 5: " + str(iterator)) sum_+=iterator print("сумма чисел кратных 3 и 5 : " + str(sum_))'''
false
355421abb31a6d13fa52ed315082c92ce25e5272
Deepanshu276/AlgorithmToolbox
/Array/2D-array/creatingArray.py
281
4.25
4
import numpy as np arr1=np.array([[1,2,3],[4,5,6],[7,8,9]]) """Time complexity in thios is O(1) as we are simultaneously giving the value in the array but if we insert the value one by one in the array then the time complexity will be O(m*n) where m=row and n=column""" print(arr1)
true
f51c20b97fc016f582163475675042b425a394b1
18516264210/MachineLearning
/sorts/select_sort.py
1,602
4.28125
4
""" 使用选择排序法进行数据的排序 什么是选择排序,通过内层循环,找到值最大的索引,然后将最大值放在最后面; 或者是通过内层循环,找到值最小的索引,然后将最小值放在最前面。 正序和逆序无所谓 """ def select_sort_1(): """对数组进行从小到大排序,先排小值到最前""" data = [9,3,7,6,5,4,8,2,1] for i in range(len(data)): index = i # 从index开始遍历,与下一个元素进行比较,获取到值为最大的index for j in range(i,len(data)): # 这里获取到的是值为最小的index,并且将当前位置i替换为本次循环的最小值。 # 即:这里排序是先排小元素,再排大元素 if data[index] > data[j]: index = j if not index == i: data[i], data[index] = data[index], data[i] return data def select_sort_2(): """对数组进行从小到大排序,先排大值到最后""" data = [9, 3, 7, 6, 5, 4, 8, 2, 1] for i in range(len(data)-1): index = 0 # 这里找到最大的index for j in range(len(data)-i): if data[index] < data[j]: index = j # 将最大的元素放在最后面,所以这里需要通过下标,定位到最后 if not index == i: data[len(data)-i],data[index] = data[index],data[len(data)-i] return data; def main(): print(select_sort_2()) a = (1,2,3,4,5,6) print(a[0]) if __name__ == "__main__": main()
false
d84a72df4fd58fba1a1aedfe016ebdb18b33705d
ProProgrammer/asyncio-rp
/theory.py
1,567
4.1875
4
from typing import Generator from random import randint import time import asyncio def odds(start, end) -> Generator: """ Produce a sequence of odd values starting from start until end including end Args: start: end: Returns: Yield each value """ for odd in range(start, end + 1, 2): yield odd def randn_synchronous_version(): time.sleep(3) return randint(1, 10) async def randn(): await asyncio.sleep(3) return randint(1, 10) async def square_odds(start, stop): for odd in odds(start, stop): await asyncio.sleep(2) # This is what makes this function asynchronous, we are pretending that we are # talking to a database or a webserver or a file system yield odd ** 2 # Because we want a generator async def main(): odd_values = [odd for odd in odds(3, 15)] odds2 = tuple(odds(21, 29)) # print(odd_values) # print(odds2) start = time.perf_counter() r = await randn() elapsed = time.perf_counter() - start print(f'{r} took {elapsed:0.2f} seconds.') start = time.perf_counter() r = await asyncio.gather(*[randn() for _ in range(10)]) elapsed = time.perf_counter() - start print(f'{r} took {elapsed:0.2f} seconds.') # Normally for a generator you'd use for..in loop, because this is an async generator, you'd use async for..in loop async for so in square_odds(11, 17): print(f'so is {so}') if __name__ == "__main__": asyncio.run(main()) # this creates the event loop for our async tasks
true
071429abd45ee187f732a3cd50c13088eb94f720
knparikh/IK
/LinkedLists/clone_arbit_list/clone.py
2,428
4.15625
4
#!/bin/python class Node: def __init__(self, node_value): self.val = node_value self.next = None self.arbit = None # Given a doubly linked list with node having one pointer next, other pointer arbit, pointing to arbitrary node. Clone the list. # Approach 1: Uses extra space O(n) in hash table: Use hash table of existing node to new node. Go through each node, make new_node.arbit = hash[curr_node.arbit]. # Also new_node.next = hash[old_node.next] # # Apprach 2: Use O(1) extra space. # 1. For each node, make its clone the next node. # 2. In the second pass make the arbit of clone point to old node's arbit's next # 3. Restore both lists by making their next point to next.next. # def clone_list(root): if root == None: return None old_node = root # Insert cloned nodes after each node in the linked list while(old_node): temp = old_node.next new_node = Node(old_node.val) old_node.next = new_node # Old node1 -> New node1 new_node.next = temp # Old node1 -> New node1 -> Old node2 old_node = temp old_node = root # Adjust arbit pointers while (old_node): new_node = old_node.next new_node.arbit = old_node.arbit.next # Next of old node's arbit, is the cloned arbit old_node = new_node.next # Separate both lists old_node = root root2 = root.next while(old_node): new_node = old_node.next if new_node: old_node.next = new_node.next if new_node.next: # For last new node, new_node.next will be None new_node.next = new_node.next.next old_node = old_node.next return root2 def print_list(root): curr = root print 'next:' while(curr): print curr.val, curr = curr.next print '\n' curr = root print 'arbit:' while(curr): print curr.arbit.val, curr = curr.next print '\n' if __name__ == "__main__": node1 = head = Node(1) node2 = Node(2) node3 = Node(3) node4 = Node(4) node5 = Node(5) node1.next = node2 node2.next = node3 node3.next = node4 node4.next = node5 node1.arbit = node3 node2.arbit = node1 node3.arbit = node5 node4.arbit = node3 node5.arbit = node2 head2 = clone_list(head) print_list(head2) print_list(head2)
true
f8eb3b6c2dc76f5a4c18e962b994df7219510308
knparikh/IK
/Recursion/class_learnings.py
2,970
4.25
4
def fibo(n): if (n == 0) or (n == 1): return n return fibo(n-1) + fibo(n-2) # Tips to write recursive functions # Define function meaningfully # Think about base cases, what's already defined # Think about the typical case # Example: # Merge sort # Recurrence relationship # Define function: merge (a (ignore static data), start, end) # Base case: If st >= end, do nothing or just return # Typical case: merge(a, start, mid) # merge(a, mid+1, end) # Merge the two sorted array # Make a execution tree. Helps to compute run time of function - it is the number of nodes in the tree. O(n) # Space complexity - Height of tree O(height of tree), largest number of stacks when reaching leaf node # f(4) # f(2) f(3) # f(0) f(1) f(1) f(2) # f(0) f(1) # # # Number of nodes in complete binary tree - geometric progression # Constant ratio across term # # solve geometric progression # Sum a*r^i (for i from 0 to n-1) = a.(r^n -1)/ r-1 # To prove: # Expand: # a + ar + ar^2 + ...ar^n-1 # a (1+r+r^2+r^3+...r^n-1) # a (r-1)/(r-1) (1+r+r^2+r^3+...r^n-1) # = a.(r^n-1)/(r-1) # In above example: a = 1, r = 2 # # # Arithmetic progression # 1+2+3+4..+N = n * (n+1) /2 # # # Towers of Hanoi # # # # Towers of Hanoi using stack class StackFrame(object): def __init__(self, n, st, end, helper) self.n = n self.st = st self.end = end self.helper = helper def toh(n): stack = () for i in range(n, -1, -1): if (n-i) % 2 == 0 end = B helper = C else: end = C helper = B # Given an array of size n, print all its subsets. Elements can be repeated. # n c 0 subets of size 0 # n c 1 subsets of size 1 # n c 2 subsets of size 2.. # nCr is number of ways we can pick r things out of N things # nC0 = 1, nCn = 1 # Total # of subsets = nC0 + nC1 + ...nCn = 2^n # def subsets(arr): helper(arr, 0,[None]*len(arr), 0) def helper(arr, i, op, op_idx): if i == len(arr): print op[:op_idx] return #exclude helper(arr, i+1, op, op_idx) #include op[op_idx] = arr[i] helper(arr, i+1, op, op_idx + 1) # Recursion with backtracking # Example print all subsets that add upto <= k def helper_backtrack(arr, i, op, op_idx, total): if i == len(arr): print op[:op_idx] return #exclude helper(arr, i+1, op, op_idx, total) #include if ((arr[i+1] + total) < k): op[op_idx] = arr[i] helper(arr, i+1, op, op_idx + 1) # permutations of set def permutations(arr): p_helper(arr, 0) def p_helper(arr): if i == len(arr): print arr return for index in range(i, len(arr)): swap(arr, i , idx) helper(arr, i+1) swap(arr, i, idx) # N Queens problem
true
b314f7c064518604957fc677897c33f51afc584e
knparikh/IK
/LinkedLists/median/median.py
1,741
4.125
4
#!/bin/python3 import sys import os class LinkedListNode: def __init__(self, node_value): self.val = node_value self.next = None def _insert_node_into_singlylinkedlist(head, tail, val): if head == None: head = LinkedListNode(val) tail = head else: node = LinkedListNode(val) tail.next = node tail = tail.next return tail # NOTE random pointer given # Find the length of the circular linked list # Also need to find start of linked list based on ascending or descending # order(smallest/largest element) # Use length or slow/fast logic to find median # To find the ascending/descending - compare 3 elements, or go to next smallest # element from ptr, then decide. def find_median(ptr): if ptr == None or ptr.next == None: return ptr.val index = 0 slow = ptr fast = ptr.next prev = None #import pdb; pdb.set_trace() while((fast.val != ptr.val) and (fast.next.val != ptr.val)): prev = slow slow = slow.next fast = fast.next.next index += 1 if fast.val == ptr.val: return slow.val else: return (prev.val + slow.val)/2 if __name__ == "__main__": ptr = None ptr_tail = None ptr_size = int(input()) ptr_i = 0 while ptr_i < ptr_size: ptr_item = int(input()) ptr_tail = _insert_node_into_singlylinkedlist(ptr, ptr_tail, ptr_item) if ptr_i == 0: ptr = ptr_tail ptr_i += 1 #----added manually---- ptr_tail.next = ptr arbitrary_shift = int(input()) while (arbitrary_shift > 0): arbitrary_shift -= 1 ptr = ptr.next #-------- res = find_median(ptr) print res
true
ccaee08097c8797bd374e374e9936f174142fd3d
walkrrr/110-L3-Soft-Build-A-Birthday-Reminder-App-Starter-1
/main.py
300
4.25
4
user_input = input("Enter a person's name: ") if user_input == "Walkrrr": print("Birthday is 12/26/1983!") elif user_input == "Missy": print("Birthday is 05/03/2006!") elif user_input == "DeVon": print("Birthday is 06/23/1983") else: print("Can't find a birthday for this person")
false
25450a5f381210b30eff26600fdf9377b7762cd4
joepark92/students_and_grades
/students_n_grades.py
1,741
4.15625
4
studentinfo = [] course_dict = { 1: 'Math', 2: 'Science', 3: 'History' } while True: numStudents = input("How many students do you have: ") try: numStudents = int(numStudents) except: print('Invalid entry... Try using digits, ex. 1, 2, 3, etc.') continue if numStudents < 1: print('Please enter a valid number.') continue break for x in range(numStudents): while True: student_name = input("Student's name: ") try: student_name = str(student_name) except: continue if student_name == "": print('Please enter a valid name.') continue break while True: student_grade = input("Student's grade: ") try: student_grade = int(student_grade) except: print('Invalid entry... Use a number grade system.') continue if student_grade > 100 or student_grade < 0: print('Please enter a valid grade.') continue break while True: student_course = input("Select a course -- 1.Math, 2.Science, 3.History: ") try: student_course = int(student_course) except: print('Invalid entry... try using 1, 2, or 3.') continue if student_course > 3 or student_course < 0: print('Please select 1, 2, or 3.') continue break print() studentinfo.append({'Name':student_name, 'Grade':int(student_grade), 'Course':int(student_course)}) for i in range(numStudents): print(f"Name: {studentinfo[i]['Name']}, Grade: {studentinfo[i]['Grade']}, Course: {course_dict[studentinfo[i]['Course']]}")
true
85490c42ce849d03911999af97526f3dc1ef6c75
TSantosFigueira/Python_Data-Structures
/Data Structures - Array/ReverseString.py
456
4.34375
4
strings = "Hi, my name is Thiago!" # approach 01 print(strings[::-1]) # approach 02 def reverseString(strings): for i in range(len(strings) - 1, -1, -1): print(strings[i], end='') #approach 03 def reverseStringWithList(strings): newStrings = [] for i in range(len(strings) - 1, -1, -1): newStrings.append(strings[i]) return "".join(newStrings) reverseString(strings) print() # skip a new line print(reverseStringWithList(strings))
true
a1c101827947b2ebc854c39bcda7bed452c54aa9
sebastianhlaw/tensorflow-benchmark
/python/playground/get_started_contrib_learn.py
1,466
4.15625
4
# Getting started with TensorFlow # https://www.tensorflow.org/get_started/get_started import tensorflow as tf import numpy as np # Declare list of features. We only have one real-valued feature. There are many other types of columns that are more # complicated and useful. features = [tf.contrib.layers.real_valued_column("x", dimension=1)] # An estimator is the front end to invoke training (fitting) and evaluation (inference). There are many predefined # types like linear regression, logistic regression, linear classification, logistic classification, and many neural # network classifiers and regressors. The following code provides an estimator that does linear regression. estimator = tf.contrib.learn.LinearRegressor(feature_columns=features) # TensorFlow provides many helper methods to read and set up data sets. Here we use `numpy_input_fn`. We have to tell # the function how many batches of data (num_epochs) we want and how big each batch should be. x = np.array([1., 2., 3., 4.]) y = np.array([0., -1., -2., -3.]) input_fn = tf.contrib.learn.io.numpy_input_fn({"x": x}, y, batch_size=4, num_epochs=1000) # We can invoke 1000 training steps by invoking the `fit` method and passing the training data set. estimator.fit(input_fn=input_fn, steps=1000) # Here we evaluate how well our model did. In a real example, we would want to use a separate validation and testing # data set to avoid over-fitting. print(estimator.evaluate(input_fn=input_fn))
true
64f2ec55e0ab9699b5d20eb1bb9408e8757f4050
pedrocambui/exercicios_e_desafios
/python/cursoemvideo/ex075.py
1,086
4.15625
4
tupla = (int(input('Digite um número: ')), int(input('Digite um número: ')), int(input('Digite um número: ')), int(input('Digite um número: '))) par = False print(f'O valor 9 apareceu {tupla.count(9)} vezes.') if 3 in tupla: print(f'O valor 3 apareceu na {tupla.index(3)+1}º posição.') else: print('O valor 3 não foi digitado em nenhuma posição.') print('Os valores pares digitados foram: ', end='') for c in range(0, 4): if tupla[c] % 2 == 0: par = True if par == True: print(tupla[c], end=' ') """tupla = (int(input('Digite um número: ')), int(input('Digite um número: ')), int(input('Digite um número: ')), int(input('Digite um número: '))) par = False print(f'O valor 9 apareceu {tupla.count(9)} vezes.') if 3 in tupla: print(f'O valor 3 apareceu na {tupla.index(3)+1}º posição.') else: print('O valor 3 não foi digitado em nenhuma posição.') print('Os valores pares digitados foram: ', end='') for n in tupla: if n % 2 == 0: print(n, end=' ') """
false
6bd1ef758a24b491de6487685bdba70f50859418
timsergor/StillPython
/008.py
283
4.125
4
#Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A. odd = [] even = [] for i in range(len(A)): if A[i] % 2 == 0: even.append(A[i]) else: odd.append(A[i]) print(even+odd)
true
99774c11dcd328634fdfe51602b7453bf243a610
timsergor/StillPython
/105.py
1,582
4.25
4
#1042. Flower Planting With No Adjacent. Easy. 47.7%. #You have N gardens, labelled 1 to N. In each garden, you want to plant one of 4 types of flowers. #paths[i] = [x, y] describes the existence of a bidirectional path from garden x to garden y. #Also, there is no garden that has more than 3 paths coming into or leaving it. #Your task is to choose a flower type for each garden such that, for any two gardens connected by a path, they have different types of flowers. #Return any such a choice as an array answer, where answer[i] is the type of flower planted in the (i+1)-th garden. The flower types are denoted 1, 2, 3, or 4. It is guaranteed an answer exists. class Solution: def gardenNoAdj(self, N: int, paths: List[List[int]]) -> List[int]: char = {} for i in range(len(paths)): if paths[i][0] not in char: char[paths[i][0]] = [paths[i][1]] else: char[paths[i][0]].append(paths[i][1]) if paths[i][1] not in char: char[paths[i][1]] = [paths[i][0]] else: char[paths[i][1]].append(paths[i][0]) flowers = [0] * N for i in range(N): if i + 1 not in char: char[i + 1] = [] neir = [flowers[j - 1] for j in char[i + 1]] if 1 not in neir: flowers[i] = 1 elif 2 not in neir: flowers[i] = 2 elif 3 not in neir: flowers[i] = 3 else: flowers[i] = 4 return flowers
true
4be06146f86619793040004e9139480283895ba7
Skippi-engineer/Console-Games
/Rock paper scissors.py
1,207
4.15625
4
# # Simple console game rock paper scissors: # from random import* game = True while game: player = (input("rock/paper/scissors: ")).lower() rand = randint(1, 3) if rand == 1: print("rock") if player == "rock": print("Tie!") elif player == "paper": print("You win!") elif player == "scissors": print("You lose!") elif rand == 2: print("paper") if player == "rock": print("You lose!") elif player == "paper": print("Tie!") elif player == "scissors": print("You win!") elif rand == 3: print("scissors") if player == "rock": print("You win!") elif player == "paper": print("You lose!") elif player == "scissors": print("Tie!") if player != "rock" and player != "paper" and player != "scissors": print("It is invalid word! Rock, paper or scissors!") else: player = input("You want to play again? (yes or no): ").lower() if player == "yes": game = True else: game = False
true
65779d0cd88f215d09e94b49567fe0ebdec5c83c
donaq/scramblecheatpy
/scramblecheat.py
1,524
4.21875
4
#!/usr/bin/python import sys import readline from scheathelpers import * if len(sys.argv)!=2: print "Usage: scramblecheat.py <dictionary file>" exit() words = read_dictionary(filename=sys.argv[1]) if not words: exit() print "\nFor instructions, type 'help'. To exit the program, press the Enter key.\n" instructions = """Welcome to the Scramble Cheater To access this instruction again, enter "help". To exit the program, enter an empty string. To enter a board, key in the letters on the board in the order from left to right from top to bottom: For example, if the board is A B C D E F G H I J K L M N Qu P key in "abcdefghijklmnqup" or "abcdefghijklmnqp" Notes: 1) In the case of the "Qu" tiles, the "u" is optional. However, if a "u" follows a "q", the program will take them to mean one tile 2) This program accepts only 4 by 4 and 5 by 5 boards """ while True: letters = raw_input("Enter a board >> ").strip().lower() if letters == "help": print instructions continue if not len(letters): break try: board,boardsize = createTiles(letters) except WrongBoardSizeError: print "There must be either 16 tiles or 25 tiles, genius. Cheat with intelligence!\n" continue except InvalidCharError: print "Only alphabets are valid tiles, Einstein. Cheat with intelligence!\n" continue for word in words: for tile in board: if findWord(word,board,0,tile,len(word)): print word.replace("q","qu") setUnused(board) break print "Thanks for using the python scramble cheat, you disgusting creature!"
true
be0404d73463c30014cddb01f3ba109e5c04b94d
chaitan64arun/algo-ds
/array_element_appearance.py
623
4.34375
4
#!/usr/bin/python """ https://www.careercup.com/question?id=5664477329489920 You have given an array of integers. The appearance of integers vary (ie some integers appears twice or once or more than once) How would you determine which integers appeared odd number of times ? a[] = { 1,1,1, 2,5,10000, 5,7,4,8} as you can see 1 appeared 3 times, 2 appeared once etc """ def outputOdd(argArray): finalArray = [] for i in argArray: if i not in finalArray: finalArray.append(i) else : finalArray.remove(i) print finalArray array = [1,2,3,4,4,4,2,3,1] outputOdd(array)
true
bb5a6198910d5e8cb45c4e0ac03002e33b5c3cbb
Elvis-IsAlive/python
/printDirectory.py
1,901
4.15625
4
#! /usr/bin/python3 """List the content of a directory to the depth of -directory""" import os import sys import argparse def printDir(directory, depth, lvl = 0): """prints the directories and files of a directory""" os.chdir(directory) for e in sorted(os.listdir()): #only non-hidden elements if not str(e).startswith("."): #files if os.path.isfile(e): if lvl > 1: print("\t" * (lvl - 1) + "--> " + e) else: print("--> " * lvl + e) #directories elif os.path.isdir(e): if lvl > 1: print("\t" * (lvl -1) + "--> " + e) else: print("--> " * lvl + e) if depth > 0: printDir(e, depth - 1, lvl + 1) os.chdir("..") def printMessage(): """Prints initial message including given arguments""" width = 90 print() print("".center(width, "+")) info = " CONTENT OF " + directory + ", DEPTH: " + str(depth) + " " print(info.center(width, "+")) info = " ARGUMENTS GIVEN: " + str(sys.argv[1:]) + " " print(info.center(width, "+")) print("".center(width, "+")) print() def pareseArguments(): """Parses the command line arguments to assign global variables""" global directory, depth parser = argparse.ArgumentParser(description = "Show content of given directory down to specified depth") parser.add_argument("directory", type=str, help="defines the directory") parser.add_argument("-d", "--depth", type=int, default = 0, help="defines the depth") args = parser.parse_args() print(args) directory = args.directory depth = args.depth if __name__ == "__main__": directory = "" depth = 0 pareseArguments() printDir(directory, depth)
true
c0f083cbddfb27401321e3d95d30056d42d0e81a
m2mathew/learn-python-in-one-day
/03_variables.py
730
4.25
4
# Chapter 3: The World of Variables and Operators userAge = 0 userAge, userName = 30, 'Peter' ''' Variable names can contain letters, numbers, or underscores But they cannot start with a number Can only start with a letter or underscore ''' # Here we go x = 5 y = 10 # x = y y = x print ('x = ', x) print ('y = ', y) # Operator examples a, b = 5, 2 # Basic operators # addition print (a + b) # subtraction print (a - b) # multiplication print (a * b) # division print (a / b) # floor division (rounds down to the nearest whole number) print (a // b) # modulus (gives the remainder) print (a % b) # exponent print (a ** b) # Even more operators! c = 10 # c = c + 2 can be rewritten as: c += 2 print (c) c -= 2 print (c)
true
36b7c19b65d70daf224f1f10e07986107572ab00
dconn20/labs.2020
/student.py
609
4.1875
4
# A Program that reads in students # until the user enters a blank # and then prints them all out again students = [] firstname = input("Enter first name (blank to quit): ").strip() while firstname != "": student = {} student ["firstname"] = firstname lastname = input ("Enter lastname: ").strip() student ["lastname"] = lastname students.append(student) firstname = input("Enter first name (blank to quit): ").strip() print ("Here are the student you entered:") for currentstudent in students: print ("{} {}".format(currentstudent["firstname"], currentstudent ["lastname"]))
true
0cd0946d99ab89504458e247982945c91fdeeebf
jmanndev/41150-Exercises
/Tutorial2/calculator-with-tax.py
775
4.375
4
# 1. Write a python program that act as a cashier which will prompt the user # for numbers that can be either integers or floats until the user enters 0. # The program should accumulate all the entered numbers up until the 0 # and provide the total before and after tax. Tax is 0.05 def inputNumber(prompt): while True: try: userInput = float(input(prompt)) except (NameError, ValueError, SyntaxError): print(" Not a number! Try again.") continue else: return userInput break total = 0 while True: n = inputNumber("Enter value (0 to end): ") if n == 0: break else: total += n print("Before tax: " + str(total)) print("After tax: " + str(total*1.05))
true
85fdc56db8157d1a346840760d4084f2b4d366e0
Coditya0809/CodersPack
/Python/Task5.py
291
4.21875
4
months=["january","february","march","april","may","june","july","august","september","october","november","december"] month_days=[31,28,31,30,31,30,31,31,30,31,30,31] month=input("Enter the month: ") for i in range (12): if(month.lower()==months[i]): print(month_days[i])
false
477b7094c6ee99f09ac6d61a4d571f06b570bacf
Xenom-msk/Exercises-from-Teach-Your-Kids-to-Code-by-Bryson-Payne
/Exercises-for Teach Your Kids to Code by Bryson Payne/What_to_wear.py
473
4.28125
4
# What to wear? rainy=input("How's the weather? Is it raining? (y/n)").lower() cold=input("Is it cold today? (y/n)").lower() if (rainy=='y' and cold=='y'): print("You'd better wear a raincoat.") elif (rainy=='y' and cold!='y'): print("Carry an umbrella with you.") elif (rainy!='y' and cold=='y'): print("Put on a jacket, it's cold outside.") elif (rainy!='y' and cold!='y'): print("It's warm outside, put on your favorite fashionable clothes!")
true
a2ac7d561a73a8d5ed225aa1e9385b01b85c9f01
Xenom-msk/Exercises-from-Teach-Your-Kids-to-Code-by-Bryson-Payne
/Exercises-for Teach Your Kids to Code by Bryson Payne/Pizza_calculator.py
663
4.34375
4
# Pizza cost calculator # How many pizzas they want number_of_pizzas=eval(input("how many pizzas do you want? ")) # Cost of each pizza cost_per_pizza=eval(input("how much does each pizza cost? ")) # Calculate the total cost of the pizzas as our subtotal subtotal=number_of_pizzas*cost_per_pizza # Calculate sales tax owed, at 8% of the subtotal tax_percent=0.08 tax=subtotal*tax_percent # Add the sales tax to the subtotal for the final total total=subtotal+tax # Show the user the total amount due, including tax print("Your order costs", total, "dollars") print("Sales tax is", tax, "becouse sales tax in our contry is", tax_percent)
true
bd4e1edd47f082abe6726aab34a9741e71f991b9
KolienPleijsant/assignment
/assignment_2_Kolien.py
2,241
4.34375
4
#open the csv file politicians = open("politicians.csv") #make a multidimensional list and set indext to 0 newlist = [] index = 0 #strip the csv and make it a multidimensional list for info in politicians: infosplit = info.strip().split(",") newlist.append(infosplit) firstname = infosplit[0] lastname = infosplit[1] year = infosplit[2] party = infosplit[3] print(str(index) + " " + firstname + " " + lastname + " was born in " + year + " and a member of the " + party + " party.") index = index + 1 #close the csv file politicians.close() #print how many rows there are in the list print("There are " + str(index) + " politicians in the list.") #make a while loop to to get back everytime to the questions while True: #ask what they want to do print("What do you want to do?") print("To remove a person, type a") print("To add a person, type b") print("To save the database, type c") print("To quit the program, type d") answer = input("Type here your answer: ") #remove a person from the list by using the indexnumber and .pop if answer == "a" or answer == "A": removeperson = input("Who do you want to remove? Type the indexnumber: ") newlist.pop(int(removeperson)) print("You have deleted " + newlist[int(removeperson)][0] + " " + newlist[int(removeperson)][1]) #add a person to the list by asking the variables and adding them to newlist by using .append elif answer == "b" or answer == "B": addfirstname = input("What is the first name? ") addlastname = input("What is the last name? ") addyear = input("Which year is he or she born? ") addparty = input("For which party is he or she working? ") newrow = [addfirstname, addlastname, addyear, addparty] newlist.append(newrow) #save the list to list to the newpoliticians csv file and quit the program. elif answer == "c" or answer == "C": index = 0 politicians = open("politicians.csv", "w") for information in newlist: infojoin = ",".join(information) + "\n" politicians.write(infojoin) index = index + 1 print("It is saved to politicians.csv") politicians.close() #exit the program elif answer == "d" or answer == "D": print("Goodbye") exit() #if someone typed another letter, exit the program else: exit()
true
890a2648b66de9c0746fb84e17d227f4569e1044
maddurivenkys/trainings
/AI_ML/training/Day1/home_work/median.py
487
4.15625
4
# -*- coding: utf-8 -*- """ Created on Mon Oct 14 21:55:07 2019 @author: e1012466 """ # is a floor division operator which will round the result to nearest integer # Python program to print # median of elements # list of elements to calculate median n_num = [1, 2,7, 8, 9,3, 4, 5,6] n = len(n_num) n_num.sort() if n % 2 == 0: median1 = n_num[n//2] median2 = n_num[n//2 - 1] median = (median1 + median2)/2 else: median = n_num[n//2] print("Median is: " + str(median))
true
ed71969d9316cc5e19d9a2e706eed432c499af66
freena22/Python-Practice-Book
/09_function_design.py
2,861
4.4375
4
# Functions and Function Design def readable_timedelta(days): """Print the number of weeks and days in a number of days.""" #to get the number of weeks we use integer division weeks = days // 7 #to get the number of days that remain we use %, the modulus operator remainder = days % 7 return "{} week(s) and {} day(s)".format(weeks, remainder) def welcome_message(name): #Prints out a personalised welcome message return "Welcome to this Python script, " + name + "!" #Call the welcome message function with the input "Udacity Student" #and print the output print(welcome_message("Luka")) def which_prize(points): if points <= 50: return "Congratulations! You have won a wooden rabbit!" elif points <= 150: return "Oh dear, no prize this time." elif points <= 180: return "Congratulations! You have won a wafer-thin mint!" else: return "Congratulations! You have won a penguin!" print(which_prize(77)) # Out: Oh dear, no prize this time. def which_prize2(points): """ Returns the number of prize-winning message, given a number of points """ prize = None if points <= 50: prize = "a wooden rabbit" elif 150 <= points <= 180: prize = "a wafer-thin mint" elif points >= 181: prize = "a penguin" if prize: return "Congratulations! You have won " + prize + "!" else: return "Oh dear, no prize this time." # Case Study: Scores To Rating Function Design def convert_to_numeric(score): """ Convert the score to a float. """ converted_score = float(score) return converted_score def sum_of_middle_three(score1,score2,score3,score4,score5): """ Find the sum of the middle three numbers out of the five given. """ max_score = max(score1,score2,score3,score4,score5) min_score = min(score1,score2,score3,score4,score5) sum = score1 + score2 + score3 + score4 + score5 - max_score - min_score return sum def score_to_rating_string(av_score): """ Convert the average score, which should be between 0 and 5, into a rating. """ if av_score < 1: rating = "Terrible" elif av_score < 2: rating = "Bad" elif av_score < 3: rating = "OK" elif av_score < 4: rating = "Good" else: #Using else at the end, every possible case gets caught rating = "Excellent" return rating # Trick: Mutable default Arguments def todo_list(new_task, base_list=['wake up']): base_list.append(new_task) return base_list todo_list('check the mail') # Out: ['wake up','check the mail'] todo_list('running') # Out: ['wake up','check the mail','running'] # Lists are mutable objects. This list object is used everytime the function is called, it isn't redefined each time.
true
26749abc649c1667a32bc15e118615cf5aa7ea90
nicsins/PLDC1150
/week3/practice.py
323
4.3125
4
from datetime import date from datetime import time from datetime import datetime print(f"Todays date is {date.today()}") print(f"The time is {datetime.time(datetime.now())}") print(f"Todays date and time is {datetime.today()}") city="Minneapolis" date=date.today() print(f'in the city of {city} and the date is {date}')
true
69353e9ee5e34e7ea82bc96ca05e5a4c7465b623
nicsins/PLDC1150
/Week5/texbook.py
2,395
4.28125
4
''' texbook program author =__DomiNic__ this is an example program of ways to use data validation for integers and floats along with presenting a solid example of nested loops **improved from lab notes***''' print('Welcome to the book shop') #start with getting user input and defining variables head="*"*40#simple decoration print(head) while True: #ask number of books as a string items =input('How many books is the customer buying? ') if not items.isnumeric():# isnumeric evaluates strings not int or float print("number must be a whole number greater than 0") continue elif int(items)<1:# cast as int to check if greater than zero only after the numeric condition is met print('must be greater than zero') continue else:#cast as integer and break the validation loop items=int(items) total = 0.0#initialize accumulator for item in range(items):#initialize for loop while True:#data validation for a float try:#exception handling checks for value error first price = float(input(f'Enter price of item #{item + 1}: '))#user input displays iteration except ValueError: print('enter a proper price in numbers ') continue# if there is an error loop continues if price<0:#conditional loop checks for number less than 0 print('muust be greater than 0') continue else: #all conditions met loop is broke break total = total + price # after data is validated accumulation occurs if item!=(items-1): # conditional loop to ensure logical output print(f'{"Running subtotal":.<30}${total :<8.2f}') else: break #final informitive output displayed print(f'{"Grand total":.<30}${total :<8.2f}')#double quotes must be used for any strings withing {} formatting #caculations in formating allowed when value is not repeated print(f'{"Average price per book":.<30}${total/items :<6.2f}') print(head) #ask user to quit close = input('Time to close? Enter y to quit any other key to continue:').lower()#turns to lowercase in case y is Y if close == 'y': break print(head) print('Thanks for using the program')
true
28ccf0700be7b1acdcb4faace4b4b85c26ee6c20
nicsins/PLDC1150
/Week2/practice.py
643
4.15625
4
def getInput(): return [int(input(f'enter score for test # {i+1}'))for i in range( int (input('How many test scores would you like to enter')))] def print_Output(nums): print('the values entered are ',end='') [print(i,' ',end='')for i in nums] print() print(f'The highesty score was {max(nums)}') print(f'the lowest score was {min(nums)}') print(f'the average score is {sum(nums)/len(nums)}') print(f'the sum of all the scores is {sum(nums)}') print (f'the sum of scores minus highest and lowest is {sum(nums)-(max(nums)+min(nums))}') if __name__ == '__main__': nums=getInput() print_Output(nums)
true
00cd83ab8506bfd32b82aa0998e845273df415ee
nicsins/PLDC1150
/Week4/apollo.py
525
4.125
4
''' author=-nic_ asks user what year we landed on the moon and tells you if you got it right 09/18/2018''' #get user input establish var right_year=1969 year = input('What year did Apollo 11 land on the moon? ') while year== '' or year.isalpha(): year = input('What year did Apollo 11 land on the moon? ') year=int(year) if year == right_year: print(f'Correct! {year} is right!') elif abs(year-1969)<=10: print(f'you are within {abs(year-1969)} years') else : print(f'Sorry, {year} is the wrong answer.')
false
07e258168dc94bf9a5f50ff74a3d15270ee86785
tessam30/Python
/examples/katrina.py
1,005
4.125
4
# Answering questions about Katrina text using Python text handling abilities f = open("katrina_advisory.txt") text = f.read() f.close() print 'Content of "katrina_advisory.txt"' print '-' * 51 print print text # Q1. Strip leading spaces and make everything lowercase text_clean = text.lower().strip() print text_clean # Q2. Count the number of times keywords appear in the text wrd_lst = ["killed", "destroyed", "death", "devastating"] # Set a text_count variable as a float to avoid rounding issues later on text_count = 0.0 for word in wrd_lst: print text_clean.count(word) text_count += text_clean.count(word) print text_count # Q3. Is the advisory urgent? is_urgent = text_clean.startswith("urgent") print is_urgent # Note hte use of split() to recover total number of words (not characters) no_words = len(text.split()) print no_words # What is the ratio of alarming words to total words? print text_count / no_words print "Alarming words ratio = {:.3f}".format(text_count/no_words)
true
72b9ddc4835863a9d492f7164d30dcb70dc5be1e
caspian2012/Wang_Ke_python
/HW1_12.py
1,595
4.25
4
""" Question 12""" # Import defaultdict function. from collections import defaultdict def ana_finder(file_name): # Open the file, read it and add the raw stripped words into a list. words = [] with open(file_name, 'r') as f: for line in f: words.append(line.rstrip()) # We find words are anagram must have the same letters and have the same # length after they are sorted. To achieve a dictionary where the keys are # each of the sorted words of anagram, the values are the anagrams of such # letter combinations, we use the function defaultdict. We assign # "anadict" to a dictionary with the above keys and values hold. The # dictionary is a list of (anagram, anawords) where "anagram" is the key, # and "anawords" is the value. anagramdict = defaultdict(list) for word in words: key = ''.join(sorted(word)) anagramdict[key].append(word) # We set the biggest length value of anawords to 0 then # replace it whenever a bigger length value of anawords is found to get # the words length of the anagrams with the most words in them. longest_ana = 0 for anagram, anawords in anagramdict.items(): if len(anawords) > longest_ana: longest_ana = len(anawords) # After finding the max value of anaword length, we print the anagrams # with the most words in them for anagram, anawords in anagramdict.items(): if len(anawords) > longest_ana-1: print (anagram, anawords) # Output the result when given an input. ana_finder('sample.txt')
true
14e196f86efa736320d4cbadae7ae7356813f13c
caspian2012/Wang_Ke_python
/HW1_2.py
739
4.53125
5
""" Question 2""" # Construct a funtion to find semordnilap that finds semordnilap pairs of a # list of words. def semordnilap(file): # Access a file, read its content and split the list of words into # individual ones. file = open ('sample.txt').read() words = file.split() # Set the default empty result list results = [] # For any word in the list, if we can find another word that is its # reverse, then we add the word pair to the result list. for word_a in words: for word_b in words: if word_b == word_a[::-1]: results.append((word_a),(word_b)) return results # Print the result list. print(semordnilap('sample.txt'))
true
52eddb29c7f0432d6837f9871af6fe604db1e06c
Jack-Sh/03_Higher_Lower
/03_secret_compare.py
1,847
4.125
4
# HL component 3 - compare secret and users guess # To Do # If users guess is below secret print too low # If users guess is above secret print too high # If users guess is the secret print congratulations # Function to check low, high, guess, and round numbers def int_check(question, low=None, high=None): situation = "" # If user has specified a low and a high # number (eg. when guessing) # set the situation to 'both' if low is not None and high is not None: situation = "both" # If user has only specified a low number # (eg. when enetering high number) # set situation to 'low only' elif low is not None and high is None: situation = "low only" while True: try: response = int(input(question)) # checks input is not too high or # too low if both upper and lower bounds # are specified if situation == "both": if response < low or response > high: print("Please enter a number between {} and {}".format(low, high)) continue # checks input is not too low elif situation == "low only": if response < low: print("Please enter a number that is more than (or equal to) {}".format(low)) continue return response # checks input is an integer except ValueError: print("Please enter an integer") continue lowest = 1 highest = 10 SECRET = 5 guess = "" while guess != SECRET: guess = int_check("Guess: ", lowest, highest) if guess < SECRET: print("Too low! Try again") elif guess > SECRET: print("Too high! Try again") else: print("Congratulations! You guessed the secret number")
true
4429b8da21d51288c7d4a9edd88568c7712cfb51
mdsksadi/python
/List_in_Python.py
2,377
4.53125
5
''' In a variable we can assign only one value. But if we assing multiple values into the variable, we need to use a list. For diclaring a list, we need to use box bracket "[]" We can assign both number and string type values. List is mutable (We can chagne the values). ''' nums= [2,4,20,54,120] #We diclear a list and inside the lise we assign some values. print(nums) print(nums[0]) #It shows the 1st value. Position like [0 1 2 3 ..] print(nums[2]) #It shows the 3rd value. #print(nums[10]) #IndexError: list index out of range. print(nums[2:]) #Start at 3rd value and go till last. print(nums[-1]) #Show the last value. names = ["Shekh","Sadi","Tamim","Zahid","Anis","Rubel"] #We assing some string values. print(names) values = [20,25.5,"Rownak"] #We assing integer,float,string at a time. print(values) mil= [nums,names] #We can also assign nested list. print(mil) nums.append(45) #We appned/add 45 at the last of the list. print(nums) #nums.clear #It will clear the eintier list nums.insert(2,420) #Add a value to a specific position. Here 2 is index number and 420 is the value print(nums) nums.remove(420) #Remove a element by using "remove" print(nums) nums.pop(2) #It pop up the 3rd value print(nums) nums.pop() #It maintains LIFO. So last value is removed print(nums) del nums[2:] #Delete multiple values. Here we delete all starting 3rd value print(nums) nums.extend([5,3,1]) #We add some values into the list with "extend" print(nums) print(min(nums)) #We can see the munimum value by using inbuild function "min()" print("The maximum value is: ",max(nums)) #We can see the maximum value by using inbuild function "max()" print(sum(nums)) #The sum of all the values by using "sum()" function. nums.sort() #Get all the values in sorted formet. Means ordering formet. print(nums) print("Physics" in names) #Find the specefic result in the list print("Tamim" in names) #"Sensor" is not in the list print("Sensor" not in names) #"not in" meant it's not in list. And it's true print(names + ["Sensor", 25,30]) #Adding extra values in the list print(nums * 3) #Shows the result 3 times
true
df20b2381136f21dd85ab4316491e8d9f90c619f
mdsksadi/python
/Dictionary.py
2,416
4.15625
4
''' List: It's orderd. It's mantain the sequence. Set: It does not maintain the sequence. Dictionary: Differenty key for different element. Example: Phone book. If we search a name, we get a number against that name. Every value has a different key given by me. But in list, the key or index number is fixed and in set we can not define that. key should be unike and immutable. We use curly bracket "{}" for the dictrionary ''' data = {1:"Shekh Sadi",2:"Zahid",4:"Anis"} #We create a dictionary and set specific kes for every elements. print(data) print(data[1]) #We have to specifiy the key to fetch the value #print(data[3]) #It shows error because we did not set any key called "3" print(data.get(3)) #If we use "get" function, it does not show the error. print(data.get(2,"Not found")) ##We can also show a perticular message if the key is missing. print(data.get(3,"Not found")) #We can also show a perticular message if the key is missing. mobile_number= { "Shekh Sadi":"+8801684443284", "Zahid":"+8801714498041", "Abbu":"+8801681303150", "Ammu":"+8801718529185" } print(mobile_number) print(mobile_number["Abbu"]) print(mobile_number["Shekh Sadi"]) #print(mobile_number["Tamim]) print(mobile_number.get("Zahid","This number is not found")) print(mobile_number.get("Tamim","This number is not found")) #We can make it another way who=["Sadi","Zahid","Anis","Rubel"] #We declare a list whom=["Rownak","Mim","Pinkey","vuila gesi"] #Declear another list together=who+whom #Add to list into a single list print(together) #Show the marged list z=zip(whom,whom) #Zip the list print(z) #We can show the zipped code "<zip object at 0x0000028843247080>" y=dict(z) print(dict(y)) #Successfully we marged 2 list into a dictionary by "dict()" function y["Roxy"]="Lichu" #It added a key "Roxy" and element "Lichu" print(dict(y)) del y["Roxy"] #We deleted the key "Roxy" and it's value print(y) #Nested list and nested dictionary prog={"Js":"Atom","CS":"VS","Python":["Pycharm","Sublime"],"Java":{"JSE":"Netbeams","JEE":"Eclipse"}} print(prog) print(prog["Js"]) print(prog["Python"]) print(prog["Python"][1]) #2nd set value of "Python" print(prog["Java"]) print(prog["Java"]["JEE"]) #"JEE" value of key "Java"
true
c48c13d876895eafa0724f5d6b9000e8208708a7
saida93522/HelloPython
/birthday.py
586
4.28125
4
import datetime date = datetime.datetime.now() # date class. # formatting date to string. %B returns full month name. currMonth = date.strftime("%B").lower() def birthday(): name = input('What is your name?\t').capitalize() month = input(f'Hi {name}!, what month were you born in?\t').lower() # check if current month is users birthday month. if month == currMonth: print(f'Happy birthday month {name}!') else: print(f'Happy Early or belated birthday {name}') print(f'Fun fact there are {str(len(name))} letters in your name.') birthday()
true
77746a97fcceca80de494fb8ff0765df5fba6c0d
ToscaMarmefelt/CompPhys
/PS3Q1.py
1,494
4.3125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Oct 11 09:26:27 2018 @author: Tosca """ import random import numpy as np # Decide on number of columns and rows for test matrices A and B col_a = random.randint(1,10) #Range 1-10 for simplicity row_a = random.randint(1,10) col_b = row_a row_b = col_a # To ensure matrix multiplication is possible # Generate random matrices entries = col_a * row_a a = [] b = [] for i in range(entries): a.append(random.randint(1,10)) b.append(random.randint(1,10)) a = np.reshape(a, (col_a, row_a)) b = np.reshape(b, (col_b, row_b)) # Function for performing matrix multiplication of any two matrices m1 and m2 def matrixMultiplication(m1, m2): # Check that matrices can be multiplied if len(m1) != len(m2[0]) or len(m1[0]) != len(m2): print("Sorry, you cannot perform matrix multiplication on these matrices.") # Multiply matrices m1 and m2 to give resulting matrix c c = [] for i in range(len(m1)): #For every row in m1 for j in range(len(m2[0])): #For every column in m2 c_entry = np.sum ( np.array(m1[i]) * np.array(m2[:,j]) ) c.append(c_entry) c = np.reshape(c, (len(m1[0]),len(m1))) return c """ Run calculation """ c = matrixMultiplication(a,b) print("A = ", a, ",B = ", b, " and C = ", c) #Comparing to np.dot(a,b), it gives the same!
true
37e4a5af48a708dbbf381bc7189e500cf9aa35bf
SolidDarrama/Python
/area_calculation.py
1,203
4.3125
4
#Billy Leager #10/1/2014 #Practice Program - Menu def rectangle_area(): side1 = int(input('Enter the value of the first side:')) side2 = int(input('Enter the value of the second side:')) print('The area of the rectangle is', (side1 * side2)) def triangle_area(): height = int(input('Enter the height of the triangle:')) base = int(input('Enter the base of the triangle:')) print('The area of the triangle is', ((height * base) / 2)) keep_going = input('Choose r to calculate the area of a rectangle or t to calculate the area of a triangle, or q to quit:') #Creating a while loop to execute the following functions and statements if menu_value does not equal Q. while keep_going != 'q': if keep_going == 'r': rectangle_area() keep_going = input('Choose r to calculate the area of a rectangle or t to calculate the area of a triangle, or q to quit:') elif keep_going == 't': triangle_area() keep_going = input('Choose r to calculate the area of a rectangle or t to calculate the area of a triangle, or q to quit:') else: keep_going = 'q' print('Exiting program')
true
68ea74d5b245e9d3df91c79e5fa7ba55a1b4be3a
SolidDarrama/Python
/Ch3 Ex/Chapter 3 Exercises 7.py
977
4.15625
4
#Jose Guadarrama #9/20/2014 #CH3 EX7 #user input 1 primary1=str(input('Enter the 1st Primary Color: ')) #if else 1 while primary1 != "red" and primary1 != "blue" and primary1 != "yellow": primary1 = input("\nerror message") #user input 2 primary2=str(input('Enter the 2nd Primary Color: ')) #if else 2 while primary2 != "red" and primary2 != "blue" and primary2 != "yellow": primary2 = input("\nerror message") #color mix equation if primary1 == 'blue' and primary2 == 'red': print('Color Result: Purple') elif primary1 == 'red' and primary2 == 'blue': print('Color Result: Purple') elif primary1 == 'blue' and primary2 == 'yellow': print('Color Result: Green') elif primary1 == 'yellow' and primary2 == 'blue': print('Color Result: Green') elif primary1 == 'red' and primary2 == 'yellow': print('Color Result: Orange') elif primary1 == 'yellow' and primary2 == 'red': print('Color Result: Orange') input()
true
c3edbfd23f522eef4534fd2feb11d6a6c9bb0b68
dheerajdbaudb22/Devops21
/Treasure_island.py
609
4.125
4
print("Welcome to Treasure island.") print("Your mission is to find the treasure.") task1 = input("Do you want to take left or right? \n") t1 = task1.lower() if ( t1 == "right" ): print("Your game is over !") else: t1 == "left" task2 = input("Do you want to swim or wait? \n") t2 = task2.lower() if (t2 == "swim"): print("Your game is over !") else: t2 == "wait" task3 = input("Which door? \n") t3 = task3.lower() if (t3 == "red"): print("your game is over") elif (t3 == "blue"): print("your game is over") elif (t3 == "yellow"): print("You win!!!")
true
45a110c28232c1b28e8a8cabb1695979e8848c8f
rageshm110/python3bootcamp
/lists.py
1,100
4.65625
5
# Lists are ordered sequences that can hold a variety of object types # they use [] and , to separate objects in list # ex: [1,2,3,4] | ["Ragesh","TechM", 4] | ["Adhik", [2007, 20, 05]] # lists supports indexing and slicing. Lists can be nested # and also have a variety of useful methods that can be called # off of them. # list of integers import os my_list = [1, 2, 3] # my_mixed_list = ["string", 300, 5.3] print(len(my_list)) print(my_list[1:]) print(my_list[::-1]) # lists are mutable data structure my_list[0] = 4 print(my_list) my_list.append(5) print(my_list) # remove items from the list my_list.pop() # pop will remove item from back of the list print("my_list: {0}".format(my_list)) # we can use indexing to pop items from specific locations my_list.pop(0) print("my_list: {0}\tHere the first element got removed.".format(my_list)) # sorting a list my_list_unsorted = [1, 2, 3, 6, 56, 22, 45, 32] my_list_unsorted.sort() print("my sorted list: {}".format(my_list_unsorted)) # reverse the list my_list_unsorted.reverse() print("my reversed list: {}".format(my_list_unsorted))s
true
1580c6aab9ceffbc8f12a68a82723d291357dccd
BrunoCAF/CES22
/Lista 2/methods.py
1,586
4.53125
5
#55-70 # Lets illustrate the use of static, class and abstract methods by modelling Polygons import abc, turtle from math import sqrt class Point: def __init__(self, x, y): self.x, self.y = x, y @staticmethod def distance(A, B): return sqrt((A.x - B.x)**2 + (A.y - B.y)**2) def norm(self): return self.distance(self, Point(0,0)) class GridPoint(Point): def __init__(self, x, y): super().__init__(x, y) @staticmethod def distance(A, B): return abs(A.x - B.x) + abs(A.y - B.y) class Polygon: __metaclass__ = abc.ABCMeta def __init__(self, list_of_points): self.points = list_of_points @abc.abstractmethod def calculate_perimeter(self): n = len(self.points) return sum(Point.distance(self.points[i], self.points[(i+1)%n]) for i in range(n)) @abc.abstractmethod def calculate_area(self): """Calculate the polygon's area""" class Triangle(Polygon): n = 3 def __init__(self, P1, P2, P3): super().__init__([P1, P2, P3]) @classmethod def number_of_sides(cls): return cls.n @classmethod def corner_triangle(cls, a, b): return cls(Point(0, 0), Point(a, 0), Point(0, b)) def calculate_area(self): return abs(P1.x*P2.y-P1.y*P2.x + P2.x*P3.y-P2.y*P3.x + P3.x*P1.y-P3.y*P1.x)/2 print(GridPoint(2, 4).norm()) print(Triangle.number_of_sides()) print(Triangle.corner_triangle(2, 5).calculate_perimeter()) print(Polygon([Point(0, 0), Point(2, 0), Point(0, 5)]).calculate_perimeter())
false
63dad4f2c002647474a4d418ac17578744dac437
AlanMalikov777/Task1_Python
/first.py
695
4.3125
4
def toSwap(listToEnter,x,y):#swaps two variables listToEnter[x],listToEnter[y]=listToEnter[y],listToEnter[x] # toPermute uses a heap's algorithm def toPermute(list, current, last):#takes a list, starting index and last index if last<0: print("") elif current == last:# if starting and last indexes will equalise then our function will be done print(''.join(list))#changes from list to string else: for i in range(current, last + 1):#permutating with recursion toSwap(list,current,i) toPermute(list, current + 1, last) toSwap(list,current,i) txt=input("Inseart your text: ") size = len(txt) list1 = list(txt) toPermute(list1, 0, size-1)
true
272ff75f4d102f291fbd318b92937d8f1b5c2b45
tkern0/misc
/School/guessNum.py
1,430
4.125
4
import random # Gets the user's name, allowing only letters, spaces and hyphens letters = "qwertyuiopasdfghjklzxcvbnm- " while True: try: name = input("What is your name? ") for i in name: if i.lower() not in letters: raise ValueError except ValueError: print("Please use only letters in your name") else: break # The game while True: secret_num, num_guessed = random.randint(1, 7), 0 # While the number is not guessed while not secret_num == num_guessed: while True: try: num_guessed = int(input("Try guess the number: ")) if not num_guessed in range(1, 8): raise ValueError # If not 1 2 3 4 5 6 or 7 except ValueError: print("Please enter a number between between 1 and 7") else: break if num_guessed > secret_num: print(str(num_guessed) + "? Too high!") elif num_guessed < secret_num: print(str(num_guessed) + "? Too low!") print("Well done, {}! You guessed the secret number! It was {}!".format(name, secret_num)) while True: # Work out if to continue try: cont = input("Do you want to continue? [Y/N] ").lower() if not cont in ("y", "n"): raise ValueError except ValueError: print("Please enter either Y or N") else: break if cont == "n": break print("Have a nice day! Thanks for playing!")
true
27a866921ee473a17cc635df89e44c516e6cbff5
devashishtrident/progressnov8
/scope.py
1,742
4.25
4
'''x =25 def my_func(): x = 50 return x "/the only x the program is aware of is global variable" #print(x) "this is looking at the myfunc scope only" #print(my_func()) "what confuses the people most is calling the function first and getting the very next value we get x will be called but a global variable not the myfunc vaala" my_func() print(x) ''' '''lets create a lambad expression''' ''' lambda x : x**2 #enclosing functional locals name = 'this is a global name!' def greet(): name = "sammy" "it worked only because hello function was called inside greet not inside hello since that will throw an error" def hello(): print("hello "+name) hello() greet() "but if i ask name to be print seperatley it wont go inside since it have no business inside the scope "" print(name) #####################################################built in functions''' x =50 def func(x): print('x is :',x) x = 1000 print('local x changed to:',x) func(x) print(x) #only above value is considered in these for #eg: x defined in func x still refers to above global x and after x changed it refers to it but #x scope was only inside the function but after that the x got reverted back to 50 #global keyword is not recommended to use y = 50 def func(): global y y =1000 print("before function call,y is:",y) func() print("after function call,y is:",y) ######################################################################################################################################
true
2eb5448693f0b2567dda1b14f81135df988ed3f9
devashishtrident/progressnov8
/Dictionaries.py
310
4.25
4
#dictionary do not return any sorted order my_stuff = {"key1":123,'key2':'value2','key3':{'123':[1,2,'grabme']}} print(my_stuff['key3']['123'][2].upper()) my_stuff = {'lunch':'pizza','bfast':'eggs'} my_stuff['lunch']='burger' my_stuff['dinner'] = 'pasta' print(my_stuff['lunch']) print(my_stuff)
false
5d5aa60886dd4729e839956378ab1e9575f5b8a2
ChristinaEricka/LaunchCode
/unit1/Chapter 09 - Strings/Chapter 09 - Studio 8 - Bugz - Bonus Mission.py
1,851
4.25
4
# Bonus Mission # # Write a function called stretch that takes in a string and doubles each # of the letters contained in the string. For example, # stretch("chihuahua") would return “cchhiihhuuaahhuuaa”. # # Add an optional parameter to your stretch function that indicates how # many times each letter should be duplicated. The default value for this # optional parameter should be 2. For example, stretch("chihuahua", 4) # would return "cccchhhhiiiihhhhuuuuaaaahhhhuuuuaaaa" but # stretch("chihuahua") should still return “cchhiihhuuaahhuuaa”, as # before. # # Add an additional optional parameter to your stretch function that # contains a list of characters. This version of stretch will only # duplicate letters that are contained in the list. The default value # for this new parameter should be the list of lowercase characters. # For example, stretch("chihuahua", 3, "ha") would return # “chhhihhhuaaahhhuaaa”. def stretch(s, n=2, chars_to_multiply=""): """ Return the string <s> with each of the letters repeated <n> times if the letter occurs in <chars_to_multiply>. """ s_multiple_chars = "" if len(chars_to_multiply) == 0: chars_to_multiply = s for char in (s): if char in chars_to_multiply: s_multiple_chars += char * n else: s_multiple_chars += char return s_multiple_chars def testEqual(a, b): if a == b: print("Pass") else: print("Fail") def main(): """ Cursory test of stretch(s) """ testEqual(stretch("chihuahua"), "cchhiihhuuaahhuuaa") testEqual(stretch("chihuahua", 4), "cccchhhhiiiihhhhuuuuaaaahhhhuuuuaaaa") testEqual(stretch("chihuahua", 3, "ha"), "chhhihhhuaaahhhuaaa") if __name__ == "__main__": main()
true
5991435ff06a5927e9d0e5c7d92a6973e1b1982d
ChristinaEricka/LaunchCode
/unit1/Chapter 08 - More About Iteration/Chapter 08 - Exercise 06.py
628
4.1875
4
# Write a program to remove all the red from an image. # # For this and the following exercises, use the luther.jpg photo import image img = image.Image("luther.jpg") win = image.ImageWin(img.getWidth(), img.getHeight()) img.draw(win) img.setDelay(1, 15) # setDelay(0) turns off animation for row in range(img.getHeight()): for col in range(img.getWidth()): p = img.getPixel(col, row) new_red = 0 new_green = p.getGreen() new_blue = p.getBlue() new_pixel = image.Pixel(new_red, new_green, new_blue) img.setPixel(col, row, new_pixel) img.draw(win) win.exitonclick()
true
62c17fd1f2fd0dcccf78a7ce41dbf87ab3ce075e
ChristinaEricka/LaunchCode
/unit1/Chapter 09 - Strings/Chapter 09 - Exercise 02.py
554
4.125
4
# Write a function that will return the number of digits in an integer import string def num_digits(n): """Return number of digits in an integer""" count = 0 for char in str(n): if char in string.digits: count += 1 return count def main(): """Cursory testing of num_digits""" print("num_digits(237) =", num_digits(237)) print("num_digits(-4) =", num_digits(-4)) print("num_digits(12493) =", num_digits(12493)) print("num_digits(0) =", num_digits(0)) if __name__ == "__main__": main()
true
783fa5014f0e5df887b967f03de35622ebf59417
ChristinaEricka/LaunchCode
/unit1/Chapter 07 - Exceptions and Problem Solving/Chapter 07 - Exercise 10.py
1,039
4.28125
4
# Write a function triangle(n) that returns an upright triangle of height n. # # Example: # print(triangle(5)) # # Output: # # # # ### # ##### # ####### # ######### def line(n, str): """Return a line consisting of <n> sequential copies of <str>)""" return_value = '' for _ in range(n): return_value += str return return_value def space_line(spaces, hashes): """ Return a line with exactly the specified number of spaces, followed by the specified number of hashes """ return_value = line(spaces, ' ') + line(hashes, '#') return return_value def triangle(n): """Return an upright triangle of height <n>""" my_EOL = '\n' return_value = '' for line in range(n): return_value += space_line(n - line - 1, line * 2 + 1) + my_EOL return return_value def main(): """Run a quick check to validate triangle(n) function""" print('triangle(5) -->') print(triangle(5)) if __name__ == '__main__': main()
true
4b2c398683572555cb7fae39882fe1e648b7b217
ChristinaEricka/LaunchCode
/unit1/Chapter 11 - Dictionaries and Tuples/Chapter 11 - Studio 10 - Yahtzee.py
2,598
4.1875
4
import random # The roll_dice function simulates the rolling of the dice. It # creates a 2 dimensional list: each column is a die and each # row is a throw. The function generates random numbers 1-6 # and puts them in the list. def roll_dice(num_dice, num_rolls): # create a two-dimensional (num_dice by num_rolls) of zeros double_list = [[0 for i in range(num_dice)] for j in range(num_rolls)] # loop through each row and column, filling it with a random roll for roll in range(0, len(double_list)): for die in range(0, len(double_list[roll])): double_list[roll][die] = (int)(random.random() * 6 + 1) return double_list # This function takes a 2D list (which can be generated by roll_dice) # and sums the value of all the dice in each row. It returns a 1 # dimensional list with the sum of each throw. # Example: # double_list: [[1, 5, 6],[2, 3, 1],[1, 3, 3]] # sum_of_roll should return: [12, 6, 7] def sum_of_roll(double_list): # Your code here sum_list = [] for roll in double_list: sum = 0 for die in roll: sum += die sum_list.append(sum) return sum_list # Bonus function! Takes a 2D list and returns # the number of times a person rolls Yahtzee (all dice have # the same value). Hint: you may want to create a helper # function that takes individual rows of the list. def yahtzee_on_roll(list_of_dice): ret_val = False for index in range(len(list_of_dice) - 1): if list_of_dice[index] == list_of_dice[index + 1]: ret_val = True else: ret_val = False break return ret_val def yahtzee(double_list): total_yahtzees = 0 for roll in double_list: if yahtzee_on_roll(roll): total_yahtzees += 1 return total_yahtzees def testEqual(a, b): """ Home-rolled version of testEqual """ if a == b: print("Pass") else: print("Fail") # To play, yo'd do something like this # dice = input("How many dice?") # rolls = input("What is the number of rolls?") # list = roll_dice(dice, rolls) # print("Sum of roll:", sum_of_roll(list)) def main(): """ Cursory test of yahtzee(double_list) """ print("Testing sum_of_roll...") testEqual(sum_of_roll([[4, 5, 2], [6, 2, 1], [4, 4, 4]]), [11, 9, 12]) testEqual(sum_of_roll([[3, 4, 6], [2, 6, 1], [3, 4, 3]]), [13, 9, 10]) print("Testing yahtzee...") testEqual(yahtzee([[4, 5, 2], [6, 2, 1], [4, 4, 4]]), 1) testEqual(yahtzee([[3, 4, 6], [2, 6, 1], [3, 4, 3]]), 0) if __name__ == "__main__": main()
true
1dedaceb98c59184781af863a5a44540a832bb9e
ChristinaEricka/LaunchCode
/unit1/Chapter 09 - Strings/Chapter 09 - Exercise 09.py
1,185
4.65625
5
# Write a function called rot13 that uses the Caesar cipher to encrypt a # message. The Caesar cipher works like a substitution cipher but each # character is replaced by the character 13 characters to “its right” in the # alphabet. So for example the letter “a” becomes the letter “n”. If a letter # is past the middle of the alphabet then the counting wraps around to the # letter “a” again, so “n” becomes “a”, “o” becomes “b” and so on. Hint: # Whenever you talk about things wrapping around its a good idea to think of # modulo arithmetic (using the remainder operator). import string def rot13(mess): """ Encrypt <mess> using the Caesar cipher """ encrypted_message = "" for char in mess: if char in string.ascii_lowercase: index = (ord(char) - ord('a') + 13) % 26 encrypted_message += chr(ord('a') + index) else: encrypted_message += char return encrypted_message def main(): print(rot13('abcde')) print(rot13('nopqr')) print(rot13(rot13( 'since rot thirteen is symmetric you should see this message'))) if __name__ == "__main__": main()
true
46e0b03dec67ab8b34ebeeb96ae2a4a52c500e9f
ChristinaEricka/LaunchCode
/unit1/Chapter 08 - More About Iteration/Chapter 08 - Exercise 03.py
1,818
4.3125
4
# Modify the turtle walk program so that you have two turtles each with a # random starting location. Keep the turtles moving until one of them leaves # the screen. import random import turtle def is_in_screen(screen, t): left_bound = - screen.window_width() / 2 right_bound = screen.window_width() / 2 top_bound = screen.window_height() / 2 bottom_bound = -screen.window_height() / 2 turtle_x = t.xcor() turtle_y = t.ycor() still_in = True if turtle_x > right_bound or turtle_x < left_bound: still_in = False if turtle_y > top_bound or turtle_y < bottom_bound: still_in = False return still_in def random_x_on_screen(screen): """Return a random x-coordinate on <screen>""" w = screen.window_width() randx = random.randrange(w) - w // 2 return randx def random_y_on_screen(screen): """Return a random y-coordinate on <screen>""" h = screen.window_height() randy = random.randrange(0, h) - h // 2 return randy def main(): screen = turtle.Screen() julia = turtle.Turtle() julia.shape('turtle') julia.color('green') julia.penup() julia.goto(random_x_on_screen(screen), random_y_on_screen(screen)) julia.pendown() julia.stamp() george = turtle.Turtle() george.shape('turtle') george.color('purple') george.penup() george.goto(random_x_on_screen(screen), random_y_on_screen(screen)) george.pendown() george.stamp() while is_in_screen(screen, julia) and is_in_screen(screen, george): for t in [julia, george]: coin = random.randrange(0, 2) if coin == 0: t.left(90) else: t.right(90) t.forward(50) screen.exitonclick() if __name__ == "__main__": main()
true
2feef2a3a3c2438b0acf31bf8df33a3f65485d4e
EvanKaeding/datacamp
/Python for R Users/Control Structures.py
390
4.125
4
# Assign 5 to a variable num_drinks = 5 # if statement if num_drinks < 0: print('error') # elif statement elif num_drinks <= 4: print('non-binge') # else statement else: print('binge') num_drinks = [5, 4, 3, 3, 3, 5, 6, 10] # Write a for loop for drink in num_drinks: # if/else statement if drink <= 4: print('non-binge') else: print('binge')
false
dd81c3c278398a8bea81d19dad23fca4fca0ca9d
sravyaysk/cracking-the-coding-interview-solutions
/LeetCode/searchInRotatedArray.py
2,629
4.1875
4
''' She asked for binary search functionality which tells no exists in array or not. Generally we find mid element through (low+high)/ 2 so she asked to change that and use random function to decide mid. Binary search is performed on sorted array but here unsorted array is given. Two modifications are performed on binary search logic. 1) instead of sorted array, unsorted array has been given 2) Mid element is decided based on random function. Now we have to find out numbers from given array for which this function gives true result. Hint: Function will return true for value x, if all numbers on left side of x are small and all number on the right side of x are greater. Example: [ 4, 3, 1, 5, 7, 6, 10] Ans: 5,10 Rotated Array : Given the array [1 2 3 4 5 6], a rotation of 2 to the left gives [3 4 5 6 1 2] ''' def method2(nums,target): def binarySearch(arr, l, r, x): if r > l: mid = int((l + r) / 2) if arr[mid] == x: return mid elif arr[mid] > x: return binarySearch(arr, l, mid, x) else: return binarySearch(arr, mid + 1, r, x) else: return -1 if (len(nums) > 1): for i in range(0, len(nums) - 1): if (nums[i] > nums[i + 1]): break left_arr = nums[0:i + 1] right_arr = nums[i + 1:] if (target >= left_arr[0] and target <= left_arr[-1]): index = binarySearch(left_arr, 0, len(left_arr), target) elif (target >= right_arr[0] and target <= right_arr[-1]): ind = binarySearch(right_arr, 0, len(right_arr), target) if (ind != -1): index = len(left_arr) + ind else: index = ind else: index = -1 return index elif (len(nums) == 1 and target != nums[0]): return -1 elif (len(nums) == 1 and target == nums[0]): return 0 else: return -1 def searchInRotatedArray(arr,h,l,mid): if(all(arr[l:mid])< arr[mid] and all(arr[mid+1:h])> arr[mid]): print(arr[mid]) return arr[mid] else: if not((all(arr[l:mid])<mid)): mid = mid -1 return searchInRotatedArray(arr,h,l,mid) elif not(all(arr[mid+1:h])>mid): mid = mid + 1 return searchInRotatedArray(arr,h,l,mid) arr = [4, 3, 1, 5, 7, 6, 10] h = len(arr) l = 0 mid = int((h + l) / 2) #searchInRotatedArray(arr,h,l,mid) arr1=[4,5,6,7,0,1,2] print(method2(arr1,0))
true
cb8d29bd928f567faf99e220423b583aab63cb97
ajay946/python-codes
/PrimeNum.py
328
4.125
4
# To find prime number in a given range start = int(input("Start: ")) end = int(input("End: ")) for i in range(start, end +1): # if number is divisible by any number between 2 and i it is not prime if i >1 : for j in range(2,i): if(i%j)==0: break else: print(i)
true
30b51090fcc64881051a00b755a8111d6482d28d
atafs/BackEnd_Python-language-
/language/americoLIB_006_VARIABLES.py
1,249
4.21875
4
#!/usr/bin/python #************************** #IMPORTS import sys #VARIABLES counter = 100 # An integer assignment miles = 1000.0 # A floating point name = "John" # A string #MULTI ASSIGNMENT multi1 = multi2 = multi3 = 1 multi4, multi5, multi6 = 1, 2, "john" #PRINT print("") print("PYTHON: VARIABLES") print("") #************************** #PRINT print (counter) print (miles) print (name) print("") #CONCATENATE FROM INT TO STRING multiAll_1 = '{} {} {}'.format(multi1, multi2, multi3) #CONCATENATE FROM (INT AND STRING) TO STRING multiAll_2 = '{} {} '.format(multi4, multi5) + multi6 print (multiAll_1) print (multiAll_2) #************************** #DELETE VARIABLE print ( 'Deleting the varible ' + '{}'.format(counter) ) print("") del counter #************************** #MANIPULATE SUBSTRINGS str = 'IT WORLD!!' print (str) # Prints complete string print (str[0]) # Prints first character of the string print (str[2:5]) # Prints characters starting from 3rd to 5th print (str[2:]) # Prints string starting from 3rd character print (str * 2) # Prints string two times print (str + "TEST") # Prints concatenated string #************************** #SUCCESS print ("SUCCESS!!")
true
4007832db5961a1f4dd5107a901c7a571b60763b
shubham264693/project
/proga.py
1,663
4.15625
4
text="Where are you? Meet me near the play station" test_list = text.split() index_list1 = [0, 3, 6] index_list2 = [1, 4, 7] index_list3 = [2, 5, 8] # printing original lists print ("Original list : " + str(test_list)) print() print ("Original index list : " + str(index_list1)) print() # using list comprehension to # elements from list res_list = [test_list[i] for i in index_list1] # printing result print ("Resultant list : " + str(res_list)) print() #for replacing Vowels def replace_vowel(mlist): vowels="aeiou" newlist=[] for word in mlist: for char in word: if char in vowels: word=word.replace(char,'%') newlist.append(word) return newlist print (replace_vowel(res_list)) print('\n') print ("Original list : \n " + str(test_list) + "\n") print ("Original index list : \n " + str(index_list2)) res_list1 = [test_list[i] for i in index_list2] print ("Resultant list : \n " + str(res_list1) + "\n") def replace_consonants(plist): consonants="bcdfghjklmnopqrstuvwxyz" newtlist=[] for word1 in plist: for char in word1: if char in consonants: word1=word1.replace(char,'#') newtlist.append(word1) return newtlist print (replace_consonants(res_list1)) print('\n') print("Original List : " + str(test_list) + "\n") print("Index Of REquired Vaule \n" + str(index_list3) + '\n') res_list2 = [test_list[i] for i in index_list3] print("Resultant Values are \n " + str(res_list2)) res_list3 = [x.upper() for x in res_list2] print(str(res_list3))
false
baafacd76c43bc5077924f822d32bab2a933aad5
kevincdurand1/Python-Data-Science-Examples
/Normalization.py
623
4.125
4
#Normalization #Data normalization is used when you want to adjust the values in the feature vector #so that they can be measured on a common scale. One of the most common forms of normalization #that is used in machine learning adjusts the values of a feature vector so that they sum up to 1. #Add the following lines to the previous file: import numpy as np from sklearn import preprocessing data = np.array([[3, -1.5, 2, -5.4], [0,4,-0.3, 2.1], [1,3.3, -1.9, -4.3]]) data_normalized = preprocessing.normalize(data, norm='l1') print ("\nL1 normalized data =", data_normalized)
true
7063ed0f8969fdfc8e5998ce83473afedea34160
anhnh23/PythonLearning
/src/theory/control_flow/functions/__init__.py
2,196
4.28125
4
''' Syntax: def function-name(parameters): statement(s) Explaination: + parameter - can be indentifier=expression ''' # be keys into a dictionary dic = {'a':10, 'b':20, 'c':30} inverse = {} for f in list(dic): inverse[dic[f]] = f print(dic) print(inverse) """This is case parameter is indentifier=expression, saving a reference's value known as the default value for the parameter. """ def f(x, y=[]): y.append(x) return y print(f(1)) print(f(2)) # alter the default value of y def f1(x, y=None): if y is None: y = [] y.append(x) return y print(f1(1)) print(f1(2)) """ ---------- *args and **kwds *args - any extra positional arguments to a call will be collected in a (possibly empty) tuple and bound in the call namespace to the name args **kwds - any extra named arguments will be collected in a (possible empty) dictionary whose items are the names and values of those arguments, and bound to the name kwds in the function call namespace """ #Examples def sum_args(*numbers): return sum(numbers) print('Sum 5 + 7 is : ', sum_args(5, 7)) """---------- Keyword-only parameter should come after *args (if any) and before **kwargs (if any) """ #Examples v3 ''' def f_kwonly(a, *, b, c=56): # b anc c are keyword-only return a, b, c f_kwonly(12, b=34) #returns (12, 34, 56) - c's optional, having a default f_kwonly(12) # raises a TypeError exception ''' #Default argument value def ask_ok(prompt, retries=4, complaint='Yes or no, please!'): while True: ok = raw_input(prompt) if ok in ('y', 'ye', 'yes'): return True if ok in ('n', 'no', 'nop', 'nope'): return False retries = retries -1 if retries < 0: raise IOError('refusenik user') print complaint # 3 ways to call ask_ok funtion ask_ok('Do you really want to quit?') ask_ok('Ok to overwrite the file?', 2) ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!') # NOTE default value evaluated at the point of function definition in the defining scope => i = 5 def f_with_default_argument(arg=i): print arg i=6 f_with_default_argument() # result: 5 (defining scope)
true
e58a6f27c032f2a349dbd6c95c674ad8807df85d
anhnh23/PythonLearning
/src/theory/io/io_module.py
2,080
4.125
4
#str() returns representations of value which are fairly human-readable #repr() generate representation which can be read by the interpreter s = 'Hello,\n world.' print(str(s)) print(repr(s)) for x in range(1, 11): print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x)) '''str() 1. rjust right justifies 2. ljust left ---------- 3. center 4. zfill: pads a numeric string on the left with zeros ''' #format() print('We are the {} who say "{}!"'.format('knights', 'Ni')) print('{0} and {1}'.format('spam', 'eggs')) print('{1} and {0}'.format('spam', 'eggs')) print('This {food} is {adjective}.'.format(food='spam', adjective='absolutely horrible')) print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred', other='Georg')) ''' !a : ascii !s : apply str() !r : repr() ''' contents = 'eels' print('My hovercraft is full of {!r}.'.format(contents)) # built-in function vars() supports ## --- Math import math ## using ":" print('The value of PI is approximately {:.3f}.'.format(math.pi)) table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678} ## --- for name, phone in table.items(): print('{0:10} ==> {1:10d}'.format(name, phone)) ## --- print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; Dcab: {0[Dcab]:d}'.format(table)) ## Using ** print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table)) ## using % print('The value of PI is approximately %5.3f.' % math.pi) ########################### # --- File Integration ---# ########################### ''' open(filename, mode) returns a file object a: append r+: read and write b: open in binary mode ''' f = open('workfile', 'w') '''Ending line \n: on Unix \r\n: on Windows ''' """Default close file with "with" keyword""" with open('workfile') as f: read_data = f.read() #Loop over file for line in f: print(line, end='') ################ # --- JSON --- # ################ import json # dump(x, f) serializes the object to a text file; f: text file. json.dumps([1, 'simple', 'list']) # load decodes object json.load(f)
true
4fb27d914ed56b2ce789e9cc45152f90520390b7
perzonas/euler
/Euler_1.py
318
4.15625
4
# If we list all the natural numbers below 10 that are # multiples of 3 or 5, we get 3, 5, 6 and 9. # The sum of these multiples is 23. # Find the sum of all the multiples of 3 or 5 below 1000. sum = 0 for i in range(3, 1000, 3): if i % 5 != 0: sum += i for i in range(5, 1000, 5): sum += i print(sum)
true
571018d26e98b054e6fee8d204d4b124f262f6a5
mhhg/acm
/1_array_string/two_pointers/1_two_sum/two_sum/two_sum.py
764
4.21875
4
from typing import Dict, List """ TwoSum Given an array of integers, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based. For example: - Input: numbers={2, 7, 11, 15}, target=9 - Output: index1=0, index2=1 """ def two_sum(arr: List[int], target: int) -> List[int]: temporary_dict: Dict[int, int] = {} for index, number in enumerate(arr): if number not in temporary_dict: temporary_dict[target-number] = index else: return [temporary_dict[number], index] return None
true
60d931a8ac4ea9d4b4047d68903ef8c50328a300
crazyAT8/Python-Projects
/While Loop.py
2,373
4.25
4
# i = 1 # Initialization # while i<=5: # Condition # print("william") # i = i + 1 # Increment/Decrement # the objective here is to print my name 5 times in a row # without the Increment/Decrement the loop would go on forever # when using while loops you have to keep track of the end/stopping point # this would also work in reverse order # i = 5 # while i>=1: # print("william") # i = i - 5 # i = 1 # while i<=5: # print(i,"william") # i = i + 1 # the output: 1 william # 2 william # 3 william # 4 william # 5 william # Nested Loops # The objective here is to print out "william rocks rocks rocks rocks" 5 times in a row # i = 1 # j = 1 # while i<=5: # print("william ") # while j<=4: # this is the nested loop # print("rocks ") # j=j+1 # i=i+1 # output: william # this is because the nested loop will be completed first # rocks # think of the outer loop as a day and the inner loop as hours # rocks # all the hours of a day have to pass before the next day comes # rocks # the other problem is that "rocks needs to be on the same line # rocks # william # william # william # william i = 1 while i<=5: print("william ",end="") # end="" will stop the loop from going to a new line j = 1 # declaring the value after the first loop and before the nested while j<=4: # will get 4 'rocks' for every 'william print("rocks ",end="") j=j+1 i=i+1 print() # but the output would put everything on one line so we need to put a print at the end # output: william rocks rocks rocks rocks # william rocks rocks rocks rocks # william rocks rocks rocks rocks # william rocks rocks rocks rocks # william rocks rocks rocks rocks
true
e6045dc8607f166a7d9ea877b0e3af73fb0303a3
Absurd1ty/Python-Practice-All
/problems_py7/power_of_3.py
598
4.25
4
"""Given an integer n, return true if it is a power of three. Otherwise, return false. An integer n is a power of three, if there exists an integer x such that n == 3x.""" class Solution: def isPowerOfThree(self, n: int) -> bool: if n==0: return False if n==3 or n==1: return True multiply = 3 while(multiply < n): multiply = multiply * 3 """"if multiply > n: return False""" if multiply == n: return True else: return False
true
9a9fdc10a372dad407a03275064b54508d07dff4
Raj-Madheshia/Datastructure
/Dynamic Programming/multipleMatrixMultiplication.py
620
4.15625
4
""" The logic behind multiple matrix mutiplication is as given below A = 10*30 B = 30*5 C = 5*60 ABC = (AB)C || A(BC) ABC = (AB)C = 10*30*5 + 10*5*60 operations = 4500 operation ----OR---- ABC = A(BC) = 30*5*60 + 10*30*60 operations = 27000 operation So to get which combination will require minimum no of operation will be used for finding the Matrix Multiplication values """ def MatMul(dim): for no = int(input("Enter number of matrix: ")) a=[] for _ in range(no): a.append([int(x) for x in input().split()]) dimension = a[0] for i in a[1:]: dimension.extend([i[0]])
true
443256679bd1828e82113c8635ce04d9d75efe14
iiepobka/3_lesson_pythons_algorithms
/task_5.py
742
4.125
4
# В массиве найти максимальный отрицательный элемент. Вывести на экран его значение и # позицию (индекс) в массиве. from random import randint COUNT_ITEMS = 10 START_ITEMS = -100 STOP_ITEMS = 100 my_list = [randint(START_ITEMS, STOP_ITEMS) for x in range(COUNT_ITEMS)] print(my_list) max_negative_item = -1 stop = 0 while stop == 0: for n, i in enumerate(my_list): if max_negative_item == i: index = n stop = 1 print(f'Максимальный отрицательный элемент в массиве: {max_negative_item}. Его индекс: {index}') else: max_negative_item -= 1
false
35b52d6776d6a4ab71caa79644f614a569f39ef5
tchrlton/Learning-Python
/HardWay/ex20.py
1,683
4.3125
4
#from the module sys, import the function or paramater argv from sys import argv #The two arguments in argv so it has the script (ex20.py) and #input_file (test.txt or whatever file you input). script, input_file = argv #The function that will print the whole txt file after it reads it def print_all(f): print(f.read()) #The f.seek(0) brings the readline line back to the beginning in the test #file so that it doesnt coninture from the end of the file. def rewind(f): f.seek(0) #The function uses the text file (f) and reads a line, then prints the #current line of the line count def print_a_line(line_count, f): print(line_count, f.readline()) #Openss the input_file when the variable current_file is used current_file = open(input_file) #prints string out and skips a line at the end print("First let's print the whole file:\n") #Runs print_all function which opens input_file and then prints the #whole txt file print_all(current_file) #prints the string print("Now let's rewind, kind of like a tape.") #Runs the function rewind using the current_file variable and the brings #the line back to the beginning with the seek(0) function rewind(current_file) #prints the string print("Let's print three lines:") #prints the first line while also showing the number the line is on current_line = 1 print_a_line(current_line, current_file) #prints the second line while showing the number the line is on which is 2 current_line += 1 print_a_line(current_line, current_file) #prints the third line of the text file since it is + 1 line of the #current line which is 2 (it would be 1 if it had seek(0) in it instead) current_line += 1 print_a_line(current_line, current_file)
true
6b18af9ead2fc973094c40dab143633e9be352dd
SDSS-Computing-Studies/006b-more-functions-bonhamer
/task3.py
461
4.46875
4
#!python3 """ Create a function that determines the length of a hypotenuse given the lengths of 2 shorter sides 2 input parameters float: the length of one side of a right triangle float: the length of the other side of a right triangle return: float value for the length of the hypotenuse Sample assertions: assert hypotenuse(6,8) == 10 (2 points) """ import math def hypotenuse(a,b): c = math.sqrt(a**2 + b**2) return c assert hypotenuse(6,8) == 10
true
8e7611672fde651757c3ea869cf9b6e9980b4018
mmveres/pyPrj06_02_2021
/ua/univer/lesson02/cycle/tasks_cycle.py
487
4.15625
4
def print_10_positive(): i = 0 while i < 10: value = int(input("enter positive value")) if value >= 0: i += 1 print("count=", i, "value =", value) else: print("not positive") def pow(x,n): value = 1 for i in range(n): value *= x return value def calc_power_value_from_console(): x = int(input("enter value x")) n = int(input("power n")) print("x =", x, " in power", n, "=", pow(x, n))
false
bd5487e173f2eb396eff5d2929288c9894e70896
WhaleJ84/com404
/1-basics/ae1-mock-paper/q2-decision.py
254
4.28125
4
# Q2) Decision print("Please enter a whole number:") num = int(input()) # an if statement that divides the input number by 2 and checks to see if it has a remainder; if so it is odd. if num % 2 == 0: print(num, "is even") else: print(num, "is odd")
true
e68b1523babc3f2820dae5d89fa90efa7bf8c1c4
WhaleJ84/com404
/1-basics/4-repetition/1-while-loop/bot.py
484
4.15625
4
# Ask user for number of robots print("How many ascii robots should I draw?") number_robots = int(input()) ROBOT = """ ######### # # # O O # | V | | --- | |_______| """ robots_displayed = 0 MAX_ROBOTS = 10 # Display robots if number_robots <= MAX_ROBOTS: while robots_displayed < (number_robots): print(ROBOT) robots_displayed = robots_displayed + 1 else: while robots_displayed < MAX_ROBOTS: print(ROBOT) robots_displayed = robots_displayed + 1
true
8c7a480827e7924c2ce43947e0c22e1823d0e39b
WhaleJ84/com404
/1-basics/6-review/1-input-output/3-interest.py
449
4.15625
4
# Read current amount from user print("What is your current amount in savings? (£)") current_amount = float(input()) # Read interest rate from user print("What is your interest percentage rate? (%)") interest_rate = float(input()) # Calculate new amount interest_amount = (interest_rate / 100) * current_amount new_amount = current_amount + interest_amount # Display the result print("Your savings after one year will be: £" + str(new_amount))
true
e76c97c6168cbfe2da5b8bd215e9645afe1a5156
ZhenyaBardachina/Python_start
/les_1.2.py
402
4.3125
4
'''Пользователь вводит время в секундах. Переведите время в часы, минуты и секунды и выведите в формате чч:мм:сс. Используйте форматирование строк.''' time = int(input('Enter time in seconds: ')) h = time // 3600 m = time // 60 % 60 s = time % 60 print(f'{h:02d}:{m:02d}:{s:02d}')
false
4ffbc088793baeeddb2804c4645acf276a46ceb8
syoliveira/sirleyoliveira
/main.py
1,038
4.3125
4
"""numero = int(input("digite um numero:")) print(numero) #numero = str (numero) print(numero) boleano = True if numero % 2 == 0: print("numero par") if numero < 5: print("numero menor") elif numero == 5: print("numero igual") else: print("numero maior")""" """numeroA = int(input("digite o 1ª numero:")) numeroB = int(input("digite o 2º numero:")) soma = numeroA + numeroB print(soma) if soma % 2 == 0: print("numero par") else: print("numero impar") if soma > 20: print("maior que 20")""" """===============================================================""" nome = input("Digite seu nome: ") idade = int(input("Digite sua idade: ")) sexo = input("Digite o sexo: ") ano = 2020 - idade ano = str(ano) print(nome + " você nasceu em " + ano) if sexo =="masculino": mulher = False else: mulher = True if mulher: print("Você é uma bela mulher") print(f"Sua idade parece ser {idade-1}") else: print("Você é um cabra") print(f"Mas tu é {sexo} mesmo?") print("fim do codigo")
false
b2d50fa5197a9e4906ec9ecc6c5339cd1dc9c14d
rkc98/Python_100_days_challenge
/day_10/fisrt_word_capital.py
347
4.1875
4
first_name=input("what is your first name ?\n") last_name=input("what is your last name ?\n") def format_name(first,last): if first=='' and last=='': return "check your inputs" f_name=first.title() l_name=last.title() return f_name+" "+l_name fullname=format_name(first=first_name,last=last_name) print(fullname)
true
6d44e6b86da192c3afae09ed13c5b507b15eadd8
mve17/SPISE-2019
/Day 1/Choose Your Own Adventure 6.py
2,084
4.125
4
name=input("Please Enter Your Name: ") intro_text=''' You've woken up with a splitting headache. Fumbling in the dark, your hand brushes against a cold metallic object in the sand. Maybe it will be useful. Would you like to take it with you? [y/n] ''' intro_response=input("\nBad news, "+name+". "+intro_text) if intro_response=='y': holding_metal_object=True else: holding_metal_object=False fire_text=''' \n As your eyes adjust to the darkness, you notice outlines of a forest behind you---as well as a faint light further on the beach. Perhaps a distant campfire? Would you like to investigate? [y/n] ''' response_2=input(fire_text) if response_2=='n': killed_by_animal_text=''' \nYou hear snapping sounds in the forest behind you. Suddenly, a roar breaks the silence and you find yourself thrown to the ground. Everything fades to black. ''' print(killed_by_animal_text) else: campfire_text='''\nAs you approach the campfire you overhear a low conversation around the fire. You hear words like iron, distaster, steel, sabatoge, missing. You're not sure if they're friendly, but it's starting to get cold and it feels like your only chance. You step into the light and receive a warm welcome. After a routine security check, they say, they'll set you up with some dinner.''' print(campfire_text) if holding_metal_object: print('''\nA man comes forward with some sort of device to use for the security check. As it passes over your pocket, the device emits a shriek and a light flashes. The man steps back hurredly and you find yourself pushed away from the campfire and told in no uncertain terms to not come back. It's gotten extremely cold, you don't think you'll survive the night''') else: print('''\nThe security check goes smoothly. Good thing you didn't pick up that metal object... You get a plate of food. You're still not sure where you are, but you know that you're safe for now. THE END.''')
true
e3b34d927246002048c1b992eb6af41dbb7c68f1
mve17/SPISE-2019
/Day 6/testing.py
588
4.15625
4
def reverse_digits(number): negative=number<0 number=abs(number) reversed_number=int(str(number)[::-1]) if negative: reversed_number*=-1 return reversed_number ############ #TEST CASES# ############ #Test 1: 0 print("Testing 0") if reverse_digits(0)==0: print('passed!') else: print('failed') #Test 2: Positive integer print("\nTesting 172") if reverse_digits(172)==271: print('passed!') else: print('failed') #Test 3: Negative Integer print("\nTesting -152") if reverse_digits(-152)==-251: print('passed!') else: print('failed')
true
0932d8c4c24a6b33759f55142a466e26ba3b0ab5
Madhan911/nopcommerceApp
/BasicPrograms/AsendingOrder.py
765
4.1875
4
#In programming, a flag is a predefined bit or bit sequence that holds a binary value. Typically, a program uses a flag to remember something or to leave a sign for another program. list_one = [1,2,3] flag = 0 if list_one == sorted(list_one): flag = 1 if flag: print("list is sorted") else: print("list is not sorted") ''' list_one = [1, 2, 3] flag = 0 i = 1 while i < len(list_one): if list_one[i] < list_one[i - 1]: flag = 1 i += 1 if flag: print(list_one, "is not sorted") else: print(list_one, "is sorted") ''' list_one = [1, 2, 3] flag = 0 list_two = list_one[:] list_two.sort() if [list_one == list_two]: flag = 1 if flag: print(list_one, "is sorted") else: print(list_one, "is not sorted")
true
7ca57bbfa2bec5c1d11a4e30f1032d2987f0b6d5
Madhan911/nopcommerceApp
/BasicPrograms/RecursionFactorial.py
421
4.28125
4
def fact(n): return 1 if (n == 0 or n == 1) else n * fact(n - 1) num = 3 print("Factorial of", num, "is", fact(num)) ''' num = int(input("enter the number : ")) factorial = 1 if num < 0: print("number is a negative number") elif num ==0: print("factorial number one is 0 ") else: for i in range(1, num+1): factorial = factorial*i print("the factorial of ", num, "is ", factorial) '''
true
c777da622c52236d1e7dd664818824cc1fae46ff
AA-anusha/pythonclasses
/formatting.py
448
4.25
4
first_name = raw_input('Your first name: ') last_name = raw_input('Your last name: ') # Old style formatting. print('Hello %s %s!' % (first_name, last_name)) # New Style formatting print('Hello {} {}!'.format(first_name, last_name)) print('Hello {0} {1}!'.format(first_name, last_name)) # This is where, you will feel the difference. print('Hello {1} {0}!'.format(first_name, last_name)) print('Hello {0} {0} {1}!'.format(first_name, last_name))
true
2ef3ef7ea96277d3dafbd81da73dc63afd2898e2
aoracle/hackerank
/all_domains/python/data_types/sets.py
573
4.1875
4
# Task # Given sets of integers, and , print their symmetric difference in ascending order. The term symmetric difference indicates those values that exist in either or but do not exist in both. # Input Format # The first line of input contains an integer, . # The second line contains space-separated integers. # The third line contains an integer, . # The fourth line contains space-separated integers. input() a = set(map(int,raw_input().split())) input() b = set(map(int,raw_input().split())) c = a.symmetric_difference(b) for n in sorted(list(c)): print n
true
dd2547464d148487e2214804d2ff1a53c25bdd88
DanielMafra/Python-LanguageStudies
/exercise075.py
486
4.125
4
number = (int(input('Enter a number:')), int(input('Enter another number:')), int(input('Enter one more number:')), int(input('Enter the last number:'))) print(f'You entered the values {number}') print(f'The value 9 appeared {number.count(9)} times') if 3 in number: print(f'The value 3 appeared in the {number.index(3)+1} position') print('The even values entered were ', end='') for n in number: if n % 2 == 0: print(f'{n} ', end='')
true
e36d10ebe0613d79cce471d872756947965708f6
DanielMafra/Python-LanguageStudies
/exercise032.py
345
4.34375
4
from datetime import date year = int( input('What year do you want to analyze? Enter 0 to analyze the current year: ')) if year == 0: year = date.today().year if year % 4 == 0 and year % 100 != 0 or year % 400 == 0: print('The year {} is a leap year.'.format(year)) else: print('The year {} is not a leap year.'.format(year))
true
e6c06ce1dbbd185c08cba48996001b3cf517e22d
pankosmas/Python-Courses
/Simple Games/tic tac toe remaster/main.py
2,396
4.15625
4
# This is a sample Python script. # Tic Tac Toe game # globals board = [ [" ", " ", " "], [" ", " ", " "], [" ", " ", " "] ] # functions def print_board(): print(" +---+---+---+") print("2 | " + board[2][0] + " | " + board[2][1] + " | " + board[2][2] + " |") print("1 | " + board[1][0] + " | " + board[1][1] + " | " + board[1][2] + " |") print("0 | " + board[0][0] + " | " + board[0][1] + " | " + board[0][2] + " |") print(" +---+---+---+") print(" 0 1 2 ") def check_rows(row): return (board[row][0] == board[row][1] and board[row][1] == board[row][2]) and board[row][0] != " " def check_cols(col): return (board[0][col] == board[1][col] and board[1][col] == board[2][col]) and board[0][col] != " " def check_diagonals(): one = (board[0][0] == board[1][1] and board[1][1] == board[2][2]) and board[1][1] != " " two = (board[2][0] == board[1][1] and board[1][1] == board[0][2]) and board[1][1] != " " res = one or two return res def main(): player = "X" for _ in range(9): # Change turn print_board() if player == "X": player = "O" else: player = "X" # user input print("Player " + player + " plays!") while True: row = int(input("Give row (0-2) :")) col = int(input("Give col (0-2) :")) if row < 0 or row > 2: print("Row out of bounds!") continue elif col < 0 or col > 2: print("Col out of bounds!") continue elif board[row][col] != " ": print("Pick an empty box!") continue else: board[row][col] = player break # check winner winner = False for i in range(3): if check_rows(i): winner = player break if check_cols(i): winner = player break if check_diagonals(): winner = player if winner: print_board() print(f"Congratulations! Player {player} wins!") break else: print_board() print("We have draw!") # main main()
false
dfd8892f50fc1ca02b00c81f1542c157f2c5a12e
Lazaro232/pythonRoadMap
/completePythonCourse/19_GUI_Tkinter/04_frames.py
802
4.53125
5
import tkinter as tk from tkinter import ttk # Instanciando o objeto Tkinter root = tk.Tk() # Definindo um 'main frame' main = ttk.Frame(root) main.pack(side="left", fill="both", expand=True) # Elementos DENTRO do Frame main tk.Label(main, text="Label Top", bg="red").pack( side="top", fill="both", expand=True) tk.Label(main, text="Label Top", bg="red").pack( side="top", fill="both", expand=True) # Elementos FORA dp Frame main tk.Label(root, text="Label left", bg="green").pack( side="left", fill="both", expand=True) root.mainloop() ''' Anotaçoes: 1) main = ttk.Frame(root) Cria uma frame em root Deve-se notar que as Label Top's NAO estao dentro de root, mas sim dentro de main, o que faz com que o segundo elemento de root seja na verdade Label Left e nao as Lebel Top's '''
false
dc4b0dabe8bcd545112104dc0f9985931b9cfed2
Lazaro232/pythonRoadMap
/completePythonCourse/13_Asynchronous_Development/01_threads.py
1,676
4.125
4
import time from threading import Thread def ask_user(): start = time.time() user_input = input('Enter your name: ') greet = f'Hello, {user_input}' print(greet) print(f'aks_user, {time.time() - start}') def complex_calculation(): start = time.time() print('Started calculating...') [x**2 for x in range(20000000)] print(f'complex_calculation, {time.time() - start}') # Single Thread start = time.time() ask_user() complex_calculation() print(f'Single thread total time: {time.time() - start}') # Multi Thread thread1 = Thread(target=complex_calculation) thread2 = Thread(target=ask_user) start = time.time() thread1.start() thread2.start() # Manda o THREAD PRINCIPAL esperar pelos thread1 e thread2 thread1.join() thread2.join() print(f'Two thread total time: {time.time() - start}') ''' Anotações 1) As funções que fazem com sistema esperar por uma resposta do usuário são chamadas de BLOCKING OPERATION. Por exemplo: input() 2) Ao se rodar ask_user(), o programa fica PARADO esperando que o usuário responda. Isso é uma ação do tipo: SINGLE THREAD 3) Ao se utilizar o módulo Thread, passa-se a poder realizar operações MULTI THREAD, ou seja: caso o programa esteja parado na função ask_user() esperando pela reposta do usuário, ele passa a executar complex_calculation() enquanto o usuário não responde. Isso agiliza o programa. 3.1) NÃO se deve usar Thread para algo que SEMPRE usa a CPU, por exemplo: complex_calculation(). Usa-se Thread somente para as chamdas BLOCK OPERATIONS. Ou seja, para funções que fazem com que o programa fique parado esperando algo, por exemplo: ask_user() '''
false
4a90435d940ba7b25452972abbc8e83709c061dd
mmilade/Tic-Tac-Toe
/Problems/Plus one/task.py
437
4.375
4
# You are given a list of strings containing integer numbers. Print the list of their values increased by 1. # E.g. if list_of_strings = ["36", "45", "99"], your program should print the list [37, 46, 100]. # The variable list_of_strings is already defined, you don't need to work with the input. # list_of_strings = ["36", "45", "99"] list_of_strings_plus_1 = [int(value) + 1 for value in list_of_strings] print(list_of_strings_plus_1)
true
b7af78cdca8b3e3df7e070410c229f5cdaa4908c
SVMarshall/programming-challanges
/leetcode/implement_stack_using_queues.py
1,353
4.25
4
# https://leetcode.com/problems/implement-stack-using-queues/ class Stack(object): # simulating first a stack class Queue(): def __init__(self): self.queue_list = [] def push(self, x): self.queue_list.append(x) def pop(self): return self.queue_list.pop(0) def peek(self): return self.queue_list[0] def empty(self): return True if not self.queue_list else False def __init__(self): """ initialize your data structure here. """ # considering the stack top value as the oldest element in the queue # pop fast: O(1); push slow: O(n) self.queue = self.Queue() self.queue_tmp = self.Queue() def push(self, x): """ :type x: int :rtype: nothing """ while not self.queue.empty(): self.queue_tmp.push(self.queue.pop()) self.queue.push(x) while not self.queue_tmp.empty(): self.queue.push(self.queue_tmp.pop()) def pop(self): """ :rtype: nothing """ return self.queue.pop() def top(self): """ :rtype: int """ return self.queue.peek() def empty(self): """ :rtype: bool """ return self.queue.empty()
true
9727529e9542a4ec8fdef1092770e5cd58db6228
yaelBrown/pythonSandbox
/pythonBasics/decorators/decoratorz.py
857
4.5
4
''' Example of python decorators ''' # have function that returns a function def func(aa="cookies"): print("This is the default function") def one(): return 1 def eleven(): return 11 if aa == "cookies": return one() else: return eleven() # print(func()) # can pass a function into a function. Functions as arguments def deco(original_func): def wrap_func(): print("some extra code before original function") original_func() print("Some code after the function") return wrap_func ''' @deco annotation, takes this function and passes into the deco function defined above The annotation has to be the name of the function that takes a function as an argument. ''' @deco def func_needs_deco(): print("I want to be decorated") decorated_func = deco(func_needs_deco) # decorated_func() func_needs_deco()
true
70c559449bd39e24557ce664afb47ca8e7359de4
yaelBrown/pythonSandbox
/LC/_sumProduct.py
2,616
4.65625
5
def sum_product(input_tuple): prod = 1 s = 0 for i in input_tuple: s += i prod *= i return s, prod def sum_product(t): sum_result = 0 product_result = 1 for num in t: sum_result += num product_result *= num return sum_result, product_result input_tuple = (1, 2, 3, 4) sum_result, product_result = sum_product(input_tuple) print(sum_result, product_result) # Expected output: 10, 24 """ Explanation def sum_product(t): - Define a function called "sum_product" that takes a tuple "t" as an argument. sum_result = 0 - Initialize a variable "sum_result" to store the sum of the elements in the tuple. Set its initial value to 0. product_result = 1 - Initialize a variable "product_result" to store the product of the elements in the tuple. Set its initial value to 1. for num in t: - Start a for loop that iterates through each element "num" in the tuple "t". sum_result += num - Add the current element "num" to the "sum_result". product_result *= num - Multiply the current element "num" with the "product_result". return sum_result, product_result - After the loop is done, return a tuple containing the "sum_result" and "product_result". Time and Space Complexity sum_result = 0 - Constant time complexity O(1) because it's a single assignment operation. Constant space complexity O(1) because it stores a single integer. product_result = 1 - Constant time complexity O(1) because it's a single assignment operation. Constant space complexity O(1) because it stores a single integer. for num in t: - Linear time complexity O(n) for the loop, where n is the number of elements in the tuple. This is because the loop iterates through each element in the tuple once. No additional space is used in the loop. sum_result += num - Constant time complexity O(1) for each addition operation inside the loop. product_result *= num - Constant time complexity O(1) for each multiplication operation inside the loop. return sum_result, product_result - Constant time complexity O(1) because it returns a tuple with two integers. Constant space complexity O(1) because it creates a tuple with two integers. Overall time complexity of the function is O(n) because the loop iterates through each element in the tuple once. The rest of the operations have constant time complexity O(1). The overall space complexity is O(1) because the function uses a constant amount of additional memory to store the sum and product, regardless of the size of the input tuple. """
true
1aa62001f4c84e91942fa762495f0ec252bc2412
yaelBrown/pythonSandbox
/LC/LC535-EncodeDecodeTinyURL.py
1,524
4.375
4
""" Note: This is a companion problem to the System Design problem: Design TinyURL. TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk. Design a class to encode a URL and decode a tiny URL. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL. Implement the Solution class: Solution() Initializes the object of the system. String encode(String longUrl) Returns a tiny URL for the given longUrl. String decode(String shortUrl) Returns the original long URL for the given shortUrl. It is guaranteed that the given shortUrl was encoded by the same object. """ class Codec: hm = {} def encode(self, longUrl: str) -> str: """Encodes a URL to a shortened URL. """ import string import random chars = list(string.ascii_lowercase + string.ascii_uppercase) out = "" for i in range(6): out += random.choice(chars) self.hm[out] = longUrl return "http://tinyurl.com/" + out def decode(self, shortUrl: str) -> str: """Decodes a shortened URL to its original URL. """ c = shortUrl.split("/")[3] return self.hm[c] # Your Codec object will be instantiated and called as such: # codec = Codec() # codec.decode(codec.encode(url))
true
79abaed44a11e0c6cdd108e345267a3b47b08b9b
yaelBrown/pythonSandbox
/LC/_maxProduct.py
2,131
4.4375
4
def max_product(arr): # Initialize two variables to store the two largest numbers max1, max2 = 0, 0 # O(1), constant time initialization # Iterate through the array for num in arr: # O(n), where n is the length of the array # If the current number is greater than max1, update max1 and max2 if num > max1: # O(1), constant time comparison max2 = max1 # O(1), constant time assignment max1 = num # O(1), constant time assignment # If the current number is greater than max2 but not max1, update max2 elif num > max2: # O(1), constant time comparison max2 = num # O(1), constant time assignment # Return the product of the two largest numbers return max1 * max2 # O(1), constant time multiplication arr = [1, 7, 3, 4, 9, 5] print(max_product(arr)) # Output: 63 (9*7) """ def max_product(arr): Define a function named max_product that takes an input array arr. max1, max2 = 0, 0 Initialize two variables, max1 and max2, to store the two largest numbers in the array. Set both variables to 0 initially. for num in arr: Iterate through the elements of the input array arr using a for loop. num represents the current element of the array. if num > max1: Check if the current number num is greater than the current maximum value max1. max2 = max1 If the condition in line 4 is True, update the second-largest number max2 by assigning it the value of the current largest number max1. max1 = num Update the largest number max1 by assigning it the value of the current number num. elif num > max2: If the condition in line 4 is False, check if the current number num is greater than the current second-largest number max2. max2 = num If the condition in line 7 is True, update the second-largest number max2 by assigning it the value of the current number num. return max1 * max2 After the loop has finished iterating through the array, return the product of the two largest numbers, max1 and max2. """
true
7c0aed711b26257167682c4ac1eae247abe451fe
17hopkinsonh/RPG_Game
/file1.py
875
4.34375
4
""" Author: Hayden Hopkinson Date: 15/09/2020 Description: A start screen explaining to the user how the game works version: 1.0 improvements from last version: """ # libraries # functions def explain_game(): """this will print out a explanation of the game to the user. Takes no paramiters and returns nothing""" print("""In this game you will be tasked with opening the magical chest, to open it you will first need to find the key, and while you search for them there will be enemy's that will try to stop you. You will need to fight these enemy's which will give you some gold and a chance of a new attack, which you will be able to use in future encounters, as you progress on you will fight stronger and stronger enemy's which will drop stronger attacks for you to use.""") # main if __name__ == "__main__": explain_game()
true
bdb27e057539b67802ac9e2bb70182b1cd002e34
zerowxx/doc
/python/lpython/hello.py
1,361
4.21875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- #hello.py print 'hello, world' print u'中文' ##list 可变长度 classmates = ['Michael', 'Bob', 'Tracy'] print classmates print 'len:',len(classmates) #delete last classmates.pop() #classmates.pop(i) print classmates #insert classmates.append('Tracy') classmates.insert(1,'Jack') print classmates ##tuple 固定不可变 a=(1,2,3) print a #小结:list和tuple是Python内置的有序集合,一个可变,一个不可变。 birth =int(raw_input('birth:')) if birth<2000: print '00前' else: print '00后' #循环 for name in classmates: print name sum = 0 for x in [1,2,3,4,5]: sum = sum + x print sum for x in range(10): print x #字典 key为不可变对象! d = {'a':1,'b':2} print d['a'] #和list比较,dict有以下几个特点: #查找和插入的速度极快,不会随着key的增加而增加; #需要占用大量的内存,内存浪费多。 #而list相反: #查找和插入的时间随着元素的增加而增加; #占用空间小,浪费内存很少。 #set 非重复元素 s = set([1,2,3]) print s s.add(4) print s s.remove(1) print s #定义函数:def关键字 函数名 括号后加: def myabs(x): if x >= 0: return x else: return -x print myabs(-9) #函数可以同时返回多个值,但其实就是一个tuple
false