blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
87df1e1450436998657e85387bf327b296890e47
zhangzheng888/Python
/Python 3/004A Tuple Accessors.py
1,721
4.9375
5
""" Data Type: Tuples Tuple Accessors Indexing The index operator [] to access an item in a tuple, where the index starts from 0. A tuple having 6 elements will have indices from 0 to 5. Trying to access an index outside of the tuple index range(6,7,... in this example) will raise an IndexError. The index must be an integer, float or other types can't be used. This will result in TypeError. Likewise, nested tuples are accessed using nested indexing. """ # Accessing tuple elements using indexing simple_tuple = ('s', 'i', 'm', 'p', 'l', 'e') print(simple_tuple[0]) # 's' print(simple_tuple[5]) # 'e' # IndexError: list index out of range # print(simple_tuple[6]) # Index must be an integer # TypeError: list indices must be integers, not float # simple_tuple[2.0] # nested tuple nested_tuple = ("spice", [8, 4, 6], (1, 2, 3)) # nested index print(nested_tuple[0][3]) # 'c' print(nested_tuple[1][1]) # 4 """ Negative Indexing The index of -1 refers to the last item, -2 to the second last item and so on. """ # Negative indexing for accessing tuple elements negative_tuple = ('h', 'o', 'r', 's', 'e', 's') # Output: 't' print(negative_tuple[-1]) # Output: 'p' print(negative_tuple[-6]) """ Slicing A range of items in a tuple by using the slicing operator colon :. """ # Accessing tuple elements using slicing slice_tuple = ('s', 'l', 'i', 'c', 'i', 'n', 'g', 's') # elements 2nd to 4th # Output: ('l', 'i', 'c') print(slice_tuple[1:4]) # elements beginning to last # Output: ('s', 's') print(slice_tuple[:-7]) # elements 8th to end # Output: ('g', 's') print(slice_tuple[6:]) # elements beginning to end # Output: ('s', 'l', 'i', 'c', 'i', 'n', 'g', 's') print(slice_tuple[:])
true
6acdf1c3b85a9d24913d1cd76ef07ee0977af257
xiaoqing928/DataStructure
/Queue and Stack/1.2queue.py
835
4.25
4
''' 用一个固定数组创建一个队列 思路:start和end两个指针,start返回值,end加入值,同时判断和数组size的大小 相当于start和end在转圈 ''' class Queue: start, end = 0, 0 arr = [[]] size = 0 def __init__(self, l): self.arr = self.arr * l def push(self, num): if self.size < len(self.arr): self.arr[self.end % len(self.arr)] = num self.end += 1 self.size += 1 else: print('arr is full') def poll(self): if self.size > 0: self.size -= 1 self.start += 1 return self.arr[(self.start-1) % len(self.arr)] else: print('arr is null') a = Queue(2) a.push(1) a.push(2) print(a.arr) a.push(3) print(a.poll()) a.push(3) a.push(3) print(a.poll())
false
0a9b7939cb27d11136da319770de28a1f8e25b87
kadr19-333/GitITEA
/HomeWork_3/hw3_6.py
827
4.4375
4
# Если решать по тому как написано в задаче "Используя условные операторы if - elif осуществить проверку:" number = float(input('Введите ЦЕЛОЕ число ')) text = 'Нет результата!' if number >= 0 and number <= 5: if number == 0: print(0) elif number == 1: print(1) elif number == 2: print(2) elif number == 3: print(3) elif number == 4: print(4) elif number == 5: print(5) else: print('Ошибка:', text) # Но можно упростить всё: # number = int(input('Введите число: ')) # text = 'Нет результата!' # if number >= 0 and number <= 5: # print(number) # else: # print('Ошибка:', text)
false
86274e0dcb9ece9bd082fb2c17f8e12a08006f93
taking1fortheteam/pands-problem-set
/Problem3.py
962
4.28125
4
# Aidan Conlon - 21 March 2019 # This is the solution to Problem 3 # Write a program that prints all numbers between 1,000 and 10,000 that are divisible # by 6 but not 12. i = 1000 # Set i to 1000 x = 1000 # Set x to 1000 # Print to screen following comment print("The Values divisible by 6 but not divisible by 12 between 1,000 & 10,000 are:") while i <= 10000: # While loop - while i is less than 10001 continue with this loop if x % 6 == 0 and x % 12 != 0: # if x is divisible by 6 (no remainder) AND not divisible by 12 (remainder) print(x) # print the value of x to the screen i = i + 1 # increment the value of i (for next iteration) x = x + 1 # increment value of x (for next iteration) quit() # Finish
true
21354b9cf2e1b31c94b65c3acc5f59b31a6fc172
dbbaskette/FinanceDataGen
/objects/Transaction.py
705
4.125
4
class Transaction(object): """A customer of with a checking account. Customers have the following properties: Attributes: name: A string representing the customer's name. balance: A float tracking the current balance of the customer's account. """ def __init__(self): """Return a Customer object whose name is *name* and starting balance is *balance*.""" self.customerNumber = 0 self.streetAddress = "" self.city="" self.state = "" self.zip = "" self.latitude = 0 self.longitude = 0 self.transactionTimestamp = 0 self.amount = 0 self.id= 0 self.flagged = 0
true
c373d27eb30c8e8b92f8742814a760b79790229f
miguelr22/Lab-Activity-4
/M4P2.py
334
4.15625
4
#This program will take a password from the user and print an appropriate message #The 'in' keyword checks to see if a value exists somewhere in the given string. greeting = input("Hello, possible pirate! What's the password?") if greeting in ("Arrr!"): print("Go away, pirate.") else: print("Greetings, hater of pirates!")
true
29bac457e5708c1da32de148ecd088b82564dde8
richbon75/practice
/CCI_6ed/Chapter_3/ch3_3_plates.py
1,680
4.25
4
"""Set of stacks - make new stack when current stack reaches max height.""" from collections import deque class SetOfStacks(object): """Make a new stack when current stack reaches max height. Should be transparent to user - push() and pop() should work simply as expected.""" def __init__(self, maxheight): """maxheight is the maximum height of a single stack""" self.maxheight = maxheight self.stax = deque() def __len__(self): return sum([len(x) for x in self.stax]) def push(self, value): """Push a value onto the set of stacks""" if not self.stax or len(self.stax[-1]) >= self.maxheight: self.stax.append(deque()) self.stax[-1].append(value) def pour(self, iterable): """Push in lots of values""" for value in iterable: self.push(value) def pop(self): """Pop a value off the set of stacks""" if not self.stax: raise IndexError('stack empty') value = self.stax[-1].pop() self.trim() return value def pop_substack(self, i): """Pop a value out of a substack""" value = self.stax[i].pop() self.trim() return value def trim(self): """Check the tail for empty stacks, and remove them.""" while self.stax and len(self.stax[-1]) == 0: self.stax.pop() def print(self): """output the SetOfStacks so we can visualize it""" for i, x in enumerate(self.stax): print('{i} : {x}'.format(i=i, x=x)) if __name__ == "__main__": merp = SetOfStacks(7) merp.pour(range(0, 55)) merp.print()
true
1288b1bb228cb31061e023620d7e96acf8c3891a
richbon75/practice
/CCI_6ed/Chapter_5/ch5_1_insertion.py
1,425
4.15625
4
"""Bit manipulation You are given two 32-bit numbers, N and M, and two bit positions, i and j. Write a method to insert M into N such that M starts at bit j and ends at bit i. You can assume that the bits j through i have enough space to fit all of M. That is, if M = 10011, you can assume that there are at least 5 bits between j and i. You would not, for example, have j = 3 and i = 2, because M could not fully fit between bit 3 and bit 2. EXAMPLE Input: N = 10000000000, M = 10011, i 2, j 6 Output: N = 10001001100 """ # Looks like we're just overwriting the bits in positions j to i. # Note: Because of the way integers work in Python (no fixed byte length) # you can't make a one step "AND" mask of zeros where you want to clear # values and 1s everywhere else, because the "everywhere else" space is # effectively infinite. So I'll do it in a two-step process with a mask # that has 1s where I want to clear values and 0s "everywhere else" (since # that's the default) def binary_overlay(N, M, i, j): # make a mask mask = 1 for _ in range(j-i): mask = (mask << 1) | 1 mask <<= i # shift M to the right place M <<= i # clear out old bits. Remember - no standard bit width in Python integers N |= mask N ^= mask # overlay new bits N |= M return N if __name__ == '__main__': print('{0:b}'.format(binary_overlay(0b10000000000, 0b10011, 2, 6)))
true
0607f44c4bf7c629d7bf5142492d64c98f32d561
TrollAndRoll/PythonMiniGames
/rps/play_game.py
2,009
4.21875
4
import random ROCK = "rock" PAPER = "paper" SCISSORS = "scissors" possible_actions = [ROCK, PAPER, SCISSORS] def get_user_input(): return input("Enter a choice (rock, paper, scissors): ") def get_computer_input(): return random.choice(possible_actions) def determine_winner(user_choice, computer_choice): """ :param user_choice: string if user chose rock, paper, or scissors :param computer_choice: computers string of rock, paper, or scissors :return: 1 if user wins, 0 if tie, -1 if computer wins """ if user_choice == computer_choice: print(f"Both players selected {user_choice}. It's a tie!") return 0 elif user_choice == ROCK: if computer_choice == SCISSORS: print("Rock smashes scissors! You win!") return 1 else: print("Paper covers rock! You lose.") return -1 elif user_choice == PAPER: if computer_choice == ROCK: print("Paper covers rock! You win!") return 1 else: print("Scissors cuts paper! You lose.") return -1 elif user_choice == SCISSORS: if computer_choice == PAPER: print("Scissors cuts paper! You win!") return 1 else: print("Rock smashes scissors! You lose.") return -1 def player_play_again(): return input("Do you want to play again? (y/n): ") == 'y' def validate_input(user_choice): return user_choice in possible_actions def run_game(): print("Get ready to play rock, paper scissors!") play_again = True while play_again: user = get_user_input() while not validate_input(user): print("Please choose between rock, paper, or scissors") user = get_user_input() computer = get_computer_input() determine_winner(user, computer) play_again = player_play_again() print("Thank you for playing!") if __name__ == '__main__': run_game()
true
60b3491525e02ce518a3d7a7cb9aba21c83de340
asya0107/candy-project
/candy_problem/main.py
1,712
4.40625
4
''' DIRECTIONS ========== 1. Given the list `friend_favorites`, create a new data structure in the function `create_new_candy_data_structure` that describes the different kinds of candy paired with a list of friends that like that candy. friend_favorites = [ [ "Sally", [ "lollipop", "bubble gum", "laffy taffy" ]], [ "Bob", [ "milky way", "licorice", "lollipop" ]], [ "Arlene", [ "chocolate bar", "milky way", "laffy taffy" ]], [ "Carlie", [ "nerds", "sour patch kids", "laffy taffy" ]] ] 2. In `get_friends_who_like_specific_candy()`, return friends who like lollipops. 3. In, `create_candy_set()`, return a set of all the candies from the data structure made in `create_new_candy_data_structure()`. 4. Write tests for all of the functions in this exercise. ''' # data = friend_favorites def create_new_candy_data_structure(data): # create function that describes differnet kinds of candy paired with a LIST of friends that like that candy candy_types = [] # this makes a list of all the candy types for friend in data: for candy in friend[1]: if candy not in candy_types: candy_types.append(candy) candy_dict = {} friends_list = [] # make each value in candy types a key in candy dict for candy in candy_types: candy_dict[candy] = [] for candy in candy_types: for friend in data: if candy in friend[1]: candy_dict[candy].append(friend[0]) return candy_dict # def get_friends_who_like_specific_candy(data, candy_name): # # return friends who like lollipops # def create_candy_set(data): # # return all candy sets made in the first function
true
57e69baedf18144687ea75d0d1ddad445f8cd0d6
yahya-10/beginner_shoppinCart_with_python
/__main__.py
1,802
4.46875
4
import sys def main_menu(): while True: print() print('''###SHOPPING CART Select an option from the list below 1.Show all items in the cart 2.Add item to the cart 3.Remove item from cart 4.Check if item exists in the cart 5.How many items in the cart 6.Cleat the cart 7.Exit ''') selection = input("Enter your option: ") if selection == "1": show_items() elif selection == "2": add_item() elif selection == "3": remove_item() elif selection == "4": check_item() elif selection == "5": count_of_items_in_cart() elif selection == "6": clear_cart() elif selection == "7": sys.exit() else: print("Wrong option!!") shopping_cart = ["Milk", "Whole Grain Bread", "Chicken Breasts", "Bananas"] def show_items(): for i in shopping_cart: print("-> ", i) def add_item(): new_item = input("Enter the new item you want to add: ") shopping_cart.append(new_item) print(new_item + " has been added to the cart") def remove_item(): unwanted_item = input("Enter the item you want to remove from cart: ") shopping_cart.remove(unwanted_item) print(unwanted_item + " has been removed successfully!!") def check_item(): item_to_check = input("Enter the item you're looking for: ") for i in shopping_cart: if i == item_to_check: print(item_to_check + " exists in the cart!") def count_of_items_in_cart(): print("There are ", len(shopping_cart), " item in cart") def clear_cart(): shopping_cart.clear() print("Shopping cart is clear!!") main_menu()
true
656191fc7588e1fdc4eb6dc09a8509980d028ba7
romaross/pythonProject
/task_1_5.py
268
4.125
4
import math def triangle_square(a, b): return 0.5 * a * b res = input('a b (separated by space)') a, b = map(float, res.split()) print('Hypotenuse of right-angled triangle -', math.hypot(a, b)) print('Square of right-angled triangle -', triangle_square(a, b))
true
71a98f3cdfe88981b6cd2ff3413cacfc613f5a8c
chnghyn/ABS
/chapter1/helloworld.py
1,059
4.1875
4
# This program says hello and asks for my name. # 이 프로그램은 인사를 하고 내 이름을 묻는 프로그램이다. print('Hello world!') print('What is your name? ') # ask for their name 그들의 이름을 묻는다 myName = input() print('It is good to meet you, ' + myName) # 내게 인사한다 print('THe length of your name is:') print(len(myName)) print('What is your age? ') # ask for their age 그들의 나이를 묻는다 myAge = input() print('You will be ' + str(int(myAge) + 1) + ' in a year.') # 일 년 후에 몇 살이 될거라고 말한다 # print(): 전달하는 문자열을 화면에 표시한다. # input(): 사용자가 키보드로 텍스트를 입력하고 Enter 키를 누를 때까지 기다린다. # len(): 문자열을 전달할 수 있고, 문자열의 문자 개수를 정수 형식으로 리턴한다. # str(): 전달되는 값을 문자열 형식으로 리턴한다. # int(): 전달되는 값을 정수 형식으로 리턴한다. # float(): 전달되는 값을 부동 소수점 형식으로 리턴한다.
false
d2dce500f9e3ec8c0347d43461a99a9439cd972d
MarinaFirefly/Python_homeworks
/5/at_lesson/square.py
975
4.125
4
#find squres of the simple numbers using map list_numers = [1,2,3,45,6,8,9,12,8,8,17,29,90,77,113] #function that calculates squares def sqrt_num(num): return num**2 #function that return new list consisting of simple numbers def dividers(list_num): new_list = [] for num in list_num: i = 2 cnt = 1 if num == 1 else 0 #take 1 as not simple number while i <= num/2: if num%i == 0: cnt+=1 #if num has dividors between 2 and num/2 cnt is equal 1 break #break if cycle find out some dividor between 2 and num/2 else: i+=1 if cnt == 0: new_list.append(num) return new_list print(list(map(sqrt_num, dividers(list_numers)))) #ugly method that uses 2 functions: 1 finds dividors and 2 makes a list of simple numbers (besides 1 is simple here) def div_for_num(num): return [i for i in range (1,num) if num%i == 0] def div_for_list(list_num): return [i for i in list_num if len(div_for_num(i))<2] print(list(map(sqrt_num, div_for_list(list_numers))))
true
7894adf619c48a61cec7f861d0efb4212055f8fa
JunctionChao/LeetCode
/next_bigger_number.py
1,463
4.15625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Date : 2020-11-05 # Author : Yuanbo Zhao (chaojunction@gmail.com) """ get the next bigger number using the same digits of a number ex: 123 -> 132 """ def next_bigger(number): # 将数字转化为list number_to_list = [] while number: number, mod = divmod(number, 10) number_to_list.append(mod) number_to_list = number_to_list[::-1] # 先找到右边比左边大的第一个位置 size = len(number_to_list) for x in range(size-1, -1, -1): if number_to_list[x-1] < number_to_list[x]: break if x > 0: # 找第二层较大的数 for y in range(size-1, -1, -1): if number_to_list[x-1] < number_to_list[y]: number_to_list[x-1], number_to_list[y] = \ number_to_list[y], number_to_list[x-1] break # 后续的数是降序的,做置换调整 for z in range((size-x)//2): number_to_list[x+z], number_to_list[size-z-1] = number_to_list[size-z-1], number_to_list[x+z] # 恢复为数字 res, ex = 0, 0 while number_to_list: res += number_to_list.pop() * 10**ex ex += 1 return res # x==0说明左边的数字总是比右边的大 else: return "the bigger number is not exist" if __name__ == '__main__': print(next_bigger(4321)) print(next_bigger(1342)) print(next_bigger(1243))
false
fcaac4ea634139f796f0256c20ce361fb83609a2
manotasce/python
/PythonApplicationPractice/PythonApplicationPractice/MontlyLoanCalc.py
423
4.25
4
# costOfLoan=input("Enter the cost of loan ") rate=input("Enter the rate of loan ") years=input("How many years you will pay the loan? ") #Converting values entered costOfLoan=float(costOfLoan) rate=float(rate) years=int(years) #Calculate monthly payment monthlyPayment=costOfLoan*((rate*(1+rate)**years)/(1+rate)**(years-1)) print("Monthly Payment %.3f " % monthlyPayment) #print(costOfLoan) #print(rate) #print(years)
true
e24400335960ffcf3adfb5236a9be56152ba3659
tandiawanedgar/EdgarTandiawan_ITP2017TugasPAKBAGUS
/Tugas 3/Tugas 3-8/3-8.py
267
4.15625
4
place=['japan','paris','italy','us','cleveland'] print(place) print(sorted(place)) print(place) print(sorted(reversed(place))) print(place) place == reversed(place) print(place) place.reverse() print(place) print(sorted(place)) print(sorted(reversed(place)))
true
cae63bb302d25fd70c99763ee56c3b919675548c
norrismei/coding-fun
/linked_list_remove_duplicates_from_sorted_ll.py
2,255
4.28125
4
# You are given the pointer to the head node of a sorted linked list, where the data in the nodes is in ascending order. # Delete nodes and return a sorted list with each distinct value in the original list. # The given head pointer may be null indicating that the list is empty. # # For your reference: # # SinglyLinkedListNode: # int data # SinglyLinkedListNode next class SinglyLinkedListNode: def __init__(self, node_data): self.data = node_data self.next = None class SinglyLinkedList: def __init__(self): self.head = None self.tail = None def insert_node(self, node_data): node = SinglyLinkedListNode(node_data) if not self.head: self.head = node else: self.tail.next = node self.tail = node def print_singly_linked_list(node): while node: print(str(node.data)) node = node.next def removeDuplicates(head): # if linked list is empty, return None if head is None: return None # if linked list only has one node, then there are no duplicates to remove if head.next is None: return head else: # starting with first two nodes as prev and curr, move through list, comparing current to previous previous = head current = head.next while current: # if current is equal to previous, then this is a duplicate that we have to delete if current.data == previous.data: # link previous's next node to current's next node so the linkedlist stays intact previous.next = current.next # current node updates to the next node we just linked from previous current = current.next # continue with loop to compare new current to previous continue # else current is greater than previous, keep moving through linked list else: # previous becomes the node we just looked at previous = current # current node moves on to the next node current = current.next return head ll = SinglyLinkedList() for num in [1, 2, 2, 3, 3, 5]: ll.insert_node(num) print_singly_linked_list(removeDuplicates(ll.head))
true
ce9675386e0d42018fe283a2670bbede7d4f5fc0
2275114213/test
/06.范型递归树的递归/98.验证二叉搜索树.py
1,776
4.125
4
""" 给定一个二叉树,判断其是否是一个有效的二叉搜索树。 假设一个二叉搜索树具有如下特征: 节点的左子树只包含小于当前节点的数。 节点的右子树只包含大于当前节点的数。 所有左子树和右子树自身必须也是二叉搜索树。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/validate-binary-search-tree 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ # Definition for a binary tree node. class TreeNode(object): def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution(object): # def isValidBST(self, root): # """ # :type root: TreeNode # :rtype: bool # """ # if root == None: # return True # res = [] # # def inorder(root, res): # if root: # inorder(root.left, res) # res.append(root.val) # inorder(root.right, res) # # inorder(root, res) # for i in range(len(res) - 1): # if res[i] >= res[i + 1]: # return False # return True def isValidBST(self, root): """ :type root: TreeNode :rtype: bool """ if root == None: return True self.last = "" def inorder(root): if root: inorder(root.left) if root.val < self.last: return False self.last = root.val inorder(root.right) else: return True res = inorder(root) return res
false
8b52358ff78a127df4ef26cebdcc799b89872fdb
AquaMagnet/Python-Samples
/OddorEven.py
2,068
4.28125
4
# -*- coding: utf-8 -*- """ Created on Sat Sep 1 02:18:20 2018 @author: JUSTINE """ """ Ask the user for a number. Depending on whether the number is even or odd, print out an appropriate message to the user. Hint: how does an even / odd number react differently when divided by 2? Extras: If the number is a multiple of 4, print out a different message. Ask the user for two numbers: one number to check (call it num) and one number to divide by (check). If check divides evenly into num, tell that to the user. If not, print a different appropriate message. """ def oddOrEven(number,divisor): if number%2 == 0: if number%4 == 0: print("{} is an even number and a multiple of 4!".format(number)) else: print("{} is an even number!".format(number)) else: print("{} is an odd number!".format(number)) print() print() print() print("Now checking whether the number is divided by the divisor evenly: ") if number%divisor == 0: print("{} is divided evenly by {}".format(number,divisor), end = '\n') else: print("{} is not divided evenly by {}".format(number,divisor), end = '\n') print("This program determine whether the user input is an odd or an even number", end = '\n') print("This program also determines whether the user's chosen divider will divide the first number evenly.", end = '\n') #First number: while True: try: usernumber = int(input("Input the number you wanted to check: ")) if usernumber < 0: print("Input a non-negative number") else: break except: print("Input a valid non-negative number!") #Second number: while True: try: divisor = int(input("Input the divisor: ")) if usernumber < 0: print("Input a non-negative number") else: break except: print("Input a valid non-negative number!") oddOrEven(usernumber,divisor)
true
8a41ad2803241d4f5ae0f9e8f0f405ad934c3f79
Cemal-y/Python_Fundamentals
/fundamentals/Opdracht_6.py
753
4.25
4
def list_manipulation(list, command, location, value=""): if command == "remove" and location == "end": return list.pop(-1) elif command == "remove" and location == "beginning": return list.pop(0) elif command == "add" and location == "beginning": list.insert(0, value) return list elif command == "add" and location == "end": list.append(value) return list list1 = [1, 2, 3] print(list_manipulation(list=list1, command="remove", location="beginning")) print(list_manipulation(list=list1, command="remove", location="end")) print(list_manipulation(list=list1, command="add", location="beginning", value=20)) print(list_manipulation(list=list1, command="add", location="end", value=30))
true
c85d1bb469df4f643420b4ddba242cb3b03e280d
isutare412/python-cookbook
/04_Iterators_and_Generators/05_iterating_in_reverse.py
791
4.125
4
class Countdown: def __init__(self, start): self._start = start def __iter__(self): n = self._start while n > 0: yield n n -= 1 class CountdownWithR(Countdown): def __reversed__(self): n = 1 while n <= self._start: yield n n += 1 if __name__ == '__main__': a = [1, 2, 3, 4] for x in reversed(a): print(x) print() for cnt in Countdown(3): print(cnt) print() # reversed() only works if the object in question has a size that can # be determined or the object implements a __reversed__() special method. for cnt in reversed(list(Countdown(3))): print(cnt) print() for cnt in reversed(CountdownWithR(3)): print(cnt)
true
06a16a7bbd31fa758edaa0bd8c9bcb423894a3b3
nakshatar/python2_assignment
/pg4.py
290
4.125
4
#string="nakshatra" string = raw_input("enter the string:\t") vowel=0 for i in string: if(i=='a'or i=='e' or i=='i' or i=='o' or i=='u' or i=='A' or i=='E' or i=='I' or i=='O' or i=='U'): vowel = vowel+1 print("\n The totel number of vowels present in the string are:\t") print(vowel)
false
43b3e1f7f59ace3b173bda5caaadd43e814b3aaf
nakshatar/python2_assignment
/pg5.py
230
4.15625
4
# TO CHECK THE ELEMENT IN THE LIST HAS WORD SOIS OR NOT list = ["vlsi","sois","SOIS","ewt","bigdata","vir"] var = raw_input("enter the key element to be found :\t") if var in list: print("SOIS IS FOUND") else: print("NOT FOUND")
true
11c06ebe7f86611a8979ab60d5f2884f9bd07fa7
cristianodeoliveira/Chapter8-1-lists
/BasicListInput.py
414
4.34375
4
#it keeps the numbers in a list numlist = list() while True: inp = input ('Enter a number: ') if inp == 'done': break try: value = float (inp) except: continue numlist.append(value) #outside the loop it calculates the sum () #then it shows the average by dividing the sum #by the number of items in the list average = sum(numlist) / len (numlist) print (numlist) print (average)
true
f96478a60f94d457c7ec1202e36a1f4dc0cd0840
mjbenitez95/connect-py
/connect-four.py
1,673
4.15625
4
import random NUM_ROWS = 6 NUM_COLS = 7 PLAYER_NUM = 1 CPU_NUM = 2 class Board: def __init__(self): self.board = [] for _ in range(NUM_ROWS): single_row = [0] * NUM_COLS self.board.append(single_row) def __str__(self): board_display = "" for row in self.board: board_display += str(row) board_display += "\n" return board_display def display(self): for row in self.board: print row print "-" * NUM_COLS * 3 def drop(self, column, player): if self.board[0][column] != 0: return False for row in range(1, NUM_ROWS): if self.board[row][column] != 0: self.board[row-1][column] = player return True elif (row == NUM_ROWS - 1): self.board[row][column] = player return True def prompt_player_move(): print "Where would you like to drop a coin?" player_input = input() return int(player_input) if __name__ == "__main__": board = Board() turn_number = 1 while True: if turn_number % 2 == PLAYER_NUM: move = prompt_player_move() while board.drop(move, PLAYER_NUM) is False: print "Invalid move. Please try again." move = prompt_player_move() else: # make computer move random_move = random.choice(range(NUM_COLS)) while board.drop(random_move, CPU_NUM) is False: random_move = random.choice(range(NUM_COLS)) board.display() turn_number += 1
true
cc69c5b3f7b92bfb0bffc1cbbcab61a0f1f2a206
amalshehu/exercism-python
/sum-of-multiples/sum_of_multiples.py
419
4.34375
4
# File: sum_of_multiples.py # Purpose: Write a program that, given a number, can find the sum of all # the multiples of particular numbers up to but not including that number. # Programmer: Amal Shehu # Course: Exercism # Date: Wednesday 7th September 2016, 11:00 PM def sum_of_multiples(limit, div_list): return sum(set(j for i in div_list if i > 0 for j in range(i, limit, i)))
true
464153406ddd89c324969fd943576f6a34475728
NicolasWarlop/AdventOfCode2017
/Day 03/2017d3.py
2,090
4.21875
4
""" 2017d2.py - Advent of code 2017 - day 3""" #Globals INPUT = 265149 def get_direction(): """Returns the next direction modifier""" current_dir = 0 direction = [(1, 0), (0, 1), (-1, 0), (0, -1)] while True: yield direction[current_dir%len(direction)] current_dir += 1 def get_manhattan_distance(point_a, point_b): """Calculate the manhattan distance between both points""" return abs(point_b[0] - point_a[0]) + abs(point_b[1] - point_a[1]) def get_cartesian_coordinates(steps): """get the x,y coordinates for a given input """ current_x = 0 current_y = 0 next_dir = get_direction() cur_dir = next(next_dir) vector_length = 1 length_counter = 0 steps_taken = 0 for _ in range(1, steps): current_x += cur_dir[0] current_y += cur_dir[1] steps_taken += 1 #are we at the tip of the vector? if steps_taken == vector_length: cur_dir = next(next_dir) steps_taken = 0 length_counter += 1 #do we need to increase the vector length? if length_counter % 2 == 0: vector_length += 1 return (current_x, current_y) def solve_part_1(): """ part 1 solver""" print("Part 1: " + str(get_manhattan_distance((0, 0), get_cartesian_coordinates(INPUT)))) def solve_part_2(): """ part 2 solver""" seen = {} seen[(0, 0)] = 1 steps = 2 return_value = 0 while return_value < INPUT: return_value = 0 #get the next coordinate cur_pos = get_cartesian_coordinates(steps) for i in range(-1, 2): for j in range(-1, 2): if (cur_pos[0]+i, cur_pos[1]+j) in seen: return_value += seen[(cur_pos[0]+i, cur_pos[1]+j)] seen[cur_pos] = return_value steps += 1 print("Part 2: " + str(return_value)) def main(): """main function""" solve_part_1() solve_part_2() #Main execution if __name__ == "__main__": main()
true
580266fd0bd4f8d963d0bbdab7839622fb805c02
joaosvictor/practice
/src/Initial/check_odd_even.py
457
4.46875
4
# check if a input number is odd or even # int input number = int(input('Enter a number: ')) # "%" operator check the remainder of a division # so, 8 / 2 = 4. No remainder! # otherwise, 8 / 3 = 2,66. It has remainder number! if number % 2 == 0: # zero represent the "remainder" print('{} is Even number'.format(number)) else: print('{} is Odd number'.format(number)) # .format() will call the variable, so you put '{}' to the .format find it
true
3a64c1343bed86cdc050ea442a5543c74046c389
RichardEsquivel/Recursive-Sorting
/src/recursive_sorting/cursion.py
979
4.3125
4
def my_recursion(n): print(n) if n == 3: return print("Before First", n) my_recursion(n + 1) print("Before Second:", n) my_recursion(n + 1) print("Before Third:", n) my_recursion(n + 1) print("Before Fourth:", n) my_recursion(n + 1) print("After Fourth:", n) my_recursion(1) """ output expected is : 1 Before First 1 2 Before First 2 3 Before Second: 2 3 Before Third: 2 3 Before Fourth: 2 3 After Fourth: 2 Before Second: 1 2 Before First 2 3 Before Second: 2 3 Before Third: 2 3 Before Fourth: 2 3 After Fourth: 2 Before Third: 1 2 Before First 2 3 Before Second: 2 3 Before Third: 2 3 Before Fourth: 2 3 After Fourth: 2 Before Fourth: 1 2 Before First 2 3 Before Second: 2 3 Before Third: 2 3 Before Fourth: 2 3 After Fourth: 2 After Fourth: 1 """ # As each value is returned back to it's caller within the recursion loop until we have the last 4th my recursion which has no original caller other than the invocation.s
true
661eb30c3cf306b90aee846309045354a0a77705
sandyhsia/codeWarwww
/string中的重复字符.py
1,136
4.15625
4
## My solution def is_isogram(string): #your code here if type(string) != str: raise TypeError('Argument should be a string') elif string == "": return True else: string = string.lower() repeat = 0 for char in string: if string.count(char) > 1: repeat += 1 if repeat > 0: return False else: return True #Best Practice def isogram(n): if not isinstance(n, str): return False elif len(n) < 1: return True n = n.lower() if len(n) == len(set(n)): ## we check if the length of the input is equal to the length of the set(n). return True else: return False # The function set() converts a collection or a sequence or an iterator object into a set. # For example: set('lists') returns {'s', 't', 'l', 'i'}, as you can see the letter 's' which appears twice in 'lists', does not appear in the set. # This is useful to check if the length of the set is equal to the length of the input, if there is a letter which appears twice in the input the condition is False.
true
923be6b25ef4609f1c45c4a21692d684100fdcd8
VanessaVanG/word_count
/word_count.py
836
4.21875
4
'''Alright, this one might be a bit challenging but you've been doing great so far, so I'm sure you can manage it. I need you to make a function named word_count. It should accept a single argument which will be a string. The function needs to return a dictionary. The keys in the dictionary will be each of the words in the string, lowercased. The values will be how many times that particular word appears in the string. Check the comments below for an example.''' # E.g. word_count("I do not like it Sam I Am") gets back a dictionary like: # {'i': 2, 'do': 1, 'it': 1, 'sam': 1, 'like': 1, 'not': 1, 'am': 1} # Lowercase the string to make it easier. def word_count(phrase): words = phrase.lower().split() counter = {} for word in words: counter.update({word: words.count(word)}) return counter
true
b52661f383b25062efd0cd2776d7366d6bd87027
sbstnzcr/project-euler
/problem_002.py
804
4.1875
4
# Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: # 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... # By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. def fibonacci(n: int) -> int: """Find the nth fibonacci number.""" sequence = [1, 2] for i in range(2, n+1): sequence.append(sequence[i-1] + sequence[i-2]) return sequence[n] if __name__ == '__main__': even_terms = [] i = 0 while True: element = fibonacci(i) i += 1 if element > 4_000_000: break elif not element % 2: even_terms.append(element) result = sum(even_terms) print(result)
true
286396e606464f35516d7cdc96207e109f069bbe
Immaannn2222/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/0-add_integer.py
348
4.21875
4
#!/usr/bin/python3 """ the add module""" def add_integer(a, b=98): """ adds two integers a and b""" if not (isinstance(a, int) or isinstance(a, float)): raise TypeError("a must be an integer") if not (isinstance(b, int) or isinstance(b, float)): raise TypeError("b must be an integer") return (int(a) + int(b))
true
62313b3d2063e28e3d1b6d6ec78b637bf435980a
philkrause/python-basics
/lists.py
564
4.15625
4
# A List is a collection which is ordered and changeable. Allows duplicate members. #Create a list numbers = [1,2,3,4,5] fruits = ['Apples', 'Oranges', 'Grapes', 'Pears'] #Use a constructor # numbers2 = list((1,2,3,4,5)) print(fruits[1]) print(len(fruits)) #Append to list fruits.append('Mangos') #Remove from list fruits.remove('Grapes') #Insert into position fruits.insert(2, 'Strawberries') #Remove with pop fruits.pop(2) fruits.reverse() fruits.sort() #alphabetical sort fruits.reverse() #change value fruits[0] = 'Blueberries ' print(fruits)
true
07576aad1ffe85389a340b42ac930fa3baac2106
tcollins1984/CollatzFun
/LICENSE.md/pwrsof2.py
1,621
4.53125
5
#The collatz algorithm ends when you hit a powewr of 2. All subsequent steps will #be to divide by 2 until you reach one. #The only way to initally "hit" a power of 2 is by taking an oddd number X and performing 3X + 1. #Let's look at the first 100 powers of 2 and see if they will ever be that power of 2 which ends #the algorigthm when by being reached from an odd number #We'll create a dataframe in pandas to show the power of 2 that ends the algorithm and the odd number which #will land us there. We'll also have a brief text description saying whether or not that particular power of 2 is a terminal number import pandas as pd max_power = 100 pwr2 = [] for i in range(0,max_power+1): pwr2.append(2**i) #Let's all each element of pwrd Ni. Since it must be reached by running an odd number X through 3X+1, #we can find out if this is so by inverting the function (Ni - 1)/3 = X #Since X must be a whole number, we know that Ni is reached through the application # of the 3X + 1 algorith when (Ni - 1)%3 = 0 cc = [] for n in range(0,len(pwr2)): if (pwr2[n]-1)%3 == 0: cc.append([pwr2[n],(pwr2[n]-1)/3,'will converge form here']) else: cc.append([pwr2[n], 'na','cannot be reached by 3n + 1']) number = [] odd = [] result = [] for i in range(0,len(cc)): number.append(cc[i][0]) odd.append(cc[i][1]) result.append(cc[i][2]) powerTwo = pd.DataFrame({"2 to the Index":number, "Corresponding Odd if Any":odd,"Result":result}) print(powerTwo) #use the following code to print to csv file in the directory of your choice #powerTwo.to_csv('CollatzTerminalNumbers.csv')
true
1a17b195885eaf95ddf3310203c68669691c5f4f
srinivasreddy/euler
/src/35.py
1,149
4.125
4
import math """ function to generate infinite prime numbers!!! """ def gen_prime(): yield 2 x=3 while True: if x>1000000: break elif(is_prime(x) and should_not(x)): yield x x=x+2 def is_prime(x): if x==1: return False for i in range(3,int(math.sqrt(x))+1,2): if(x%i==0): return False return True """ the idea is -if it cotains any even number ,then it will not be a prime after rotations.. and remove zero as it's presence will make 103 as 31 and 13 then we will loss one number in the digit. """ def should_not(n): cache =str(n) return (not "0" in cache) and (not "2" in cache) and (not "4" in cache) and (not "6" in cache) and (not "8" in cache) if __name__ =="__main__": total=0 for i in gen_prime(): flag=True original=i if len(str(i))==1: total=total+1 else: for j in range(len(str(i))): if(not is_prime(i)): flag=False i=int(str(i)[1:]+str(i)[:1]) if flag: total=total+1 print total
true
e71c8cfdaabf3d4eb9e04dc145afb6a33047228e
harrydadson/Python-DataStructures-Algo
/03-Searching-and-Sorting/05-insertion-sort.py
832
4.375
4
# Implementation of Insertion Sort Algorithm # Insertion look at the next index values and pick and put # them at their right sport in ascending order # Sorts a sequence in ascending order using Insertion def insertionSort(theSeq): n = len(theSeq) # Starts with the first item as the only sorted entry for i in range(1, n): # Save the value to be positioned value = theSeq[i] # find the position where the value fits in the ordered part of the list pos = i while pos > 0 and value < theSeq[pos - 1]: # shift the items to the right during search theSeq[pos] = theSeq[pos - 1] pos -= 1 # Put the saved value into the open slot theSeq[pos] = value return theSeq print(insertionSort([8,3,22,15,5,13,9]))
true
39692630b6a7f7d305d0aef4fb52ee298c882d60
mzqshine/test
/day1/test1.py
1,444
4.3125
4
# ''' # 编写时间:2021-06-27 # 编写者:马志强 # 功能描述:第一天 # ''' # # #注释 # # #打印helloworld # # print('helloworld') # # # # # 变量 --简单断点 # # his_name = '小明' # # print(his_name) # # print(his1name) # # #数据类型 # m=123 # print(type(m)) # m = 0.123 # n = 'sad' # print(type(m)) # print(type(n)) # print(type(True)) # b = (1,2) # v = {1,2} # c = {'s':1,'b':2} # print(type(b)) # print(type(v)) # print(type(c)) # 格式化输出 ctrl+alt+l 可以对代码进行格式调整 his_name = '小飞' age = 18 weight = 50.12 num = 1 print('我的名字是:%s' % his_name) # 字符串 print('我的年龄是:%d' % age) # 整形 print('我的体重是:%f' % weight) # 浮点,默认小数点后6位 print('我的学号是:%05d' % num) # 必须0开始,5代表总长度 print('我的年龄是:%.2f' % weight) # 。2代表小数点位数 print('我的名字是:%s,我的年龄是:%d,我的体重是:%f' % (his_name, age, weight)) # 整合 print('我的名字是:%s,我的年龄是:%d,我的明天体重是:%.3f' % (his_name, age, weight - 1)) # 打印加减函数 print(f'我的名字是:{his_name},我的年龄是:{age},我的明天体重是:{weight}') # 3.7版本上有f参数使用 print('shjdkahdjka\nshd\tadjk\n\tsdhka') # 转义换行符 \n换行 \t非行开头空格1个字符 \t行开头是tab 4个字符 print('结束', end='-------') # 结束标识
false
6108d7674abd9d8930f8779ba130db204164b69d
jamalie/Reverse3
/reverse3.py
549
4.3125
4
#Given an array of ints length 3, return a new array with the elements in reverse order, so {1, 2, 3} becomes {3, 2, 1}. #reverse3([1, 2, 3]) -> [3, 2, 1] #reverse3([5, 11, 9]) -> [9, 11, 5] #reverse3([7, 0, 0]) -> [0, 0, 7] def reverse3(nums): for i in range(len(nums)-1): if i <= (len(nums)-1-i): x = nums[i] nums[i] = nums[len(nums)-1-i] nums[len(nums)-1-i] = x else: return nums return nums print reverse3([1, 2, 3]) print reverse3([5, 11, 9]) print reverse3([7, 0, 0])
true
2e09fea6272e4c0cc1a1c28b046d1025cc228722
estela-ramirez/PythonCourses
/Homework 3 #1.py
1,611
4.1875
4
''' ICS 31 Homework 3 Problem 1 Author: UCI_ID: 18108714 Name: Estela Ramirez Ramirez ''' def main(): hint_list = ["I am round.", "I can be seen during the day.", "I am very hot.", "I am brihgt.", "I am in the sky."] introduction() is_Guess_correct("answer") ask_question(hint_list, "answer" ) def is_Guess_correct(answer:str)->str: # asks the question # does not give hints, but if the guess is right/wrong it works hint_number = 5 for hints in range(hint_number): user_answer = input("Now make a guess: ") if user_answer== "sun": print("Good job you guessed correctly!") break elif user_answer == "the sun": print("Good job you guessed correctly!") break else: print("Nope, Guess again! ") def introduction(): print("Let's play a guessing game! ") print("I've picked something, and I will give you five hints. ") print("You get to make a guess after each hint. ") print("If you get it right, I will let you know otherwise ") print("You will keep guessing until I run out of hints. ") print("Let's get started ") def ask_question(hint_list:list, answer:str): # gives hints, asks for guess hint_number = 5 for x in hint_list: print() print("Here is your hint: ","\n", x) user_answer = input("Now make a guess: ") user_answer = user_answer.lower() hint_number -=1 if hint_number < 1: print("\n","Ohh, I must not have given good hints. I was the sun. ") main()
true
a26dfcfb34a20b6340fff0ce648100025ca8a352
estela-ramirez/PythonCourses
/LAB 3 Q1.py
1,340
4.125
4
''' ICS 31 Lab 3 Question 1 Driver: UCI_ID: 18108714 Name: Estela Ramirez Ramirez Navigator: UCI_ID: 69329009 Name: Karina Regalo ''' def main(): i = get_n_of_people() ns, ag = getsAgesAndNames(i) maxb, index = maxAge(ag) minb, index2 = minAge(ag) s = sumAge(ag) printOldestYoungestAverage(index,index2,s,i,ns,ag) def get_n_of_people(): return int(input("Number of people: ")) def getsAgesAndNames(number_of_people)->list: a =[] b =[] for x in range(1, number_of_people+1): name = input("What is Person #{}'s name: ". format(x)) a.append(name) age = int(input("What is {}'s age? ". format(name))) b.append(age) return a, b def maxAge(b:list)->int: maxb = 0 for x in b: if x >= maxb: maxb = x index = (b.index(maxb)) return maxb, index def minAge(b:list)->int: minb = 100000000000 for x in b: if x <= minb: minb = x index = (b.index(minb)) return minb, index def sumAge(b:list)->int: for x in (b): sumb = sum(b) def printOldestYoungestAverage(ma,mia,ta,np,ns,ag): print( ns[mia], "is the youngest and is", ag[mia], "years old") print( ns[ma], "is the oldest and is ", ag[ma], "years old") print("Average Age is:",(sum(ag)/len(ag))) main()
false
2bebea84337e7ca8e2146a7cf59dd982694175a5
estela-ramirez/PythonCourses
/Pre Lab 4 P 3.py
2,207
4.125
4
#This function checks if the data in num is an integer. def isInt(num: str) -> bool: try: int(num) return True except ValueError: return False #IN OPERATOR L = [1,2,3] val = 1 if val in L: print( val , "is in the list") else: print(val , "is not in the list") S = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" sub_Str = "JK" if sub_Str in S: print( sub_Str , "is in the list") else: print(sub_Str , "is not in the list") #Also note that the empty string is considered in every string empty = "" if empty in S: print("S has the empty_string") #String INDEXING S = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" first_15 = S[0:15] #Contains the first 15 letters, or the letters in indexes 0 - 14 last_15 = S[len(S) - 15 : len(S)] #Specify the end index + 1 last_15_alt = S[len(S) - 15 : ] #Say start here and grab all print(first_15) print(len(first_15)) print() print(last_15) print(len(last_15)) print() print(last_15_alt) print(len(last_15_alt)) #INDEXING BACKWARDS # 0 1 2 3 4 # H E L L O # -5 -4 -3 -2 -1 first_15 = S[ -len(S) : (-len(S) + 15)] last_15 = S[-15: len(S)] #Contains the last 15 letters, or the letters in indexes -15 to -1 last_15_alt = S[-15 : ] #Say start here and grab all print(first_15) print(len(first_15)) print() print(last_15) print(len(last_15)) print() print(last_15_alt) print(len(last_15_alt)) #FIND str1 = "My Example, Sample, Text, String"; str2 = "exam"; #This will return -1, as find is case sensitive print(str1.find(str2)) #This will return 3, as that is the index of the substring print(str1.lower().find(str2.lower())) #This will return -1, as it will start searching after the substring print(str1.lower().find(str2.lower(), 10)) #This will return 1, as find goes from the front of the string print(str1.find(str2)) #R.FIND searches backwards and returns the highest rather than lowest index #This will return 13 as rfind goes from the back of the string print(str1.rfind(str2)) #This will return 1, as their is no later occurrence before index 10 print(str1.rfind(str2, 0, 10)) #This will return 13, as their is no later occurrence after index 10 print(str1.rfind(str2, 10))
true
72dd09f5af0d18b42e2584ced6503e8a18958ed1
alee1412/activities
/Lesson_3_Python/Activity_5.py
1,973
4.21875
4
prices = ["24", "13", "16000", "1400"] price_nums = [int(price) for price in prices] print(prices) print(price_nums) print("**************************************") dog = "poodle" letters = [letter for letter in dog] print(letters) print(f"We iterate over a string into a list: {letters}") print("**************************************") capital_letters = [letter.upper() for letter in letters] capital_letters = [] for letter in letters: capital_letters.append(letter.upper()) print(capital_letters) print("**************************************") #First way no_o = [letter for letter in letters if letter != 'o'] print(no_o) #Second way no_o = [] for letter in letters: if letter != 'o': no_o.append(letter) print(no_o) print("**************************************") june_temperature = [72,65,59,87] july_temperature = [87,85,92,79] august_temperature = [88,77,66,100] temperature = [june_temperature, july_temperature, august_temperature] print("**************************************") #short hand lowest_summer_temperature = [min(temps) for temps in temperature] maximum_summer_temperature = [max(temps) for temps in temperature] print(sum(maximum_summer_temperature)/len(maximum_summer_temperature)) print(lowest_summer_temperature[0]) print(lowest_summer_temperature[1]) print(lowest_summer_temperature[2]) print("=" * 30) print("**************************************") #long hand lowest_summer_temperature = [] for temps in temperature: lowest_summer_temperature.append(min(temps)) print(lowest_summer_temperature[0]) print(lowest_summer_temperature[1]) print(lowest_summer_temperature[2]) print(sum(lowest_summer_temperature)/len(lowest_summer_temperature)) print("**************************************") def name(parameter): return "Hello " + parameter print(name("Albert")) def average(data1,data2): return (sum(data1)/len(data1)) + (sum(data2)/len(data2)) print("=" * 40) print(average([1,2,3,4,5],[2,3,4,5,6]))
false
b4215a396e6e080c19154eeacf2a91ad1a80ca85
stge4code/CodePractice
/stepic.org/Python_Programming/3.7-4.py
739
4.15625
4
# put your python code here class Turtle: def __init__(self, x=0, y=0): self.x = x self.y = y def movement(self, s): (cmd, steps) = (s.split()) self.CMDs[cmd](self, int(steps)) def nord(self, steps): self.y += steps def east(self, steps): self.x += steps def west(self, steps): self.x -= steps def south(self, steps): self.y -= steps def getcoords(self): return str(self.x) + ' ' + str(self.y) CMDs = { "север": nord, "юг": south, "восток": east, "запад": west } turtle = Turtle() n = int(input()) for i in range(n): turtle.movement(input()) print(turtle.getcoords())
false
fb077e5b1a676165bbe69a90211b076cf1d35903
VenkateshSatagopan/Data-Structures
/Other_problems/array_binary_sum.py
1,140
4.25
4
def add_arr(arr_1,arr_2): ''' Function to add 2 binary numbers array and return the result ''' arr_3=[0]*(max(len(arr_1),len(arr_2))+1) k=len(arr_3)-1 i=len(arr_1)-1 j=len(arr_2)-1 carry=0 while(i>=0 and j >= 0): arr_3[k] = (arr_1[i]+arr_2[j] + carry )%2 carry=(arr_1[i]+arr_2[j]+ carry)//2 k-=1 j-=1 i-=1 while(i>=0): arr_3[k]=(arr_1[i]+carry)%2 carry=(arr_1[i]+carry)//2 i-=1 k-=1 while(j>=0): arr_3[k]=(arr_2[j]+carry)%2 carry=(arr_2[j]+carry)//2 j-=1 k-=1 if carry: arr_3[k]=carry return arr_3 if __name__ == '__main__': # Test case 1 arr1=[1,1,1,1,1,0] arr2=[1,1,1,1,1,1] assert [1,1,1,1,1,0,1] == add_arr(arr1,arr2) # Test case 2 arr1=[1,0,1] arr2=[1,1,1,1] assert [1,0,1,0,0] == add_arr(arr1,arr2) # Test case 3 arr1=[1,0,0,0,1,0] arr2=[1,1] assert [0,1,0,0,1,0,1] == add_arr(arr1,arr2) # Test case 4 arr1=[1,1,1,1,1,1] arr2=[1,1,1,1,1,1] assert [1,1,1,1,1,1,0] == add_arr(arr1,arr2)
false
53e46e1fc8a9445e723c34bdbdbfe6a3d308a368
jos-h/Python_Exercises
/List_Container/merge_unsortedlist_insertion.py
638
4.15625
4
#!/usr/bin/python3 def sort_list(list_3): key = 0 i = 1 j = 0 while i < len(list_3): j = i - 1 key = list_3[i] while j >= 0 and key < list_3[j]: list_3[j + 1] = list_3[j] j -= 1 list_3[j + 1] = key i += 1 return list_3 def main(): list_1 = eval(input("accept the first list")) list_2 = eval(input("accept the second list")) list_3 = [] list_3.extend(list_1) list_3.extend(list_2) print("Merged list is {}".format(list_3)) print("sorted list is {}".format(sort_list(list_3))) if __name__ == '__main__': main()
false
ab2d94b7c694176eedcd4aa2e9878a94c0cef134
jos-h/Python_Exercises
/substring_string.py
1,366
4.125
4
""" Given two strings s1, s2, write a function that returns true if s2 is a special substring s1. A special substring s2 is such that the s1 contains s2 where each character in s2 appears in sequence in s1, but there can be any characters in s1 in between the sequence. Example: isSpecialSubstring('abcdefg', 'abc') => true isSpecialSubstring('abcdefg', 'acg') => true isSpecialSubstring('abcdefg', 'acb') => false; The first two are abc and acg appears in 'abcdefg' in that order, although there might be multiple chars between the next character in s2. The last one is false, because in 'acb' the character 'b' appears before the character 'c' in 'abcdefg' """ def check_dest(dest): des_len = len(dest) - 1 i = 0 j = 0 while i < des_len and j <= des_len: j = i + 1 if dest[i] > dest[j]: return False i += 1 def is_special_substring(org, dest): dest_len = len(dest) flag = 0 val = check_dest(dest) if val == False: return False else: for j in dest: for i in org: if j == i: flag += 1 break if flag == 3: return True def main(): val = is_special_substring('abcdefg', 'bad') if val: print("True") else: print("False") if __name__ == '__main__': main()
true
940bdcee82e02161b8002b6fc031a4d47ae51101
jos-h/Python_Exercises
/List_Container/Union_list.py
1,447
4.21875
4
#!/usr/bin/python3 def menu(): print("1:Union of Lists\n" "2:Intersection of Lists\n" "3:Difference in Lists\n" "4:Exit") choice = eval(input("Accept the choice")) return choice def union_lists(list_1, list_2): list_3 = [] list_3.extend(list_1) for x in list_2: if x not in list_3: list_3.append(x) return list_3 def intersection_list(list_1, list_2): list_3 = [] for x in list_1: for y in list_2: if x == y: list_3.append(x) return list_3 def difference_lists(list_1, list_2): list_3 = [] j = 0; list_3.extend(list_1) while j < list_3.__len__(): i = 0 while i < list_2.__len__(): if list_3[j] == list_2[i]: list_3.remove(j) i += 1 j += 1 return list_3 def main(): list_1 = eval(input("Accept 1st list")) list_2 = eval(input("Accept 2nd list")) while True: choice = menu() if choice == 1: print("Union of list is {}".format(union_lists(list_1,list_2))) elif choice == 2: print("Intersection of list is {}".format(intersection_list(list_1, list_2))) elif choice == 3: print("Difference between lists is {}".format(difference_lists(list_1, list_2))) else: print("bye") return if __name__ == "__main__": main()
false
d4706392e28c352dc53d2d54580be308a8f53acd
jiten-kmar/python-code
/largest_number_list.py
342
4.4375
4
#Python Program to Find the Largest Number in a List list1=[] total_num=int(input("Enter how many numbers needed for the list: ")) for n in range(0, total_num): number=input("Enter the number for the list ") list1.append(number) new_list=sorted(list1, key=int, reverse=True) print(new_list) print ("Largest number is ", new_list[0])
true
12a9d741f8120cfb240b36572b1ab357926ea033
kiranprabakaran/rock_paper_scissors
/main.py
1,283
4.15625
4
import random while True: print("rock, paper, scissors?") choice = input() choice = choice.lower() print("my choice is ", choice) choices = ['rock', 'paper', 'scissors'] computer_choice = choices[random.randint(0, len(choices)-1)] print("computer choice is ", computer_choice) if choice in choices: if choice == 'rock': if computer_choice == 'rock': print("It is a Draw") elif computer_choice == 'paper': print("You Lost :(") elif computer_choice == 'scissors': print("Winner, Winner!!!!") if choice == 'paper': if computer_choice == 'rock': print("Winner, Winner!!!!") elif computer_choice == 'paper': print("It is a Draw") elif computer_choice == 'scissors': print("You Lost :(") if choice == 'scissors': if computer_choice == 'rock': print("You Lost :(") elif computer_choice == 'paper': print("Winner, Winner!!!!") elif computer_choice == 'scissors': print("It is a Draw") else: print("Your answer doesn't make sense. Try again") print()
false
0a1126a739b46f19a8c2ec082ad880e08e7c46db
ashleynguci/pythonproj
/point.py
902
4.21875
4
# -*- coding: utf-8 -*- """ class that implements 2D point """ class Point: """ class that knows x and y coordinates """ def __init__(self, _x=0, _y=0): self.__x = _x self.__y = _y @property def x(self): return self.__x @property def y(self): return self.__y def xy(self, _x, _y): """ sets new values to point's coordinates """ self.__x = _x self.__y = _y #objects methods # def length(self): # """ Point distance from origo """ # return pow((self.__x**2 + self.__y**2), 0.5) def length(self, _point=None): """ Point distance from origo if _point is None else distance from given point """ if _point is None: _point = Point() return pow(((self.__x - _point.x)**2 + (self.__y - _point.y)**2), 0.5)
false
cb208030a3d35d607ded29d8121d3a16ebf2b390
Nadjamac/Mod1_Blue
/Aula8 Exerc5.py
321
4.125
4
num = int(input("Digite um numero :\n")) contador = 0 for x in range (1,num+1): if num % x == 0: print("{} é divisivel : {} ".format(num, num/x)) contador += 1 if contador == 2: print("é um numero primo ") else: print("não é um numero primo ")
false
6372b4c622b02fe034aa8aec03d3dabb1545670f
mohapatralovleen4/Python-task-0
/3rd program.py
238
4.34375
4
#program to count the total number of digits in a given number n = int(input("Enter a number to calculate the number of digits\n")) c = 0 while(n>0): c = (c+1) n = (n//10) print("The number of digits in the given number are",c)
true
18e2f774f328af2d0036a75a291a2e860fb24d4d
TIBTHINK/damien
/lesson4/lesson4.3/beer.py
1,106
4.28125
4
from os import system, name # Creating a function for clearing the screen # (You will thank me later) def clear(): if name == 'nt': _ = system('cls') else: _ = system('clear') beer_count = 0 # Sets the counter to 0 as a base line try: print("all systems go") clear() print("how many beers do you order?") # Asking the user for a number question = int(input("[1-13]: ")) # Saving there answer as a integer while beer_count < 13: # Checking every cycle if beer_count = 13, if not it will continue the loop until it does beer_count = beer_count + question # Adds your answer to the beer counter plus what its current at print("beer count: " + str(beer_count)) # Tells the user how many they have ordered question = int(input("[1-13]: ")) # Reasks the questions to start the loop else: # If you have ordered 13 the program will exit exit("you have had enough to drink") except KeyboardInterrupt: exit("good bye")
true
8df245c5c4de0f7655fffcb29496f491630b6980
kz/compsci-homework
/1. AS Level/5. Encryption Exercise/Task 1.py
2,046
4.75
5
# Task 1 # Author: Kelvin Zhang # Date Created: 2016-03-22 # This program takes in a word and makes it uppercase (e.g., "computing" -> "COMPUTING". It then takes in a keyword. # An encrypted message is generated by adding the alphabet value of the message to the value of the keyword. # If the word is longer than the keyword, the keyword repeats (e.g., "GCSE" -> "GCSEGCSEG" for "COMPUTING"). def convert_character_to_alphabet_value(char): return ord(char) - ASCII_A + 1 # Incremented by one as the alphabet does not use zero-based numbering def convert_alphabet_value_to_character(val): return chr(ASCII_A + val - 1) # This function takes a position of a message (starting from position zero [zero-based numbering]) # and returns the equivalent keyword letter for this position. # E.g., if message is "COMPUTING", keyword is "GCSE" and we are taking the position five ("T"), # the equivalent keyword letter would be "GCSE"[5 % 4] = "GCSE"[1] = "C" def get_keyword_letter_for_position(keyword, pos): return keyword[pos % len(keyword)] # ASCII value for the letter A ASCII_A = 65 # Prompt for input rawMessage = input("Enter your message: ") keyword = input("Enter your keyword: ") # Initialise empty string for the encrypted message encryptedMessage = "" # Loop through the raw message, generating the encrypted message for i in range(0, len(rawMessage)): # Get the letter of the keyword as an alphabet value keywordLetter = get_keyword_letter_for_position(keyword, i) keywordValue = convert_character_to_alphabet_value(keywordLetter) # Get the alphabet value for the letter of the message messageValue = convert_character_to_alphabet_value(rawMessage[i]) # Obtain the encrypted letter encryptedValue = (keywordValue + messageValue) % 26 # Modulo 26 is used to bring overflow values back to the start encryptedLetter = convert_alphabet_value_to_character(encryptedValue) # Append the letter to the message encryptedMessage += encryptedLetter # Output to user print(encryptedMessage)
true
113e7df40ee698ec6788c9ad34cce936811ea356
Kyle5150/CSE111
/CSE111/TireVolume.py
1,068
4.21875
4
print() with open("/Users/kylejohnson/Documents/Python/CSE111/volumes.txt", "at") as volume_file: import math w = int(float(input("Enter the width of the tire in mm (ex 205): "))) a = int(float(input("Enter the aspect ratio of the tire (ex 60): "))) d = int(float(input("Enter the diameter of the wheel in inches (ex 15): "))) v = (math.pi * w ** 2 * a * (w * a + 2540 * d)) / 10000000 liters = v / 1000 print() print(f"The approximate volume is {v:.1f} milliliters\nor\n{liters:.1f} liters") print() from datetime import datetime current_date_time = datetime.now() buy_tires = input("Would you like to buy tires (yes/no)? ") if buy_tires == "yes": phone_number = input("Please enter your phone number ((555)555-5555): ") print(f"{current_date_time}, {w}, {a}, {d}, {v:.1f}, {phone_number}", file = volume_file) print("Thank you for your time.") else: print(f"{current_date_time}, {w}, {a}, {d}, {v:.1f}", file = volume_file) print("Thank you for your time.") print()
true
4b32a03bacf3057df50147de4d873a06178943a6
JohnnyChingas/Algorithms
/LinkedList.py
2,161
4.15625
4
# Some linked list operations # T. Melano class Node: def __init__(self, data = None): # Node initiator # @param data is any object contained in the node self.data = data self.next = None def insert(self, data): # Add nodes to linked list # @param data for new node added to linked list if self.next == None: self.next = Node(data) else: self.next.insert(data) def traverse(self): # Traverse and print linked list print self.data if self.next != None: self.next.traverse() def reverse(self): # Reverse linked list last = None head = self while head != None: next = head.next head.next = last last = head head = next return last def delete(self,data): if self.data == data: return self.next else: head = self n = self flag = 0 while n.next != None: if n.next.data == data: n.next = n.next.next n = n.next flag = 1 else: n = n.next if not flag: print "Element not found" return head def remove_duplicates(linked_list): if isinstance(linked_list,Node): prev = linked_list htable = {} n = prev.next htable[prev.data] = None while n != None: if n.data in htable: prev.next = n.next n = n.next else: htable[n.data] = None prev = n n = n.next #Write function that reverses a linked list using recursion def main(): list = [1,2,3,4,5] head = Node(0) for elem in list: head.insert(elem) print "Print list" head.traverse() print "Reversing list" head = head.reverse() head.traverse() print "Reversing list" head = head.reverse() head.traverse() if __name__ == "__main__": main()
true
7ab53e3a31bde9b675212fdf1f0f48b490edbbbc
Anory/Python_projeck
/list_test/sample_list.py
741
4.25
4
# 列表的操作 name_list = ["张三", "李四", "王五", "赵六", "孙斌", "王五"] wangwu = name_list[2] # 正向取值 print(wangwu) wangwu = name_list[-3] # 负向取值 print(wangwu) # 范围取值:切片(左闭右开原则:包含左边的对应数据, 不包含右边的对应数据) name_list1 = name_list[1:3] # 从1开始到3(不包含3) print(name_list1) # 获取列表值的位置(index函数用于获取列表指定元素的索引值,注意:只会返回元素第一次出现的索引值) wangwu_index = name_list.index("王五") print(wangwu_index) # 获取指定元素的索引值 for i in name_list: print(i) name_index = name_list.index(i) if i == "王五": print(name_index)
false
a0d691d843234cad7a9f151c109e966679ceff79
RFishwick/CO_SCI_124_Python
/AsnCh10/10_1.py
625
4.125
4
import pet def main(): # Local variables pet_name = "" pet_type = "" pet_age = 0 # Get pet data. pet_name = input('Enter the name of the pet: ') pet_type = input('Enter the type of animal: ') pet_age = int(input('Enter the age of the pet: ')) # Create an instance of Pet. mypet = pet.Pet(pet_name, pet_type, pet_age) # Display the data that was entered. print('Here is the data that you entered: ') print('Pet name: ', mypet.get_name()) print('Animal type: ', mypet.get_animal_type()) print('Age of pet: ', mypet.get_age()) # Call the main function. main()
true
45e60c606aad958ee86045f71a11a9c0545a6c44
RFishwick/CO_SCI_124_Python
/AsnCh9/ex9_5.py
1,682
4.46875
4
# Write a program that reads the contents of a text file. # The program should create a dictionary in which the keys are the individual words # found in the file and the values are the number of times each word appears. # # For example, if the word “the” appears 128 times, the dictionary would contain an element with 'the' # as the key and 128 as the value. The program should either display the frequency of each word # or create a second file containing a list of each word and its frequency. # def main(): input_name = 'text.txt' # Assign file name # Open the input file and read the text. input_file = open(input_name, 'r') # Open the file for read access text = input_file.read() # Read the file into a string variable words = text.split() # Split text into a list of words # Extra steps to strip off special characters new_text = '' for word in words: word = word.strip(',') word = word.strip('.') new_text = new_text + word + ' ' # Assign individual stripped words to words list and split again words = new_text.split() # Create a set containing the unique words. unique_words = set(words) # Create a word_count dictionary from unique words and initialize counts to zero word_count = {} for word in unique_words: word_count[word] = 0 # Increment word_count dictionary value for each word in words for word in words: word_count[word] += 1 # Print the results print('\n*** Word Frequency ***\n') for key in word_count: print(key, word_count[key]) # Close the file. input_file.close() # Call the main function. main()
true
bdb0a0cacb35c26c02b82acda79b42f6389530cb
Nan-Do/DailyCoding
/Daily_113.py
1,543
4.15625
4
# Cost O(n) (we traverse the string two times) # Traverse the string putting each word in a stack and then # extract words from the stack that will return the words in # a reversed order. def reverse_words(s): words = [] word = '' for x in s: if x == ' ': words.insert(0, word) word = '' continue word += x words.insert(0, word) return ' '.join(words) def reverse_from(s, init, end): while init < end: temp = s[init] s[init] = s[end] s[end] = temp init += 1 end -= 1 # Cost O(n) We traverse the string three times, one to detect the words # another one to reverse each word and the last time to reverse the whole # string # The algorithm works as follows traverse the string reversing each word # and then return the reverse of the string (if we reverse each word and # then we reverse the whole string we obtain the desired answer without # having to care about where to put the spaces on the reversed string # which can complicate the exercise quite a lot def reverse_words_mutable(s): last_init = 0 for pos, x in enumerate(s): if x == ' ': reverse_from(s, last_init, pos - 1) last_init = pos + 1 # Reverse last word reverse_from(s, last_init, len(s) - 1) reverse_from(s, 0, len(s) - 1) print(reverse_words("hello world here")) s = [ 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', ' ', 't', 'h', 'e', 'r', 'e' ] reverse_words_mutable(s) print(s)
true
79591707fec63b979b5e6e6d34cdee4ba97dce67
iriasyk/python_language
/students/km63/Ryasyk_Ihor/homework_5.py
2,635
4.1875
4
#task1-------------------------------------------------------------------- ''' Даны четыре действительных числа: x1, y1, x2, y2. Напишите функцию distance(x1, y1, x2, y2), вычисляющая расстояние между точкой (x1,y1) и (x2,y2). Считайте четыре действительных числа и выведите результат работы этой функции. ''' from math import sqrt def distance(x1,y1,x2,y2): return sqrt((x1-x2)**2+(y1-y2)**2) x1=float(input()) y1=float(input()) x2=float(input()) y2=float(input()) print(distance(x1,y1,x2,y2)) #-------------------------------------------------------------------------- #task2--------------------------------------------------------------------- ''' Дано действительное положительное число a и целоe число n. Вычислите a^n. Решение оформите в виде функции power(a, n). ''' def power(a, n): res=1 if n>0: for i in range(n): res*=a elif n<0: for i in range(-1*n): res/=a return res print(power(float(input()), int(input()))) #-------------------------------------------------------------------------- #task3--------------------------------------------------------------------- ''' Дано действительное положительное число a и целое неотрицательное число n. Вычислите an не используя циклы, возведение в степень через ** и функцию math.pow(), а используя рекуррентное соотношение a^n=a*a^(n-1). Решение оформите в виде функции power(a, n). ''' def power(a, n): if n == 0: return 1 else: return a * power(a, n - 1) print(power(float(input()), int(input()))) #-------------------------------------------------------------------------- #task4---------------------------------------------------------------------- ''' Напишите функцию fib(n), которая по данному целому неотрицательному n возвращает n-e число Фибоначчи. В этой задаче нельзя использовать циклы — используйте рекурсию. ''' def fib(n): if n == 1 or n == 2: return 1 else: return fib(n - 1) + fib(n - 2) n = int(input()) print(fib(n)) #--------------------------------------------------------------------------
false
e23596e870f260c2df15a847431b678c5eba3bf1
Ran-oops/python
/3/06描述符/07.py
1,061
4.3125
4
#声明类 #自定义类来继承系统的整形类 class myint(int): #魔术方法 触发时机:当前对象+另外一个数值的时候触发 def __add__(self,other): #print('add被触发') return int(self) - int(other) #魔术方法 触发时机:当前对象-另外一个数值的时候触发 def __sub__(self,other): #print('sub备触发') return int(self) + int(other) #魔术方法 触发时机:当前对象*另外一个数值的时候触发 def __mul__(self,other): #print('mul备触发') return int(self) / int(other) #魔术方法 触发时机:当前对象/另外一个数值的时候触发 def __truediv__(self,other): #print('__truediv__ 备触发') return int(self) * int(other) #实例化对象 one = myint(10)#相当于int(10) #加法操作 #result = one + 20 #print(result) #减法操作 #result = one - 2 #print(result) #乘法操作 #result = one * 5 #print(result) #除法操作 #result = one / 4 #print(result)
false
3771e08cb17bb5323d042ee530a04d37b6a927e4
Ran-oops/python
/1python基础/07Python中的nolocal关键词的使用,lambda表达式,递归,字符串操作/09.py
973
4.125
4
''' # + 字符串连接运算 str1 = '你问我爱你有多深' str2 = '大概10cm左右!' result = str1 + ':' + str2 print(result) # * 字符串相乘(复制) str1 = '吕欣' result = str1 * 10 print(result) #[] 索引操作 # 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 str1 = '下班的时候我宝贝骑摩托车来接你!' # ....-4-3-2-1 print(str1[3]) print(str1[-3]) ''' #取片操作 str1 = '冬天脱毛衣会有很多静电,噼里啪啦,夏天为什么没有涅?因为夏天傻子才穿毛衣!' #从指定位置截取到最后 print(str1[17:]) #从开头截取到指定位置之前(不包含结束索引位置) print(str1[:17]) #从开始索引截取到指定的索引之前(不包含结束索引位置) print(str1[12:16]) #获取整个字符串 print(str1[:]) #根据指定的间隔获取字符 print(str1[::3]) #指定和截取字符串的范围同时指定间隔数值 print(str1[17:30:2])
false
7ad7c535a5a6e60090ebe38b333a1956ba9df1f2
Ran-oops/python
/2/02列表 元组 字典/04.py
669
4.4375
4
#元组的操作 #1.创建空元组 #tuple1 = () tuple1 = tuple() print(type(tuple1)) print(tuple1) #2.创建具有一个元素的元组 tuple1 = ('不知妻美刘强东',)#tuple1 = '不知妻美刘强东', print(type(tuple1)) print(tuple1) #3.创建多个元素的元素 tuple1 = ('马云','马化腾','王健林','丁磊')#tuple1 = '马云','马化腾','王健林','丁磊' print(type(tuple1)) print(tuple1) #元组的基本操作(除了访问啥也干不了) #使用索引访问元素 tuple1 = ('王思聪','牛广林','牛少鸟') print(tuple1[2]) #删除整个元组 tuple1 = ('王思聪','牛广林','牛少鸟') del tuple1 print(tuple1)
false
15786735b73566332996aeef2d6cc3133bfd6ea2
Ran-oops/python
/2/02列表 元组 字典/05.py
837
4.375
4
#元组的序列操作 #元组相加 tuple1 = ('肉夹馍','土豆丝卷饼','山东烧饼','煎饼','煎饼果子') tuple2 = ('抄手','燃面','砂锅面','砂锅土豆粉') result = tuple1 + tuple2 print(result) #模拟修改元组 tuple1 = ('肉夹馍','土豆丝卷饼','山东烧饼','煎饼','煎饼果子') result = tuple1[0:3] + ('糁',) + tuple1[3:] print(result) #元组相乘 tuple1 = ('雍建凯','李艳玲') result = tuple1 * 5 print(result) #分片操作 tuple1 = ('张飞','岳飞','双飞','王菲','飞飞','咖妃','尿嫔') print(tuple1[2:5]) print(tuple1[2:]) print(tuple1[:5]) print(tuple1[:]) print(tuple1[::2]) #成员检测 tuple1 = ('张建宇','邢天宇','田宇','王雷雨','王晓雨') result = '田宇' in tuple1 print(result) result = '吕欣' not in tuple1 print(result)
false
dcfecea3b168804ef867b088677fce2187e6ec0a
Ran-oops/python
/1python基础/01 Python基础/04/repeat.py
2,557
4.34375
4
#书写代码 ''' print('我们对于女朋友提出的要求向来是不太注重,草草了事!') print('我们对于女朋友提出的要求向来是不太注重,草草了事!') print('我们对于女朋友提出的要求向来是不太注重,草草了事!') print('我们对于女朋友提出的要求向来是不太注重,草草了事!') print('我们对于女朋友提出的要求向来是不太注重,草草了事!') print('我们对于女朋友提出的要求向来是不太注重,草草了事!') print('我们对于女朋友提出的要求向来是不太注重,草草了事!') print('我们对于女朋友提出的要求向来是不太注重,草草了事!') print('我们对于女朋友提出的要求向来是不太注重,草草了事!') print('我们对于女朋友提出的要求向来是不太注重,草草了事!') ''' ''' #声明一个变量,作为计数变量使用 num = 0 while num<100: #要循环的内容 print('我们对于女朋友提出的要求向来是不太注重,草草了事!') #变量变化 num += 1 ''' ''' 执行过程: 1.声明了变量num 并且赋值为0 2.进入while循环,判断num<100是否为真->0<100 真 3.执行循环代码组,输出了打印内容 4.将mum +1 变为了1 5.再次进入while循环,判断num<100 是否为真-> 1<100 真 6.执行循环代码组,输出了打印内容 7.将num +1 变为2 ..... 再次进入while循环,判断num<100是否为真 -> 99<100 真 执行循环代码组,输出了打印内容 将num +1 变为100 再次进入while循环,判断num<100 是否为真 -> 100<100 假 循环结束 ''' ''' #使用while循环实现1-100的和 #声明计数变量 num = 1 #声明一个累加数值的变量 total = 0 while num<=100: #将当前的num值添加到total当中 total += num #total = total + num #改变num的值 num += 1 #顺序结构区域 print(total) ''' ''' #格式2 num = 100 while num<50: print('悲催的职业,炮兵连的炊事兵') num += 1 else: print('条件为假') ''' #判断循环的第一次是否就是假值 #计数变量 num = 200 #是否开始循环的标志变量 flag = False while num<100: #进入循环时设定标志为True 表示来过循环区域执行 flag = True print('悲催的职业,炮兵连的炊事兵') num+=1 else: #判断是否第一次就是假值 if flag == False: print('起始值为假,循环未能执行') else: print('起始值为真,进入过循环')
false
ec41d9fc44f34b45f90aa8e63e77b37891603005
GeekyShacklebolt/PYM_exercises
/day_1/variable_and_datatypes.py
1,628
4.25
4
#!/usr/bin/python3 a = 21 b = 34 c = a + b print(c) print('India') print("India") print('India\'s') print("\n") # reading input from the keyboard num = int(input("Enter a number: ")) print(num) if num < 10: print("this is less than 10") else: print("this is bigger than 10") print("\n") # INTEREST PROBLEM amt = float(input("Enter the amount: ")) interest = float(input("Enter the rate of interest: ")) period = float(input("Enter the period: ")) year = 1 tot = 0 while year <= period: amt = amt + (interest*amt) print("After %d year, your amount will be %f" % (year,amt)) year = year + 1 print("\n") # AVERAGE OF N NUMBERS N = int(input("Enter how many numbers would you like to enter: ")) ctr = 1 SUM = 0 average = 0 while ctr <= N: num = int(input("Enter the no. {} : " .format(ctr))) SUM = SUM + num ctr = ctr + 1 average = float(SUM)/N print("N is %d, SUM of \'N\' numbers is %d, Average is %f" % (N,SUM,average)) print("\n") # TEMPERATURE CONVERSION celcius = 0 while celcius <= 350: farhenheit = 1.8 * celcius + 32 print("Celcius = %d and Farhenheit = %f" % (celcius,farhenheit)) celcius = celcius + 25 print("\n") # MULTIPLE ASSIGNMENT a, b = 50, 10 print(a, '+', b) # swapping a, b = b, a print("%d + %d" % (a,b)) print("\n") # TUPLE PACKING AND UNPACKING tuple = ("shiva","Btech","Python") name, course, language = tuple print(name, course, language) print("\n") # FORMATTING STRINGS msg = "{0} is studying in {1} and learning {2}".format(name,course,language) print(msg) msg2 = f"{name} is studying in {course} an learning {language}" print(msg2)
true
cd96511ea7d7a311542ea00ad6b0c27921ed1ca0
Youth-Avenue-2021/All_Programming
/PYTHON/LIST/double space identifier.py
392
4.28125
4
#This programs returns the index value where double space occure else it returns -1 a = "This program enables you to find if the string conatins double space!" #a = "This program enables you to find if the string conatins double space!" double_space = a.find(" ") print(double_space) #now the further code replaces double space (if any) with single space a = a.replace(" "," ") print(a)
true
8d89fbba4e0f120c138ed4bc009cc502976c045b
carlossarante/python100days
/EventsPlayGround/turtle_race.py
1,838
4.21875
4
import turtle import random from turtle import Turtle, Screen def get_turtle_race(screen_width, screen_height, turtle_colors): starting_point_x = - screen_width / 2 + 20 gap = screen_height / len(turtle_colors) turtle_list = [] turtle_y_positions = [-(screen_height / ) + gap * color_index for color_index in range(0, len(turtle_colors))] for turtle_index in range(0, len(turtle_colors)): turtle_created = Turtle(shape="turtle") turtle_created.penup() turtle_created.color(turtle_colors[turtle_index]) turtle_created.goto((starting_point_x, turtle_y_positions[turtle_index])) turtle_list.append(turtle_created) return turtle_list def start_race(screen_width, screen_height): screen = Screen() is_race_on = False screen.setup(width=screen_width, height=screen_height) user_bet = screen.textinput(title="Make your first bet", prompt="Which turtle will win the race? Enter a color: ") turtle_colors = ['red', 'pink', 'blue', 'black', 'yellow', 'gray'] turtle_list = get_turtle_race(screen_width=screen_width, screen_height=screen_height, turtle_colors=turtle_colors) if user_bet: is_race_on = True while is_race_on: # turtle size is 40 for turtle_created in turtle_list: if turtle_created.xcor() > screen_width / 2 - (40 / 2): is_race_on = False winner_color = turtle.pencolor() if user_bet.lower() == winner_color: print(f'You\'ve won! turtle {turtle_created.pencolor()} is the winner!') else: print(f'You\'ve lost! turtle {turtle_created.pencolor()} is the winner!') random_distance = random.randint(0, 10) turtle_created.forward(random_distance) screen.exitonclick()
true
ba4278fba6ee31001612f952843c93d39a28b66e
warmer90/ttas
/面向对象/bike.py
1,466
4.28125
4
""" 一个自行车类(Bicycle),run(骑行),调用显示骑行里程km(骑行里程传入的数字) 写一个EBicycle 继承 Bicycle,添加电量valume 属性通过参数传入,有两个方法 1. fill_charge(vol),用来充电。vol 为电量 2. run(km) 方法骑行, 10km消耗一度电,电量耗尽调用Bicycle的run方法骑行 """ class Bicycle: # 定义一个run方法,需要传入km参数 def run(self,km): print(f"自行车骑行的里程数:{km}") class EBicycle(Bicycle): #初始化 def __init__(self,volume): #实例变量 self.valume = volume def get_valume(self): print("当前电量:",self.valume) def fill_charge(self,vol): print("充电电量",vol) def run(self,km): #电量支持的最大里程数 e_miles = self.valume*10 ## 假如电瓶有10度电,我们支持的里程 10*10=100 miles = km - e_miles if miles<=0: print("电瓶车骑了:",km) else: #因为子类中有个run,把父类的run覆盖掉了 #self.run #应该传入参数是除了电瓶车之外的里程数 print("电瓶车骑了",e_miles) super().run(miles) # bicycle= Bicycle() # bicycle.run(100) #类在初始化时候,给init中定义的参数传参 # bike = EBicycle(100) # bike.get_valume() bike = EBicycle(16) bike.run(250)
false
c38bd931c248c1b4f1b4ce75d79f12195c8ddd62
martinbolger/hein_scraping
/code/modules/data_manipulation_functions.py
1,779
4.34375
4
#!/usr/bin/env python import pandas as pd #Removes commas from all values in a row of a dataframe def remove_commas(df1): for col in df1.columns: df1[col] = df1[col].str.replace(',', '') return df1 #This function checks to see if a file with the papers from a professor has already been created #If it has, their name is skipped (their data is not rescraped) def check_files(fm_name, last_name, current_files): done = False for cur_file in current_files: if fm_name.lower() in cur_file.lower() and last_name.lower() in cur_file.lower(): done = True break return done # This function converts a list of strings to a comma # separated string. def list_to_comma_separated_string(list_of_strings): list_str = ', '.join(list_of_strings) list_str = list_str.replace('\'', '') list_str.replace('\"', '') return list_str # This function is used to concatenate strings # in a panda dataframe. It can handle cases when # one of the strings is missing. It is used in an # apply statement. def concat_function(x, y): if not pd.isna(x) and not pd.isna(y): return x + ", " + y elif not pd.isna(x): return x elif not pd.isna(y): return y else: return x # This function removes substrings from one list of # comma separated strings from another list. It is used # to remove error names from the alt names lists. def remove_err_names(names, err_names): if names: names_list = names.split(", ") else: names_list = [] if err_names: err_names_list = err_names.split(", ") else: err_names_list = [] names_list = [x for x in names_list if x not in err_names_list] return list_to_comma_separated_string(names_list)
true
2bf68d11dad29d6d5e4bdac9df597f79e6f6ffce
dragan-nikolic/python_ex
/operators.py
659
4.125
4
""" Created on 2012-02-12 @author: dnikolic """ def use_logical_operators(os_name='WINDOWS', os_version='5.1'): if os_name == 'WINDOWS' and os_version == '5.1': print 'OS is WinXP!' else: print 'OS is not XP' if ((os_name == 'WINDOWS') and (os_version == '5.1')): print 'Told you, WinXP!' else: print 'Told you, not XP!' def use_arithmetic_operators(): x = 5 print 'x=%d' % x x += 9 print 'x=%d' % x x /= 2 print 'x=%d' % x if __name__ == '__main__': use_logical_operators() use_logical_operators('LINUX') #use_arithmetic_operators() pass
false
21f0da384a2b5a8e4960ff3384fa07f7eda8e272
dragan-nikolic/python_ex
/tools/bulk_rename.py
1,674
4.25
4
""" The utility for renaming all the files in a directory which name contains PATTERN_IN_ORIGINAL_NAME text. New name will be NAME_PREFIX + PATTERN_IN_NEW_NAME + NAMME_SUFFIX. Examples: old.E23.name.mp4 -> new_E23_name.m4v """ import os import sys import re # --- Modify these variables to customize the renaming --- PATTERN_IN_ORIGINAL_NAME = '\.E\d{1,3}\.' PATTERN_IN_NEW_NAME = '\d{1,3}' # PATTERN_IN_NEW_NAME pattern is subpattern of the PATERN_IN_ORIGINAL_NAME NAME_PREFIX = 'new_' NAME_SUFFIX = '_name.m4v' # -------------------------------------------------------- try: dir_name = sys.argv[1] except Exception: dir_name = "." def find_pattern_in_string(pattern, string): '''Returns string that satisfies pattern if found Otherwise returns None ''' res = None try: res = re.compile(pattern).search(string).group() except Exception: res = None return res def rename_file(old_name, new_name): os.rename(old_name, new_name) for root, dirs, files in os.walk(dir_name): for filename in files: filepath = os.path.abspath(os.path.join(root, filename)) print(filepath) filepath_parts = os.path.split(filepath) filename = filepath_parts[1] print(filename) print(type(filename)) result = find_pattern_in_string(PATTERN_IN_ORIGINAL_NAME, filename) print('result1: ', result) print(type(result)) result = find_pattern_in_string(PATTERN_IN_NEW_NAME, result) print('result2: ', result) if result: rename_file(filepath, os.path.join(filepath_parts[0], NAME_PREFIX + result + NAME_SUFFIX))
true
8c974518142abb05afd1becb891d60e530b0ba1c
kemoelamorim/Entra21_Resolucao
/Resolucao_Aula007/Ex001.py
436
4.21875
4
""" --- Exercício 1 - Funções - 1 --- Escreva uma função que imprima um cabeçalho --- O cabeçalho deve ser escrito usando a multiplicação de carácter --- O cabeçalho deev conter o nome de uma empresa, que será uma variável --- Realize a chamada da função na ultima linha do seu programa """ empresa = input('Digite o nome da empesa: ') def cabecalho(empresa): print(f"{empresa:*^30}".upper() ) cabecalho(empresa)
false
ac2af637e4aebb77a5b3637d37f446b2f5aad852
gdmhw/automateTheBoringStuffWithPython
/collatz_sequence.py
413
4.15625
4
def collatz(number): if number % 2 == 0: res = number // 2 print(res) return res elif number % 2 == 1: res = 3 * number + 1 print(res) return res try: userNum = int(input('Enter a number: ')) while userNum != 1: userNum = collatz(int(userNum)) except ValueError: print('Value Error - please enter an integer value')
false
856b03934440680775d97774fb653a1669c4bff5
hhhoang/100DaysOfCode_HH
/Day41.py
908
4.125
4
""" Create a GUI to convert user input of ounce into gram with tkinker """ from tkinter import * window = Tk() window.title("Ounce to Gram Converter") #window.minsize(width=500, height=300) window.config(padx=20, pady=20) # Input input = Entry(width=10) input.grid(column=1, row=1) input.insert(END, string="0") print(input.get()) #Label ounces = Label(text="Ounces", font=("Arial", 10)) ounces.grid(column=2, row=1) #my_label.config(padx=50, pady=50) equal = Label(text="is equal to", font=("Arial", 10)) equal.grid(column=0, row=2) result = Label(text="0", font=("Arial", 10)) result.grid(column=1, row=2) gram = Label(text="Gram", font=("Arial", 10)) gram.grid(column=2, row=2) # Button def button_clicked(): ounce = float(input.get()) gram = round(ounce*28.3495231) result.config(text=f"{gram}") button = Button(text="Calculate", command=button_clicked) button.grid(column=1, row=3)
true
c60621068444c1b118cd05cfe1f69a380186ecc9
hhhoang/100DaysOfCode_HH
/Day21.py
856
4.25
4
# https://www.codewars.com/kata/after-midnight/train/python? """ Write a function that takes a negative or positive integer, which represents the number of minutes before (-) or after (+) Sunday midnight, and returns the current day of the week and the current time in 24hr format ('hh:mm') as a string. """ def day_and_time(mins): dayspos = ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday") print(mins) minutes, hours_final, days_final = get_min_hour_day(mins) return "{} {}:{}".format(dayspos[days_final], str(hours_final).zfill(2),str(minutes).zfill(2)) def get_min_hour_day(mins, clock_wise=True): hours, minutes = divmod(mins, 60) days, hours_final = divmod(hours, 24) days_final = days%7 print(days_final, days, hours_final, hours, minutes) return(minutes, hours_final, days_final)
true
dc52ecd5042e14b08b5f913fd15f63e26cc1c5a9
CarolFLima/hackerrank-solutions
/miscellaneous/primality.py
268
4.15625
4
def primality(n): if n == 2: return "Prime" if n < 2 or n % 2 == 0: return "Not prime" i = 3 while (i*i <= n): if n % i == 0: return "Not prime" i += 2 return "Prime" n = 5 print(primality(n))
false
823ac6f88f56e861802a399a7adad4fa655694b2
tford-dev/BMI-calculator
/BMI 2.py
2,765
4.125
4
class bmi_metric: def __init__(self, kgs = 1, m = 1): self.kgs = kgs self.m = m def bmi_met(self): return kgs / pow(m, 2) class bmi_imperial: def __init__(self, lbs = 1, ins = 1): self.lbs = lbs self.ins = ins def bmi_imp(self): return 703 * lbs / pow(ins, 2) while True: print("Welcome Body Mass Index Powered By @tfordfit") print("Enter 1 to use METRIC measurements.") print("Enter 2 to use IMPERIAL measurements.") print("Enter 3 to calculate height in meters.") print("Enter 4 to calculate height in inches.") print("Enter 5 to exit.") choice = input("Enter choice (1/2/3/4/5): ") if choice == '1': kgs = float(input("Enter your weight in kgs: ")) m = float(input("Enter your height in m: ")) met = bmi_metric(kgs, m) print(f"Your BMI is {met.bmi_met()}.") if met.bmi_met() < 19: print("Based on your BMI, you are considered underweight.") elif met.bmi_met() > 25: print("Based on your BMI, you are considered overweight, but note that the BMI scale does not take into account muscle mass.") elif met.bmi_met() >= 30: print("Based on your BMI, you are considered obese, but note that the BMI scale does not take into account muscle mass.") else: print("You are in the healthy range!") elif choice == '2': lbs = float(input("Enter your weight in pounds(lbs): ")) ins = float(input("Enter your height in inches: ")) imp = bmi_imperial(lbs, ins) print(f"Your BMI is {imp.bmi_imp()}.") if imp.bmi_imp() < 19: print("Based on your BMI, you are considered underweight.") elif imp.bmi_imp() > 25: print("Based on your BMI, you are considered overweight, but note that the BMI scale does not take into account muscle mass.") elif imp.bmi_imp() >= 30: print("Based on your BMI, you are considered obese, but note that the BMI scale does not take into account muscle mass.") else: print("You are in the healthy range!") elif choice == '3': cm = float(input("Enter your height in centimeters: ")) m = (cm * .01) print(f"Your height in meters is {m}.") elif choice == '4': ft = int(input("Enter your height in feet(you will enter how many inches next): ")) ins = float(input("Enter the amount of inches you are in ADDITION to your height in feet: ")) inches_total = (ft * 12) + ins print(f"Your height in inches is {inches_total}.") elif choice == '5': print("Peace be upon you.") break
false
799ed2b3388d2bdf28ae143d6ced43a3d7ccdceb
ParkerCS/ch18-19-exceptions-and-recursions-bernhardtjj
/recursion_lab.py
1,978
4.5625
5
""" Using the turtle library, create a fractal pattern. You may use heading/forward/backward or goto and fill commands to draw your fractal. Ideas for your fractal pattern might include examples from the chapter. You can find many fractal examples online, but please make your fractal unique. Experiment with the variables to change the appearance and behavior. Give your fractal a depth of at least 5. Ensure the fractal is contained on the screen (at whatever size you set it). Have fun. (35pts) """ import turtle colors = ["red", "orange", "yellow", "green", "blue", "purple", "magenta", "cyan", "black"] my_turtle = turtle.Turtle() my_turtle.showturtle() my_screen = turtle.Screen() my_screen.bgcolor('white') # Draw Here my_turtle.color("black") def draw(x, y, heading, dist, depth): my_turtle.up() my_turtle.goto(x, y) my_turtle.fillcolor(colors[depth % len(colors)]) my_turtle.down() my_turtle.begin_fill() for i in range(4): my_turtle.setheading(heading - 90 * i) my_turtle.forward(dist) my_turtle.end_fill() new_dist = dist / 1.618033 # phi my_turtle.backward(dist - new_dist) new_y = my_turtle.ycor() new_x = my_turtle.xcor() if depth > 0: draw(new_x, new_y, heading - 90, new_dist, depth - 1) draw(100, -250, 180, 500, 10) my_screen.exitonclick() # ____ # / ___|__ _ _ __ _ _ ___ _ _ __ _ _ _ ___ ___ ___ # | | / _` | '_ \ | | | |/ _ \| | | | / _` | | | |/ _ \/ __/ __| # | |__| (_| | | | | | |_| | (_) | |_| | | (_| | |_| | __/\__ \__ \ # \____\__,_|_| |_| \__, |\___/ \__,_| \__, |\__,_|\___||___/___/ # |___/ |___/ # _ _ _ _ _ _ ___ # __ _| |__ __ _| |_ | |_| |__ (_)___ (_)___ |__ \ # \ \ /\ / / '_ \ / _` | __| | __| '_ \| / __| | / __| / / # \ V V /| | | | (_| | |_ | |_| | | | \__ \ | \__ \ |_| # \_/\_/ |_| |_|\__,_|\__| \__|_| |_|_|___/ |_|___/ (_)
true
44d0d809ed25f029d3e71cccd9737b36e74d26fe
listenviolet/leetcode
/206-Reverse-Linked-List.py
1,452
4.3125
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ if head is None or head.next is None: return head cur = head p = head.next n = p.next while(n is not None): p.next = cur cur = p p = n n = p.next p.next = cur head.next = None head = p return head # Description # Reverse a singly linked list. # Example: # Input: 1->2->3->4->5->NULL # Output: 5->4->3->2->1->NULL # Follow up: # A linked list can be reversed either iteratively or recursively. Could you implement both? # Solution: # O -> O -> O -> O -> O -> None # | # head # | | | # cur p n # O<-> O O -> O -> O -> None # | | | # cur p n # O<-> O <- O O -> O -> None # | | | # cur p n # O<-> O <- O <- O O -> None # | | | # cur p n # None <- O <- O <- O <- O <- O # | | # cur p # | # head # Beats: 99.86% # Runtime: 40ms # easy
false
bb2b78245e2fb1b50f686c5733903fd0e2131f20
lincolen/Python-Crash-Course
/7 input and while/pizza_topings.py
271
4.15625
4
messege = "\n what would you like me to add to your pizza?: " messege += "\n when youve listed everything enter quit, to stop \n" topping = "" while topping!= "quit": topping = input(messege) if topping != "quit": print("\n I will add "+topping+" to your pizza")
true
5be60dddfa3603fa9a63f55553249b77b0a24292
DriveMyScream/Python
/07_Loops/Problem_No4.py
314
4.25
4
num = int(input("Enter a Number: ")) if(num>1): for i in range(2, num): if(num % 2 == 0): isPrime = False break else: isPrime = True else: isPrime = False if(isPrime): print("The Given Number is prime") else: print("The Given Number is Not Prime")
true
d45ea6047176d37a44821d3bfe2459c4ee878ee2
DriveMyScream/Python
/02_Data Type and Variable/02_Arithmetic_Operators.py
389
4.15625
4
a = 10 b = 20 addition = a + b substraction = a - b multiplication = a * b divide = a / b module = a % b print("The Addition Of Two Numbers is:",addition) print("The Substraction of Two Numbers is:",substraction) print("The Multiplication Of Two Numbers is:", multiplication) print("The Division Of Two Numbers is: ", divide) print("The Remiander of Two Operator is:", module)
true
235cefdfbc3438805deec087fc35e1a351afe923
dsahney/choose_sorting_algorithm
/max_and_min_values_of_list.py
1,017
4.5625
5
# This function will take a list, L, and determine its maximum and minimum values. import bubble_sort import insertion_sort import selection_sort def max_min_bubble(L): ''' (list) -> tuple Return a tuple that uses the bubble sort algorithms, to determine the min and max value of a list, respectively. ''' sorted_list = bubble_sort(L) max_value = L[-1] min_value = L[0] return (min_value, max_value) def max_min_insertion(L): ''' (list) -> tuple Return a tuple that uses the insertion sort algorithms, to determine the min and max value of a list, respectively. ''' sorted_list = insertion_sort(L) max_value = L[-1] min_value = L[0] return (min_value, max_value) def max_min_selection(L): ''' (list) -> tuple Return a tuple that uses the selection sort algorithms, to determine the min and max value of a list, respectively. ''' sorted_list = selection_sort(L) max_value = L[-1] min_value = L[0] return (min_value, max_value)
true
c1f228c7db44937757a7694374ccfef77911d0bd
acosme/project-euler
/38-pandigital_multiples.py
1,489
4.25
4
'''Take the number 192 and multiply it by each of 1, 2, and 3: 192 x 1 = 192 192 x 2 = 384 192 x 3 = 576 By concatenating each product we get the 1 to 9 pandigital, 192384576. We will call 192384576 the concatenated product of 192 and (1,2,3) The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4, and 5, giving the pandigital, 918273645, which is the concatenated product of 9 and (1,2,3,4,5). What is the largest 1 to 9 pandigital 9-digit number that can be formed as the concatenated product of an integer with (1,2, ... , n) where n > 1?''' #time: 1.5 hour def number_is_pandigital(concated_pandigital): no_repeat = True for c in concated_pandigital: if concated_pandigital.count(c) > 1: no_repeat = False return ('0' not in concated_pandigital) and (len(concated_pandigital) == 9) and no_repeat big_pandigital = 0 for multiplicand in range(0,9999): product = 0 multiplier = 0 procced = True concated_pandigital = "" print multiplicand while procced: multiplier += 1 product = multiplicand * multiplier concated_pandigital += str(product) if len(concated_pandigital) >= 9: procced = False if number_is_pandigital(concated_pandigital): if int(concated_pandigital) > big_pandigital: big_pandigital = int(concated_pandigital) print big_pandigital print "big_pandigital => %d" % big_pandigital
true
59ea937883e8bf59218e31a4c5469a312a8ef0e9
ltakuno/impacta
/POO/tratamento_erros/ex02.py
290
4.1875
4
from math import sqrt try: num = float(input('Digite um numero:')) resultado = sqrt(num) print ('A raiz quadrada de %.1f: %.1f' % (num, resultado) ) except ValueError: print('Não é possível tirar a raiz quadrada!') except Exception: print('Erro desconhecido!!')
false
25448a22ca20feff72b567f5a01274e7a5618c9f
marco-zangari/math
/data-statistics/variance_standard_dev.py
1,037
4.1875
4
"""Calculate the variance and standard deviation of a list of numbers.""" def calculate_mean(nums): """Calculate the meand of a given list of numbers.""" mean = sum(nums) / len(nums) return mean def find_differences(nums): """Find differences between each number in given list and mean.""" mean = calculate_mean(nums) diff = [] for num in nums: diff.append(num - mean) return diff def calculate_variance(nums): """Calculate variance of given list of numbers.""" diff = find_differences(nums) squared_diff = [] for d in diff: squared_diff.append(d**2) sum_squared_diff = sum(squared_diff) variance = sum_squared_diff / len(nums) return variance if __name__ == '__main__': donations = [100, 60, 70, 900, 100, 200, 500, 500, 503, 600, 1000, 1200] variance = calculate_variance(donations) print(f'The variance in the list of numbers is {variance}.') std = variance**0.5 print(f'The standard deviation of the list of numbers is {std}.')
true
573a8e549e804a81786320b263b1a49e402d9840
fpem123/ConcurrencyProgramming
/3주차/customThread.py
761
4.28125
4
''' - 20년 가을학기 분산병렬 프로그래밍 - 3장 스레드 라이프 - 사용자 정의 스래드 클래스 - 이호섭 ''' from threading import Thread # Thread를 상속받아 만들어진 사용자 정의 스래드 클래스 class myWorkerThread(Thread): i = 0 # 생성자 def __init__(self, i): self.i = i print("Hello World") Thread.__init__(self) # 필수 호출 # run() is start() def run(self): print("Thread {} is now running".format(i)) myThread = [] for i in range(10): myThread.append(myWorkerThread(i)) print("Create my Thread Object") myThread[i].start() print("Started my thread") for i in range(10): myThread[i].join() print("My Thread finished")
false
0fb97fc7411daac2e6550c6cc5dbe0755f40a51a
normkh21/PythonBasics
/dictionaries_loops.py
2,116
4.25
4
# looping dictionaries and more student1 = {'name': 'Hamza', 'gpa': 3.8, 'lastName': 'Hamrakulov'} student2 = {'name': 'Alexa', 'gpa': 3.9, 'lastName': 'Moseyeva'} # looping with keys for key in student1: print(' key is:', key) print() for key in sorted(student1.keys()): print('key is:', key) # for info in student1.keys(): for key in student1: print('value is:', student1[key]) for value in student1.values(): print('value is', value) print() # Looping the values for dkey, dvalue in student1.items(): print('key is', dkey) print('value is ', dvalue) print("Nesting dictionaries in LIST ") class_2020 = [student1, student2] print(class_2020) for student in class_2020: print('Name of the student:', student['name']) print('GPA of student:', student['gpa']) print('Last name of student:', student['lastName']) print("------------------------------------") print("****** Nesting dictionaries in Dictionaries") dclass_2020 = {'student1': student1, 'student2': student2} print(dclass_2020) for key, value in dclass_2020.items(): print('Key of the element: ', key) print('Value of the element: ', value) print('Name of the student: ', value['name']) print('GPA of the student: ', value['gpa']) print('Last Name of the student: ', value['lastName']) print("----------------") # # # print() # print('Excercise 6-5') # rivers = {'nile': 'egypt:', 'hudson' : 'usa:', 'volga': 'russia:', 'mississippi' : 'usa', 'thames': 'uk'} # # # The KEY runs through Value # for river, country in rivers.items(): # # if country == 'usa' or cuntry == 'uk' # if country in ['usa', 'uk']: # print(f"The {river.title} runs through {country.upper()}") # else: # print(f"The {river.title} runs through {country.title()}") # # print('Rivers are: ') # for river in rivers.keys(): # print('\t', river.title) # # print('Countires are: ') # for country in sorted(rivers.values(), reverse=True): # if country in ['usa', 'uk']: # print('\t', country.title()) # else: # print('\t', country.upper(), end=" | ") # #
false
aa72af9d0f2ec0b36cb7c5ef1707e8feea6f3c68
tonyechen/python-codes
/argsParameter/main.py
374
4.15625
4
# *args = parameter that will pack all arguments into a tuple # useful so that a function can accept a varying amount of arguments def add(*stuff): # doesn't have to be args, can be named anything else sum = 0 print(stuff) stuff = list(stuff) print(stuff) stuff[0] = 0 for i in stuff: sum += i return sum print(add(1,2,3))
true
4f3b5169cfe8767c3623305056ec1756a3e466d2
tonyechen/python-codes
/stringMethods/main.py
731
4.40625
4
# string methods name = "hello world" # len() = length of string print(len(name)) # str.find() - find index of the first appearance of string print(name.find("Bro")) # str.capitalize() - only the first letter is capitalized print(name.capitalize()) # str.upper() + str.Lower() - all cap or all lower-case print(name.upper()) print(name.lower()) # str.isdigit() - true or false depending on if the string is a digit print(name.isdigit()) # str.isalpha() - are these all alphabetical characters print(name.isalpha()) # str.count("String") - count the number of appearance print(name.count("o")) # str.replace("String", "String") - replace string print(name.replace("o", "x")) print(name * 3) # print a string multiple times
true
502c2f54445201c08db1e01808465dbf77fbffe3
tonyechen/python-codes
/sort/main.py
1,195
4.4375
4
# sort() method = used with lists # sort() function = used with iterables students = list() students = ["Squidward", "Sandy", "Patrick", "Spongebob", "Mr.Krabs"] students.sort() #students.sort(reverse = True) # reverse for i in students: print(i) #---------------------------------------------------------------------- print() students1 = ("Squidward", "Sandy", "Patrick", "Spongebob", "Mr.Krabs") sorted_students = sorted(students, reverse = True) for i in sorted_students: print(i) print() #---------------------------------------------------------------------- students2 = [("Squidward", "F", 60), ("Sandy", "A", 33), ("Patrick", "D", 36), ("Spongebob", "B", 20), ("Mr.Krabs", "C", 78)] grade = lambda grades:grades[1] students2.sort(key=grade) print(students2) print() #---------------------------------------------------------------------- students3 = (("Squidward", "F", 60), ("Sandy", "A", 33), ("Patrick", "D", 36), ("Spongebob", "B", 20), ("Mr.Krabs", "C", 78)) age1 = lambda ages:ages[2] sorted_students3 = sorted(students3, key=age1) print(sorted_students3)
true
4733c4cecc951c4d1fef7e1ae575617c9713e5ca
tonyechen/python-codes
/stringFormats/main.py
1,106
4.15625
4
# str.format() = oprtional method that gives users more control when displaying output animal = "Cow" item = "moon" print("the " + animal + " jumped over the " + item) print("The {} jumped over the {}".format(item, animal)) print("The {1} jumped over the {0}".format(item, animal)) # positional argument print("The {animal} jumped over the {item}".format(item="moon", animal="cow")) # keyword argument text = "The {} jumped over the {}" print(text.format(animal, item)) name = "Tony" print("Hello, my name is {:10}. Nice to meet you".format(name)) print("Hello, my name is {:<10}. Nice to meet you".format(name)) print("Hello, my name is {:>10}. Nice to meet you".format(name)) print("Hello, my name is {name:^10}. Nice to meet you".format(name="Tony")) number = 1000 print("The number pi is {:.3f}".format(number)) print("The number pi is {:,}".format(number)) print("The number pi is {:b}".format(number)) #binary print("The number pi is {:o}".format(number)) #Octave print("The number pi is {:x}".format(number)) #Hex print("The number pi is {:e}".format(number)) #scientific notation
true
bd61f2c7afbc677422126a6a912f90896804658b
YRTr/python_basics
/-2basic programs-/5KilometersToMiles.py
212
4.15625
4
K = input("Enter the number of kilometers") try: kilometers = float(K) except: print("Expected values") Mile = (1.6)*(kilometers) print("For a kilometers of %g -- The miles are : %g" %(kilometers, Mile))
true
b713e9cf1c446bc4f496ba05eed66eb1f2da95ff
dougscohen/cs-module-project-algorithms
/product_of_all_other_numbers/product_of_all_other_numbers.py
1,655
4.625
5
def multiplyList(myList) : if len(myList) == 0: return 0 # Multiply elements one by one else: result = 1 for x in myList: result = result * x return result def product_of_all_other_numbers(arr): """ Returns a list of integers consisting of the product of all numbers in the array _except_ the number at that index. Parameters: arr (list): a list of integers Returns: arr (list): a list of integers """ # Loop through each item in the list # using index as the split, separate into left and right arrays at index # create helper function to multiply all items in a list with each other multi = [] for i in range(1, len(arr) + 1): if i == 1 or i == (len(arr)): left = arr[:(i - 1)] right = arr[i:] left = multiplyList(left) right = multiplyList(right) both = left + right multi.append(both) else: left = arr[:(i - 1)] right = arr[i:] left = multiplyList(left) right = multiplyList(right) both = left * right multi.append(both) return multi if __name__ == '__main__': # Use the main function to test your implementation # arr = [1, 2, 3, 4, 5] arr = [2, 6, 9, 8, 2, 2, 9, 10, 7, 4, 7, 1, 9, 5, 9, 1, 8, 1, 8, 6, 2, 6, 4, 8, 9, 5, 4, 9, 10, 3, 9, 1, 9, 2, 6, 8, 5, 5, 4, 7, 7, 5, 8, 1, 6, 5, 1, 7, 7, 8] print(f"Output of product_of_all_other_numbers: {product_of_all_other_numbers(arr)}")
true
5c081dcbd81d1ce507a960c25465cba40045b499
nmwalsh/project-euler-solutions
/p1.py
781
4.53125
5
""" Problem 1 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. """ # Concepts used: # set, range, union import math # question-specific parameters min_val = 0 max_val = 1000 multiple_one = 3 multiple_two = 5 def sum_of_multiples(min_val, max_val, multiple_one, multiple_two): """ Function that returns sum of union set of all multiples between min_val and max_val for two given multiples """ set_one = set(range(min_val, max_val, multiple_one)) set_two = set(range(min_val, max_val, multiple_two)) union_sum = sum(set_one | set_two) print(union_sum) return union_sum sum_of_multiples(min_val, max_val, multiple_one, multiple_two)
true
72f1472ecac5a8783383fcbf62a3bbadb78f7ead
mohowzeh/Python_basics
/Python_basic_calculator.py
924
4.15625
4
''' freeCodeCamp - Python and Django BUILDING A BASIC CALCULATOR See YouTube: https://youtu.be/jBzwzrDvZ18?t=9458 ''' # try .. except .. statement # simple calculator # exit by typing q as operator while 1==1: try: num1 = int(input('Enter first number: ')) num2 = int(input('Enter second number: ')) except ValueError: print('Please enter numbers.') else: op = input('Enter operator (+, -, *, /) or type q to quit: ') if op == '+': print(num1, num2, op, '=>', num1+num2) elif op == '-': print(num1, num2, op, '=>', num1-num2) elif op == '*': print(num1, num2, op, '=>', num1*num2) elif op == '/': print(num1, num2, op, '=>', num1/num2) elif op == 'q': break else: print('Invalid operator.') finally: print('=============================')
false