blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
032e58342dd4dd263ae96aabb6563dad78d68b15
vinayakentc/BridgeLabz
/DataStructProg/Palindrome_Checker.py
1,363
4.46875
4
# Palindrome­Checker # a. Desc ­> A palindrome is a string that reads the same forward and backward, for # example, radar, toot, and madam. We would like to construct an algorithm to # input a string of characters and check whether it is a palindrome. # b. I/P ­> Take a String as an Input # c. Logic ­> The solution to this problem will use a deque to store the characters of # the string. We will process the string from left to right and add each character to # the rear of the deque. # d. O/P ­> True or False to Show if the String is Palindrome or not. # -------------------------------------------------------------------------------------- # importting required deque from DataStructProg.Deque import * # palindrom function def palindrome_checker(): # creating a Deque pali_deque = Deque() # taking an input string = input("Enter a string:") # inserting elements at rare for i in string: pali_deque.insertRare(i) # finding size of deque size = pali_deque.size() # take a empty string new_string = "" for i in range(size): new_string = new_string + pali_deque.removeRare() # comparing both strings if string == new_string: print("palindrome strings") else: print("Not palindrome strings") # driver program if __name__ == '__main__': palindrome_checker()
true
25fab75d27473ef6b0949ddcbb0a2678eefbf108
vinayakentc/BridgeLabz
/FunctionalProg/Factors.py
1,012
4.21875
4
# 6. Factors # a. Desc ­> Computes the prime factorization of N using brute force. # b. I/P ­> Number to find the prime factors # c. Logic ­> Traverse till i*i <= N instead of i <= N for efficiency . # d. O/P ­> Print the prime factors of number N # ---------------------------------------------------------------------- import math # Function on Factors def Factors(Number): while Number % 2 == 0: # prints 2 until num divided by 2 print(2) Number = Number // 2 for i in range(3, int(math.sqrt(Number)) + 1, 2): # using Brute force decreased iteration by i*i<=N while Number % i == 0: # for loop is for any odd number that gives remainder zero while dividing print(i) # prints number if remainder is 0 Number = Number // i if Number > 2: # this loop is for remaining numbers which not gives remainder zero print(Number) if __name__ == '__main__': Num = int(input("Enter number to find prime factors of it:")) Factors(Num)
true
8475bd109f4efb302b35f5d16ef5aaf358d43ad6
vinayakentc/BridgeLabz
/DataStructProg/UnOrderedList.py
1,985
4.28125
4
# UnOrdered List # a. Desc ­> Read the Text from a file, split it into words and arrange it as Linked List. # Take a user input to search a Word in the List. If the Word is not found then add it # to the list, and if it found then remove the word from the List. In the end save the # list into a file # b. I/P ­> Read from file the list of Words and take user input to search a Text # c. Logic ­> Create a Unordered Linked List. The Basic Building Block is the Node # Object. Each node object must hold at least two pieces of information. One ref to # the data field and second the ref to the next node object. # d. O/P ­> The List of Words to a File. # ------------------------------------------------------------------------------------------- import re from DataStructProg.LinkedList import * # function to read data from file def words_read(): file = open("DataStructWordsFile", "r") # created a linked list words_list = Linkedlist() # storing the elements into list for i in file: str_x = re.split(',| |\.|\n',i.lower()) for j in str_x: # STORING DATA into list words_list.append(j) file.close() return words_list # function for searching element in the list def searchList(doc_list): search_key = input("Enter a string to search:") search_key = search_key.lower() # seraching a key from using utility search function from linked list class sk=doc_list.search(search_key) # if found then # poping the element from list if sk == True: doc_list.pop(doc_list.indexOf(search_key)) # if word not found # adding word to the list else: doc_list.append(search_key) return doc_list # driver program if __name__ == '__main__': # calling function to read the words from a file a = words_read() # calling search function to search a element from list b = searchList(a) #a.printlist() # printing final list b.printlist()
true
43571e37ad1874a2fae40dda3072bf32b5a7129c
acse-yq3018/CMEECourseWork
/Week2/Code/lc1.py
1,521
4.21875
4
#!/usr/bin/env python3 """Use list comprehension and loops to extract target data""" __appname__ = 'lc1.py' __author__ = 'Yuxin Qin (yq3018@imperial.ac.uk)' __version__ = '0.0.1' ################################################################### birds = ( ('Passerculus sandwichensis','Savannah sparrow',18.7), ('Delichon urbica','House martin',19), ('Junco phaeonotus','Yellow-eyed junco',19.5), ('Junco hyemalis','Dark-eyed junco',19.6), ('Tachycineata bicolor','Tree swallow',20.2), ) #(1) Write three separate list comprehensions that create three different # lists containing the latin names, common names and mean body masses for # each species in birds, respectively. LatinName = list(i[0] for i in birds) print ("The latin names are ", LatinName) CommonName = list(i[1] for i in birds) print ("The common names are ", CommonName) BodyMass = list(i[2] for i in birds) print ("The BodyMass names are ", BodyMass) # (2) Now do the same using conventional loops (you can shoose to do this # before 1 !). LatinName2 = [] CommonName2 = [] BodyMass2 = [] for i in birds: LatinName2.append(i[0]) CommonName2.append(i[1]) BodyMass2.append(i[2]) print("The latin names are ", LatinName2) print("The common names are ", CommonName2) print("The mean body masses are ", BodyMass2) # ANNOTATE WHAT EVERY BLOCK OR IF NECESSARY, LINE IS DOING! # ALSO, PLEASE INCLUDE A DOCSTRING AT THE BEGINNING OF THIS FILE THAT # SAYS WHAT THE SCRIPT DOES AND WHO THE AUTHOR IS.
false
ecdab4779ef50d91930195f0e2199b8314b8ee47
josephhyatt/python_snippets
/check_for_greatest_of_3_numbers.py
405
4.1875
4
user_input_0 = int(input("Insert 1st number: ")) user_input_1 = int(input("Insert 2nd number: ")) user_input_2 = int(input("Insert 3rd number: ")) print("The biggest number is: ", end="") if user_input_1 <= user_input_0 >= user_input_2: print(user_input_0) elif user_input_0 <= user_input_1 >= user_input_2: print(user_input_1) elif user_input_0 <= user_input_2 >= user_input_1: print(user_input_2)
false
7d46a845ad0bed2298511f782e37faee1f7701ac
afurkanyegin/Python
/The Art of Doing Code 40 Challenging Python Programs Today/2-MPH to MPS Conversion App.py
262
4.15625
4
print("Welcome to the MPH to MPS Conversion App") speed_in_miles=float(input("What is your speed in miles:")) speed_in_meters=speed_in_miles * 0.4474 rounded_speed_in_meters=round(speed_in_meters,2) print(f"Your speed in MPS is: {rounded_speed_in_meters}")
true
23a71da2a35150b6dd70cc4f5507cce6c37b87a6
TonyVH/Python-Programming
/Chapter 02/Calculator.py
541
4.25
4
# Calculator.py # This is a simple, interactive calulator program def calculator(): print('Calculator guide:') print('Use + to add') print('Use - to subtract') print('Use * to multiply') print('Use / to divide') print('Use ** for exponentials') print('Use // for floor division') print('Use % to find the remainder of two numbers that cannot divide equally') print() x = eval(input('Enter your equation here: ')) print (x) print() while 1 != 2: return calculator() calculator()
true
0c7a6dc53b0e75076918ef422b5cf3da28b052a1
TonyVH/Python-Programming
/Chapter 05/acronym.py
330
4.34375
4
# acronym.py # Program to create an acronym from a user given sentence/phrase def main(): print('This program will create an acronym from a word or phrase\n') phrase = input('Enter a sentence or phrase: ') phrase = phrase.split() for words in phrase: print(words[0].upper(), end='') print() main()
true
433a50201f6701711216a57bd7839d86ca667331
zhangweisgithub/demo
/python_basic/其他/range的参数.py
508
4.25
4
# !/usr/bin/env python # -*- coding: utf-8 -*- # range(start, stop[, step]) print(list(range(5))) # [0, 1, 2, 3, 4] 默认是0-4 print(list(range(0, 5))) # [0, 1, 2, 3, 4] print(list(range(1, 7))) # [1, 2, 3, 4, 5, 6] print(list(range(3, 20, 3))) # [3, 6, 9, 12, 15, 18] 第三个参数代表的是step print(list(range(10, 0, -1))) # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] 代表的是从大到小排列,range的第一个参数大于第二个,step必须为负 for i in range(10, 0, -1): print(i)
false
a5e07f98fb6d18fc88a88495e1aadb105b7fb5a5
zhangweisgithub/demo
/algorithm/冒泡排序.py
1,468
4.1875
4
# !/usr/bin/env python # -*- coding: utf-8 -*- """ 基本思想: 冒泡排序,类似于水中冒泡,较大的数沉下去,较小的数慢慢冒起来,假设从小到大,即为较大的数慢慢往后排,较小的数慢慢往前排。 直观表达,每一趟遍历,将一个最大的数移到序列末 冒泡排序的时间复杂度是O(N^2) 冒泡排序的思想: 每次比较两个相邻的元素, 如果他们的顺序错误就把他们交换位置 冒泡排序原理: 每一趟只能将一个数归位, 如果有n个数进行排序,只需将n-1个数归位, 也就是说要进行n-1趟操作(已经归位的数不用再比较) 缺点: 冒泡排序解决了桶排序浪费空间的问题, 但是冒泡排序的效率特别低 """ def bubble_sort(alist): for j in range(len(alist) - 1, 0, -1): # 从大到小排列 # j表示每次遍历需要比较的次数,是逐渐减小的 for i in range(j): if alist[i] > alist[i + 1]: alist[i], alist[i + 1] = alist[i + 1], alist[i] li = [54, 15, 12, -10, 45, 96, 23, 75] bubble_sort(li) print(li) # [-10, 12, 15, 23, 45, 54, 75, 96] # 第二种方法: def bubble_sort2(lis): for i in range(0, len(lis)): for j in range(i + 1, len(lis)): # 这个代表随着i的增加,进行比较的次数会越来越少 if lis[i] > lis[i + 1]: lis[i], lis[i + 1] = lis[i + 1], lis[i] return lis print(bubble_sort2(li))
false
1bcd526e6e0efd5c566f629a2d4945e2c41b759b
Yurcik45/python-train
/pynative_exercises/2.py
264
4.34375
4
#2 Отображение трех строк «Name», «Is», «James» как «Name ** Is ** James» string_1 = "Name" string_2 = "Is" string_3 = "James" print(string_1 + "**" + string_2 + "**" + string_3) # or print(string_1, string_2, string_3, sep="**")
false
a0ee9db42b6a9cc7f4a423e2281a718a1789981f
DeepeshYadav/AutomationMarch2020
/PythonPractice/Lambda_function/practice/Decorator Introdcution.py
740
4.3125
4
""" Decorators 1. Need to take a function as parameters 2. Add Functionality to the function. 3. Function need to return another function. -> In general language a decorator means , the person who does decoration job. to make things more presentable. for examples i want to given gift to my friend like watch 1 -> I can give watch to friend 2 -> I can give watch to friend with gift wrapping, which is more presentable and good look. THERE ARE TWO TYPE DECORATORS: 1 -> Function Decorators 2 -> Class Decorators Following thing will learn in function decorators: 1 : Nested Function 2 : Function Return Function. 3 : Refrence of function it memory location of function. 4 : Use Function as parameter of another function. """
true
cde40dccf5ea9938c8572de56bb6de3a9f8d131e
DeepeshYadav/AutomationMarch2020
/PythonPractice/Decorators/property_decor_example1.py
544
4.28125
4
# In this class will how to set values using setter # and next example2 will explain how achieve this using @propert decorator class Student: def __init__(self, name, grade): self.name = name self.grade = grade def msg(self): return self.name +" got the grade "+self.grade def setter(self, msg): sent = msg.split(" ") self.name = sent[0] self.grade = sent[-1] obj = Student('Amey', 'A') obj.setter("Rahul got the grade B") print(obj.name) print(obj.grade) print(obj.msg())
true
0248a047a97752eb6028adf81022ad57b765e5e2
ahmed-t-7/Programming-Foundations-Fundamentals
/3. Variables and Data Types/Challenge_What_is_The_output.py
496
4.40625
4
print("Challenge 1:") # A message for the user message = "This is going to be tricky ;)" Message = "Very tricky!" print(message) # show the message on the screen this statement will print the first message variable # Perform mathematical operations result = 2**3 print("2**3 =", result) result = 5 - 3 #Change the value of variable from 8 To 2 #print("5 - 3 =", result) #This is a comment statement willn't print anything print("Challenge complete!") # This Will print Challenge complete
true
8bcdc627379f686bbc937d6c6c756cadd1d9cc75
JeffreyAsuncion/Study-Guides
/Unit_3_Sprint_2/study_part1.py
2,472
4.28125
4
import os import sqlite3 """ ## Starting From Scratch Create a file named `study_part1.py` and complete the exercise below. The only library you should need to import is `sqlite3`. Don't forget to be PEP8 compliant! 1. Create a new database file call `study_part1.sqlite3` """ DB_FILEPATH = os.path.join(os.path.dirname(__file__), "study_part1.sqlite3") """ 2. Create a table with the following columns ``` student - string studied - string grade - int age - int sex - string ``` """ connection = sqlite3.connect(DB_FILEPATH) cursor = connection.cursor() #Drop Table cursor.execute('DROP TABLE IF EXISTS students;') create_table_query = """ CREATE TABLE IF NOT EXISTS students ( id INTEGER PRIMARY KEY AUTOINCREMENT ,student VARCHAR(30) ,studied TEXT ,grade INTEGER ,age INTEGER ,sex INTEGER ); """ cursor.execute(create_table_query) """ 3. Fill the table with the following data """ thundercats = [ ('Lion-O', 'True', 85, 24, 'Male'), ('Cheetara', 'True', 95, 22, 'Female'), ('Mumm-Ra', 'False', 65, 153, 'Male'), ('Snarf', 'False', 70, 15, 'Male'), ('Panthro', 'True', 80, 30, 'Male') ] for thundercat in thundercats: insert_query = f''' INSERT INTO students (student, studied, grade, age, sex) VALUES {thundercat} ''' cursor.execute(insert_query) connection.commit() """ 4. Save your data. You can check that everything is working so far if you can view the table and data in DBBrowser """ """ 5. Write the following queries to check your work. Querie outputs should be formatted for readability, don't simply print a number to the screen with no explanation, add context. """ query = 'SELECT AVG(age) FROM students;' results = cursor.execute(query).fetchone() print("What is the average age? Expected Result - 48.8", results) query = "SELECT student FROM students WHERE sex = 'Female';" results = cursor.execute(query).fetchall() print("What are the name of the female students? Expected Result - 'Cheetara'", results) query = """ SELECT count(student) FROM students WHERE studied = 'True'; """ results = cursor.execute(query).fetchone() print("How many students studied? Expected Results - 3", results) query = """ SELECT student FROM students ORDER BY student; """ results = cursor.execute(query).fetchall() print("Return all students and all columns, sorted by student names in alphabetical order.", results)
true
223b6e68740e9411f390b37869df3125c8fe49c0
usamarabbani/Algorithms
/squareRoot.py
996
4.15625
4
'''take user input number = int(input("Enter a number to find the square root : ")) #end case where user enter less than 0 number if number < 0 : print("Please enter a valid number.") else : sq_root = number ** 0.5 print("Square root of {} is {} ".format(number,sq_root))''' def floorSqrt(x): # Base cases if x<0: return "Please enter a positive number" if (x == 0 or x == 1): return x # Do Binary Search for floor(sqrt(x)) start = 1 end = x while (start <= end): mid = (start + end) // 2 # If x is a perfect square if (mid * mid == x): return mid # Since we need floor, we update # answer when mid*mid is smaller # than x, and move closer to sqrt(x) if (mid * mid < x): start = mid + 1 ans = mid else: # If mid*mid is greater than x end = mid - 1 return ans # driver code x = 9 print(floorSqrt(x))
true
f3e397a744558c935850f18001b4a5bf14e56ec6
usamarabbani/Algorithms
/mergeTwoSortedList.py
2,189
4.46875
4
# Defining class which will create nodes for our linked lists class Node: def __init__(self, data): self.data = data self.next = None # Defining class which will create our linked list and also defining some methods class LinkedList: def __init__(self): self.head = None def printList(self): # Method to print linked list temp = self.head while temp: print (temp.data) temp = temp.next def append(self, new_data): # Method to add node at the end of the linked list new_node = Node(new_data) if self.head is None: self.head = new_node return last = self.head while last.next: last = last.next last.next = new_node # Defining function which will merge our linked lists def mergeLists(l1, l2): temp = None if l1 is None: return l2 if l2 is None: return l1 if l1.data <= l2.data: temp = l1 temp.next = mergeLists(l1.next, l2) else: temp = l2 temp.next = mergeLists(l1, l2.next) return temp # The main logic starts from here if __name__ == '__main__': list1 = LinkedList() # Creating linked list 1 list1.append(10) # Assigning values to linked list 1 in sorted manner list1.append(20) list1.append(30) list1.append(40) list1.append(50) list2 = LinkedList() # Creating linked list 2 list2.append(5) # Assigning values to linked list 2 in sorted manner list2.append(15) list2.append(25) list2.append(35) list2.append(45) print ("Printing Linked List 1") list1.printList() # Printing linked list 1 print ("Printing Linked List 2") list2.printList() # Printing linked list 2 list3 = LinkedList() # Creating linked list 3 # Merging linked list 1 and linked list 2 in linked list 3 list3.head = mergeLists(list1.head, list2.head) print ("Printing Linked List 3") list3.printList() # Printing linked list 3
true
970f23ef1afa5d5c2ae538b25c9c9fbc191745f9
BigThighDude/SNS
/Week3/Ch5_Ex2.py
1,133
4.34375
4
num = int(input("Enter integer to perform factorial operation:\n")) #prompt user to enter number, converts string to interger. program doesnt work if float is entered def fact_iter(num): #define iterative function product = 1 # define product before it is used for i in range(1,num+1): #count up from 1 (works with 0 as the product is just returned as 0 product = i*product #count up and multiply with each successive integer return product #return the product to the main script def fact_rec(num): if num==1: return 1 else: return num*fact_rec(num-1) # def fact_rec(num): #define recursive function # # product = product*fact_rec(num-1) #function calls itself # return product #function returns the final product ie. the factorial if num>1: #makes sure number is positive print("iterative ", fact_iter(num)) #run iterative program if input is valid print("recursive ", fact_rec(num)) #run recursive program if input is valid elif num==1 or num==0: print("1") else: #if number is negative print("Enter valid number") #return error message
true
59367641bfd30e48e5d18b80b386a518d30b627a
waltermblair/CSCI-220
/hydrocarbon.py
263
4.125
4
print("This program calculates the molecular weight of a hydrocarbon") h=eval(input("How many hydrogen atoms?")) c=eval(input("How many carbon atoms?")) o=eval(input("How many oxygen atoms?")) w=h*1.0079+c*12.011+o*15.9994 print("The weight is ",w," grams/mole")
false
dce29aacbef5e86574b300659dd52c9edb4868f5
waltermblair/CSCI-220
/random_walk.py
723
4.28125
4
from random import randrange def printIntro(): print("This program calculates your random walk of n steps.") def getInput(): n=eval(input("How many steps will you take? ")) return n def simulate(n): x=0 y=0 for i in range(n): direction=randrange(1,5) if direction==1: y=y+1 elif direction==2: x=x+1 elif direction==3: y=y-1 else: x=x-1 return x, y def printOutput(distance, n): print("You will be {0} steps away from origin after {1} steps" \ .format(distance, n)) def main(): printIntro() n=getInput() x, y =simulate(n) printOutput(abs(x)+abs(y), n) if __name__=='__main__': main()
true
ddb747b2b03438b099c0cf14b7320473be16888b
waltermblair/CSCI-220
/word_count_batch.py
404
4.28125
4
print("This program counts the number of words in your file") myfileName=input("Type your stupid ass file name below\n") myfile=open(myfileName,"r") mystring=myfile.read() mylist=mystring.split() word_count=len(mylist) char_count=len(mystring) line_count=mystring.count("\n") print("Words: {0}".format(word_count)) print("Characters: {0}".format(char_count)) print("Lines: {0}".format(line_count))
true
28f61625f6cc35e07557140465f6b2dcc3974d77
delgadoL7489/cti110
/P4LAB1_LeoDelgado.py
549
4.21875
4
#I have to draw a square and a triangle #09/24/13 #CTI-110 P4T1a-Shapes #Leonardo Delgado # #import the turtle import turtle #Specify the shape square = turtle.Turtle() #Draws the shape for draw in range(4): square.forward(100) square.right(90) #Specify the shape triangle = turtle.Turtle() #Draws the shape for draw in range(3): triangle.forward(50) triangle.left(120) #Imports the turtle to use #Specify the shape thats going to be drawn #Draw the shape #Specify the other shape #Draw the new shape
true
714c9c402b65cf3102425a3467c1561eaa20f2dd
delgadoL7489/cti110
/P3HW2_Shipping_LeoDelgado.py
532
4.15625
4
#CTI-110 #P3HW2-Shipping Charges #Leonardo Delgado #09/18/18 # #Asks user to input weight of package weight = int(input('Enter the weight of the package: ')) if weight <= 2: print('It is $1.50 per pound') if 2 < weight <=6: print('It is $3.00 per pound') if 6 < weight <=10: print('It is $4.00 per pound') if weight > 10: print('It is $4.75 per pound') #Prompts user to input weight of package #Saves value #Calculates if value is over certain value #Outputs the specific value for the inputed weight
true
05be92d0a985f8b51e2478d52d0d476539b1f96c
delgadoL7489/cti110
/P5T1_KilometersConverter_LeoDelgado.py
659
4.59375
5
#Prompts user to enter distance in kilmoters and outputs it in miles #09/30/18 #CTI-110 P5T1_KilometerConverter #Leonardo Delgado # #Get the number to multiply by Conversion_Factor = 0.6214 #Start the main funtion def main(): #Get the distance in kilometers kilometers = float(input('Enter a distance in kilometers: ')) #Display the converted distance. show_miles(kilometers) #Start the callback conversion function def show_miles(km): #Formula for conversion miles = km * Conversion_Factor #Output converted miles print(km, 'kilometers equals', miles, 'miles.') #Calls back the main funtion main()
true
b97e8694dd80c4207d2aef3db11326bef494c1d5
aju22/Assignments-2021
/Week1/run.py
602
4.15625
4
## This is the most simplest assignment where in you are asked to solve ## the folowing problems, you may use the internet ''' Problem - 0 Print the odd values in the given array ''' arr = [5,99,36,54,88] ## Code Here print(list(i for i in arr if not i % 2 ==0)) ''' Problem - 1 Print all the prime numbers from 0-100 ''' ## Code Here for num in range(101): if num > 1: for i in range(2, num): if (num % i) == 0: break else: print(num) ''' Problem - 2 Print the reverse of a string ''' string = 'Reverse Me!' ## Code Here print(string[::-1])
true
c487f10008953853ffce904974c01f60be0e9874
justus-migosi/desktop
/database/queries.py
1,179
4.40625
4
import sqlite3 from sqlite3 import Error # Create a connection def create_connection(file_path): """ Creates a database connection to the SQLite database specified by the 'path'. Parameters: - path - Provide path to a database file. A new database is created where non exists. Return: - Returns a Connection Object or None. """ try: connection = sqlite3.connect(r'file_path') except Error as e: connection = None print(f'Error! Occured while creating a connection! --> {e}') return connection # Read table from the database def read_table(connection, command): """ Queries all rows of the 'table' provided as a parameter. Parameters: - connection - Provide a connection object to the desired database. - table - Give the name of the table to query from the database. Return: - A list of rows related to the queried table. """ try: cur = connection.cursor() cur.execute(command) rows = cur.fetchball() except Error as e: rows = None print(f'This Error Occured while querying the {table} table! --> {e}') return rows
true
0acadc79127f5cc53cb616bac3e31c2ef120822f
shahzadhaider7/python-basics
/17 ranges.py
926
4.71875
5
# Ranges - range() range1 = range(10) # a range from 0 to 10, but not including 10 type(range1) # type = range range1 # this will only print starting and last element of range print(range1) # this will also print same, starting and last element list(range1) # this will list the whole range from start to the end list(range1[2:5]) # slicing the range datatype, using list to show all elements list(range1[3:9:2]) # slicing the range datatype with a step of 2 list(range1)[3:9:2] # another way to slice, this will return same as the last command list(range(20)) # we can still use range function without creating it first len(range1) # length is 10, 0 to 9 10 in range1 # False, because 10 is last element and is not included 7 not in range1 # False, because 7 is in range1 range1[3] # element at index 3 range1.index(5) # returns the index of 5
true
69f33f4919562b4dd54d868fbc63c81ecf4567ca
youssefibrahim/Programming-Questions
/Is Anagram.py
725
4.15625
4
#Write a method to decide if two strings are anagrams or not from collections import defaultdict def is_anagram(word_one, word_two): size_one = len(word_one) size_two = len(word_two) # First check if both strings hold same size if size_one != size_two: return False dict_chars = defaultdict(int) # Use dictionary to store both characters and how many # times they appear in one dictionary for chars in word_one: dict_chars[chars] += 1 for chars in word_two: dict_chars[chars] += 1 # Each character has to be divisible by two since # characters for both words are stored in the same # dictionary for key in dict_chars: if (dict_chars[key] % 2) != 0: return False return True
true
65778e41f5d2fae0c62993edd0c98ca8c603783d
EXCurryBar/108-2_Python-class
/GuessNumber.py
374
4.125
4
import random number = random.randint(0,100) print(number) print("Guess a magic number between 0 to 100") guess = -1 while guess != number : guess = eval(input("Enter your guess: ")) if guess == number : print("Yes, the number is ",number) elif guess > number : print("Your guess is too high") else : print("Your guess is too low")
true
24c61c19c87c1dfe990ace7a4640a17328add3b0
PaulSweeney89/CTA-Quiz
/factorial.py
322
4.15625
4
# Recursive Algorithms - Lecture 06 # Computing a factorial # Iterative Implementation def factorial(n): answer = 1 while n > 1: answer *= n n -= 1 return answer print(factorial(5)) # Recursive Implementation def factorial_rec(n): if n <= 1: return 1 else: return n*factorial_rec(n-1) print(factorial(5))
false
112da84fe029bfec6674f8fdf8cea87da361a96f
tminhduc2811/DSnA
/DataStructures/doubly-linked-list.py
2,053
4.3125
4
""" * Singly linked list is more suitable when we have limited memory and searching for elements is not our priority * When the limitation of memory is not our issue, and insertion, deletion task doesn't happend frequently """ class Node(): def __init__(self, data): self.data = data self.next = None self.prev = None class LinkedList(): def __init__(self, data): a = Node(data) self.head = a def traversal(l): temp = l.head result = '' while temp != None: result += str(temp.data) + '\t' temp = temp.next return result def insert_at_beginning(l, n): n.next = l.head l.head.prev = n l.head = n def insert_at_last(l, n): temp = l.head while temp.next != None: temp = temp.next temp.next = n n.prev = temp def insert_node_after(n, a): n.next = a.next n.next.prev = n n.prev = a a.next = n def delete(l, n): if n.prev == None: # If n is head l.head = n.next else: # n is not head n.prev.next = n.next if n.next != None: n.next.prev = n.prev del n if __name__=='__main__': l = LinkedList(20) a = Node('node-a') b = Node('node-b') c = Node('node-c') # Connecting all nodes l.head.next = a a.next = b a.prev = l.head b.next = c b.prev = a c.prev = b print('Linked list: ', traversal(l)) # Insert a node at the beginning of the list d = Node('Inserted-node') insert_at_beginning(l, d) print('Linked list after inserting a node at the beginning: ', traversal(l)) # Insert a node after node b e = Node('Node-after-b') insert_node_after(e, b) print('Linked list after inserting a node after b: ', traversal(l)) # Insert a node at the end of the list f = Node('last-node') insert_at_last(l, f) print('Linked list after inserting a node at the end: ', traversal(l)) # Delete node b = 50 delete(l, b) print('Linked list after delete node b: ', traversal(l))
true
2d0e92702fd53f816265742c6f025e2b8b39e181
tminhduc2811/DSnA
/Algorithms/binary_search.py
703
4.3125
4
import merge_sort def binary_search(arr, start, end, x): # T(n/2) => O(lg(n)) if start <= end: middle = (start + end)//2 if arr[middle] == x: return middle if arr[middle] > x: return binary_search(arr, start, middle - 1, x) if arr[middle] < x: return binary_search(arr, middle + 1, end, x) return None if __name__=='__main__': a = [2, 5, 1, 6, 7, 0, 33, 100, 12, 4, 22, 28, 27, 27] print('Array before being sorted: ', a) merge_sort.merge_sort(a, 0, len(a) - 1) print('Array after being sorted: ', a) # Now let's find the index of 100 print('Index of 100 is: ', binary_search(a, 0, len(a) - 1, 100))
false
bf3bf0b5546410fa191c261b24ec632e761ff151
nayana09/python
/file1.py
2,555
4.125
4
#!/usr/bin/env python # coding: utf-8 # In[1]: print("Hello, Welcome to python Introduction") # In[2]: #Python Variables x = 5 y = "Nayana" print(x) print(y) # In[7]: x = 4 x = "Grapes" print(x) # In[4]: #casting x = str(3) y = int(3) z = float(3) print(x) print(y) print(z) # In[6]: #get data type x = 5 y = "Nayana" print(type(x)) print(type(y)) # In[8]: x = "Orange" print(x) #double quotes are the same as single quotes: x = 'Orange' print(x) # In[10]: #case sensetive a = 4 A = "Orange" print(a) print(A) # In[11]: #assign multiple values in one line x, y, z = "Orange", "Banana", "Cherry" print(x) print(y) print(z) # In[12]: x = y = z = "Orange" print(x) print(y) print(z) # In[13]: fruits = ["apple", "banana", "grapes"] x, y, z = fruits print(x) print(y) print(z) # In[15]: #output variable x = "good morning" print("Hello " + x) # In[16]: x = "I Am " y = "Groot" z = x + y print(z) # In[17]: #Global variable x = "Groot" def myfunc(): print("I Am " + x) myfunc() # In[18]: x = "Groot" def myfunc(): x = "fantastic" print("Python is " + x) myfunc() print("I AM " + x) # In[19]: def myfunc(): global x x = "Groot" myfunc() print("I Am " + x) # In[22]: x = 5 y = 5.0 z = 'orange' a = 1j print(type(x)) print(type(y)) print(type(z)) print(type(a)) # In[23]: #random number import random print(random.randrange(1, 10)) # In[25]: #casting x = int(1.005) y = float(2) z = str(3.0) print(x) print(y) print(z) # In[26]: #python string a = "hai am very happy to learn python" print(a) # In[27]: #slicing a string a = "Hello, World!" print(a[2:5]) # In[31]: #slicing front, end, negative indexing b = "Hello, World!" print(b[:5]) print(b[2:]) print(b[-5:-2]) # In[41]: #String modifications a = " I am a groot " print(a.upper()) print(a.lower()) #remove white space print(a.strip()) #replace string print(a.replace("a", "not")) # In[47]: #split string a = "Hello, World" b = a.split(",") print(b) # In[48]: #String concatanation a = "Hello" b = "World" c = a + b print(c) # In[49]: a = "Hello" b = "World" c = a + " " + b print(c) # In[55]: #string format age = 23 txt = "My name is Nayana, and I am {}" print(txt.format(age)) # In[57]: #string format using index quantity = 3 itemno = 567 price = 49.95 myorder = "I want to pay {2} rupees for {0} pieces of Dolls {1}." print(myorder.format(quantity, itemno, price)) # In[59]: #escape chracter txt = "I am very \"innocent\" from the heart." print(txt) # In[ ]:
false
4e60800182b8bb8fccbb924b21ebc40cdfb497b5
jessiicacmoore/python-reinforcement-exercises
/python_fundamentals1/exercise5.py
319
4.125
4
distance_traveled = 0 while distance_traveled >= 0: print("Do you want to walk or run?") travel_mode = input() if travel_mode.lower() == "walk": distance_traveled += 1 elif travel_mode.lower() == "run": distance_traveled += 5 print("Distance from home is {}km.".format(distance_traveled))
true
6760a6c8331365ef174c58d2b742b3ffd407807c
jessiicacmoore/python-reinforcement-exercises
/python_fundamentals2/exercise6.py
218
4.25
4
def temperature_converter(f): c = (f-32)*5/9 print(f"{f} degrees fahrenheit is {c} degrees celsius!") print("Enter a temperature to convert from fahrenheit to celsius:") f = int(input()) temperature_converter(f)
false
32c4cc3778f9713a09d237cdb6024a7ec4fca5f2
chantigit/pythonbatch1_june2021data
/Python_9to10_June21Apps/project1/dictapps/ex1.py
534
4.25
4
#1.Creating empty dict a={} b=dict() #2.Creating dict with key,value c={'id':21,'name':'Ajay','height':5.6,'age':21,'name':'Arun'} print(type(a),type(b),type(c)) print(c) #3.Accessing dict values based on keys print(c['id']) print(c['name']) print(c['age']) print(c['height']) #4.Updating the dict c['height']=6.9 c['age']=25 print(c) #5.Deleting a pair from dict del c['age'] print(c) #6.Adding new pairs to exisitng dict c['city']='Hyd' c['phone']=9849098490 print(c) print(c.get('city')) c.pop('phone') print(c) c.clear() print(c)
false
bcc2045e953975bbdf2d78dc2888346072a0af24
chantigit/pythonbatch1_june2021data
/Python_9to10_June21Apps/project1/listapps/ex5.py
407
4.3125
4
#II.Reading list elements from console list1=list() size=int(input('Enter size of list:')) for i in range(size): list1.append(int(input('Enter an element:'))) print('List elements are:',list1) print('Iterating elements using for loop (index based accessing)') for i in range(size): print(list1[i]) print('Iterating elements using foreach loop(element based accessing)') for i in list1: print(i)
true
7ccc459d2ab9e420b47bfefd00e04dddff87fa8a
NSO2008/Python-Projects
/Printing to the terminal/HelloWorld.py
584
4.21875
4
#This is a comment, it will not print... #This says Hello World... print('Hello World') #This is another example... print("This uses double quotes") #Quotes are characters while quotation is the use quotes... print("""This uses triple quotation... it will be displayed however I type it""") #This is an exampe of the use of single quotes against double quotes... print('''I could do same with single quotes... See?''') #This is another way of printing a new line as against triple quotation... print("This uses a backslash then an n.... \nIt's used to signify a new line")
true
0b8f08d1f44d32eac328848be344c8d5e7cca3ad
cbolles/auto_typing
/auto_type/main.py
2,162
4.125
4
""" A tool that simulates keypresses based on a given input file. The program works by accepting a source file containing the text and an optional delimeter for how to split up the text. The program then creates an array of string based on the delimeter. Once the user presses the ESCAPE key, each value in the array will be typed out seperated by newlines. :author Collin Bolles: """ import keyboard import argparse from typing import List def get_segments(delimeter: str, source_location: str) -> List[str]: """ Takes in the location of the source file and returns a list of inputs that are split up based on the passed in delimeter :param delimeter: The delimeter to break up the input :param source_location: Path to file where source material exists """ segments = [] with open(source_location) as source_file: for line in source_file: for word in line.split(delimeter): segments.append(word.strip()) return segments def run_typing(segments: List[str]): """ Function that handles typing the segments out. :param segments: The segments to write out seperated by newlines """ for segment in segments: keyboard.write(segment) keyboard.press_and_release('enter') def main(): parser = argparse.ArgumentParser(description='''A tool to automatically type out a given piece of text''') parser.add_argument('source', action='store', help='''path to the source text that will be typed out by the program''') parser.add_argument('--delimeter', action='store', help='''delimeter that will be used to split up the text, by default will be split by newline''', default='\n') args = parser.parse_args() # Get the segments seperated based on the defined delimeter segments = get_segments(args.delimeter, args.source) # Setup listener to kick off running the typing function keyboard.add_hotkey('esc', lambda: run_typing(segments)) # Wait until the escape key is pressed again keyboard.wait('esc') if __name__ == '__main__': main()
true
3aa1d42dbbe55beadaeafe334950694fa9ece8f2
mickeyla/gwc
/Test A/test.py
596
4.125
4
#Comments are not for the code #Comments are for you #Or whoever answer1 = input ("What is your name?") print ("My name is", answer1) answer2 = input ("How old are you?") print ("I am", answer2, "years old!") answer3 = input ("Where are you from?") print ("I am from", answer3) answer4 = input ("Do you like coding?") if answer4 == ("Yes"): print ("Great! So do I!") else: print ("Oh, I'm sorry.") answer5 = input ("Do you think pineapple on pizza is okay?") if answer5 == ("Yes"): print ("No. Rethink your answer.") else: print ("Thank you! It's terrible!")
true
cc8bf4379d575d1d414c7fd61e236c3d4d904b12
hauqxngo/PythonSyntax
/words.py
1,385
4.75
5
# 1. For a list of words, print out each word on a separate line, but in all uppercase. How can you change a word to uppercase? Ask Python for help on what you can do with strings! # 2. Turn that into a function, print_upper_words. Test it out. (Don’t forget to add a docstring to your function!) def print_upper_words(words): """Print out each word on a separate line in all uppercase.""" for word in words: print(word.upper()) # 3. Change that function so that it only prints words that start with the letter ‘e’ (either upper or lowercase). def print_upper_words_e(words): """Print words that start with the letter ‘e’ (either upper or lowercase) on a separate line in all uppercase.""" for word in words: if word.startswith("E") or word.startswith("e"): print(word.upper()) # 4. Make your function more general: you should be able to pass in a set of letters, and it only prints words that start with one of those letters. def print_upper_words_x(words, must_start_with): """You should be able to pass in a set of letters, and it only prints words that start with one of those letters on a separate line in all uppercase.""" for word in words: for letter in must_start_with: if word.startswith(letter): print(word.upper()) break
true
9fe09a75083d05a172e61ce01faf3ab5d0e3e638
JoySnow/Algorithm
/tree/basic.py
1,253
4.3125
4
import Queue # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None def make_a_basic_n_level_tree(n): """ :type n: int :rtype: TreeNode """ if n <= 0: return None root = TreeNode(1) if n == 1: return root q = Queue.Queue() q.put(root) last_level_cnt = pow(2,n-1) val = 2 while not q.empty() and q.qsize() < last_level_cnt: c = q.get() l, r = TreeNode(val), TreeNode(val+1) c.left, c.right = l, r q.put(l) q.put(r) val += 2 return root def print_tree(root): """ :type root: TreeNode :rtype: None """ print "======Print Tree========" h = root if not h: print "Empty tree!" return level = [h,] while level: new_level = [] print_this_level = '' for n in level: print_this_level += "%s\t" % (n.val) if n.left: new_level.append(n.left) if n.right: new_level.append(n.right) print "BT: ", print_this_level level = new_level if __name__ == "__main__": pass
false
be8fc7374858e1eb60bf2c3d3f82e7d351eb67eb
rorschachwhy/mystuff
/learn-python-the-hard-way/ex11_提问.py
502
4.1875
4
#ϰ11 print "How old are you?" age = raw_input() #עʾ䣬printһšԲỻ #6'2"鿴you're '6\'2"'tall print "How tall are you?", #һֵ䣬ѡšҲֵheightIJе˼ height = raw_input(), print "How much do you weight?" weight = raw_input() print "So, you're %r old, %r tall and %r heavy." % ( age, height, weight)
false
f318ba10d7384cec391620866cf1dbaa4d533e1e
rorschachwhy/mystuff
/learn-python-the-hard-way/ex7_10.py
2,062
4.40625
4
#ϰ7ӡ print "Mary had a little lamb." print "Its fleece was white as %s." % 'snow' print "And everywhere that Mary went." #ӡ10 print "." * 10 end1 = 'C' end2 = 'h' end3 = 'e' end4 = 'e' end5 = 's' end6 = 'e' end7 = 'B' end8 = 'u' end9 = 'r' end10 = 'g' end11 = 'e' end12 = 'r' #עⶺţcomma÷űʾո print end1 + end2 + end3 + end4 + end5 + end6, print end7 + end8 + end9 + end10 + end11 +end12 #ϰ8ӡ ӡ formatter = "%r %r %r %r" print formatter % (1, 2, 3, 4) #עӡǵţpythonȴӡţ print formatter % ("one", "two", "three", "four") #עСддDzֵСдδ֪ҪôֵҪôŵַ print formatter % (True, 'false', False, "true") #formatterַӡעʹ˵ţ print formatter %(formatter, formatter, formatter, formatter) # print formatter % ( "I had this thing.", "That you could type up right.", "But it didn't sing.", "So I said goodnight.", ) #ϰ9ӡӡӡ days = "Mon Tue Wed Thu Fri Sat Sun" #ע \n ᵼ»س months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug" #ִӡݵģԡո񡱷ֿ print "Here are the days: %s" % 'aaa', days, "ddddd" #\nӡɻس print "Here are the months: ", months #ڴӡʱǰ󶼻л print """ There's something going on here. With the three double-quotes. We'll be able to type as much as we like. even 4 lines if we want, or 5, or 6. """ print "www" #ϰ10ʲô tabby_cat = "\tI'm tabbed in." persian_cat = "I'm split\non a line." #תַ backslash_cat = "I'm \\ a \\ cat." # fat_cat = """ I'll do a list: \t* Cat food \t* Fishies \t* Catnip\n\t* Grass """ print tabby_cat print persian_cat print backslash_cat print fat_cat #ת print "I am 6'2\" tall." print 'I am 6\'2" tall.'
false
b9aca14147a83020a98c423326da53267a25e8f2
Alexandra0102/python_basic_11_05_20
/env/les1_hw_6.py
1,244
4.25
4
"""6. Спортсмен занимается ежедневными пробежками. В первый день его результат составил a километров. Каждый день спортсмен увеличивал результат на 10 % относительно предыдущего. Требуется определить номер дня, на который общий результат спортсмена составить не менее b км. Программа должна принимать значения параметров a и b и выводить одно натуральное число — номер дня.""" while True: a = input('Введите количество за первый день км.\n') if a.isdigit(): a = int(a) break else: print('Неверный ввод. Повторите') while True: b = input('Введите необходимое количество км к итогу.\n') if b.isdigit(): b = int(b) break else: print('Неверный ввод. Повторите') i =1 while a <= b: print(f'{i} - день: {round(a,2)}') a = a * 1.1 i += 1 print(i)
false
1f52ebb74b762dcce6213360939086acb0b59f46
getconnected2010/testing123
/adventure story.py
1,194
4.1875
4
name = input('What is your name?:') print(f'Hello {name.capitalize()}, you are about to go on an adventure. You enter a room and see two doors. One is red and the other blue.') door_input = input('which door do you choose?: ') if door_input == 'red': print('Red door leads you to the future. You have to help a scientist to get back.') help = input('Do you help?: ') if help == 'yes': print('Awesome, the scentist will help you get back') elif help == 'no': print('what? now you are stuck in the future forever. Game over.') elif door_input == 'blue': print('Blue dooor leads to the past. You have to help a wizard, who will help you get back') wizard_help = input('will you help the wizard?: ') if wizard_help == 'yes': print('yaaay you get back') elif wizard_help == 'no': print ('omg. what were you thinking? now you have to steal his saber to escape.') steal = input('would you steal or leave?: ') if steal == 'steal': print('good choice. now run and use it to escape. good luck') elif steal == 'leave': print('woow you must know a way out. good luck.')
true
ad0f0a5db0b0ed49f0424fc474b802fa0d374581
josemariasosa/jomtools
/python/classes/exercises/person-list.py
368
4.15625
4
#!/usr/bin/env python # coding=utf-8 """ EN: ES: """ # ------------------------------------------------------------------------------ class A(object): """Definiendo la clases A""" def __init__(self, cantidad): self.cantidad = cantidad a = A(10) print(a.cantidad) # ------------------------------------------------------------------------------
false
cd7793038854eab3c67e631d3c158f2f00e9ad70
gauravraul/Competitive-Coding
/lcm.py
485
4.15625
4
# Program to get the lcm of two numbers def lcm(x,y) : #take the greater number if x>y: greater = x else: greater = y #if greater is divisible by any of the inputs , greater is the lcm #else increment greater by one until it is divisible by both the inputs while(True): if((greater % x == 0) and (greater % y == 0)): lcm = greater break greater +=1 return lcm print(lcm(10,45))
true
111497f1b16aaf63fbe66df46dfc1eb12b0e705e
migantoju/design-patterns
/structural/facade.py
1,225
4.3125
4
""" *Facade Pattern* Proporciona una interfaz unificada más simple a un sistema complejo. Proporciona una forma más sencilla de acceder a los métodos de los sistemas subyacentes al proporcionar un único punto de entrada. Oculta la complejidad de los sitemas y provee una interfaz al cliente con la cual puede acceder al sistema/sistemas. *PROS* - *CONS* - Cambios en métodos, los métodos están atados a la capa Facade, esto quiere decir que cualquier cambio en los métodos, también se deberá cambiar en la capa facade, lo cual no es favorable. """ class CPU: def freeze(self): print("freezing cpu....") def stuff(self): print("making cpu stuff....") class Memory: def load(self): print("making memory stuff...") class SSD: def stuff(self): print("making ssd's stuff....") class ComputerFacade: def __init__(self): self.cpu = CPU() self.memory = Memory() self.ssd = SSD() def start(self): self.cpu.freeze() self.memory.load() self.ssd.stuff() self.cpu.stuff() def main(): computer_facade = ComputerFacade() computer_facade.start() if __name__ == "__main__": main()
false
4d8e97b7749d85b15f5e1f20e332332ddf8e2513
the07/Python
/Algorithms/vowel_reduce.py
425
4.21875
4
#take a word and remove all the vowels and capitalise the first word state_names = ['Alabama', 'California', 'Oklahoma', 'Florida'] vowels = ['a','e','i','o','u'] for state in state_names: state_list = list(state) for letter in state_list: if letter.lower() in vowels: state_list.remove(letter) state_names[state_names.index(state)] = (''.join(state_list)).capitalize() print (state_names)
false
ecf0d4117ad8aab226e9808899b922d720cb0294
2018JTM2248/assignment-8
/ps2.py
1,919
4.65625
5
#!/usr/bin/python3 ###### this is the second .py file ########### ####### write your code here ########## #function definition to rotate a string d elemets to right def rotate_right(array,d): r1=array[0:len(array)-d] # taking first n-d letters r2=array[len(array)-d:] # last d letters rotate = r2+r1 # reversed the order return rotate #return ststement decrypted="" # decrypted string will be stored here #k1=int(input("Enter the amount by which key1 elemets to be rotated\n Decryption key1 = : ")) #k2=int(input("\nDecryption key2 = : ")) #k3=int(input("\nDecryption key3 = : ")) print("Enter Key") j1,j2,j3 =input().split(" ") k1=int(j1) k2=int(j2) k3=int(j3) quer_str = input("Enter Encrypted string\n") print(quer_str) alphabets="abcdefghijklmnopqrstuvwxyz_" alphabets1=alphabets[0:9] alphabets2=alphabets[9:18] alphabets3=alphabets[18:27] # Declaring Strings to store different key characters key1="" key2="" key3="" # Seperating keys for different range for i in quer_str : for j in alphabets1: if i==j : key1 = key1 + str(i) for k in alphabets2: if i==k : key2 = key2 + str(i) for l in alphabets3: if i==l: key3 = key3 + str(i) # keys sorted according to input numbers by which they are to be shifted new_k1=rotate_right(key1,k1) new_k2=rotate_right(key2,k2) new_k3=rotate_right(key3,k3) index1=0 index2=0 index3=0 # Decrypting a string and printing original decrypted string for i in quer_str: for j in new_k1 : if i==j: decrypted=decrypted+new_k1[index1] index1 = index1+1 for k in new_k2 : if i==k : decrypted=decrypted+new_k2[index2] index2=index2+1 for l in new_k3 : if i==l : decrypted=decrypted+new_k3[index3] index3=index3+1 print("Decrypted string is : ",decrypted)
true
620f08c42f7787718afa05210bef6c49e5422dff
vikashvishnu1508/algo
/oldCodes/threeNumSort.py
588
4.21875
4
array = [1, 0, 0, -1, -1, 0, 1, 1] order = [0, 1, -1] result= [0, 0, 0, 1, 1, 1, -1, -1] def threeNumSort(array, order): first = 0 second = 0 third = len(array) - 1 for i in range(len(array)): if array[i] == order[0]: second += 1 elif array[i] == order[2]: third -= 1 for i in range(len(array)): if i < second: array[i] = order[0] elif i >= second and i <= third: array[i] = order[1] else: array[i] = order[2] return array print(threeNumSort(array, order))
false
b71a8ef228748fe80c9696c057b4f6c459c13f49
vikashvishnu1508/algo
/Revision/Sorting/ThreeNumSort.py
521
4.15625
4
def threeNumSort(array, order): first = 0 second = 0 third = len(array) - 1 while second <= third: if array[second] == order[0]: array[first], array[second] = array[second], array[first] first += 1 second += 1 elif array[second] == order[2]: array[second], array[third] = array[third], array[second] third -= 1 else: second += 1 return array print(threeNumSort([1, 0, 0, -1, -1, 0, 1, 1], [0, 1, -1]))
true
4b56de005259fa36f89377a8f315b029ea6a0ef4
vikashvishnu1508/algo
/oldCodes/threeNumberSum.py
704
4.15625
4
def threeNumberSum(array, targetSum): # Write your code here. array.sort() result = [] for i in range(len(array) - 2): left = i + 1 right = len(array) - 1 while left < right: newSum = array[i] + array[left] + array[right] if newSum == targetSum: result.append([array[i], array[left], array[right]]) if len(result) == 3: return result left += 1 right -= 1 elif newSum < targetSum: left += 1 elif newSum > targetSum: right -= 1 return result print(threeNumberSum([12, 3, 1, 2, -6, 5, -8, 6], 0))
false
fff30ad774cb793bd20a0832cf45a1855e75a263
kacifer/leetcode-python
/problems/problem232.py
2,563
4.34375
4
# https://leetcode.com/problems/implement-queue-using-stacks/ # # Implement the following operations of a queue using stacks. # # push(x) -- Push element x to the back of queue. # pop() -- Removes the element from in front of queue. # peek() -- Get the front element. # empty() -- Return whether the queue is empty. # Example: # # MyQueue queue = new MyQueue(); # # queue.push(1); # queue.push(2); # queue.peek(); // returns 1 # queue.pop(); // returns 1 # queue.empty(); // returns false # Notes: # # You must use only standard operations of a stack -- which means only push # to top, peek/pop from top, size, and is empty operations are valid. # Depending on your language, stack may not be supported natively. You may # simulate a stack by using a list or deque (double-ended queue), as long as # you use only standard operations of a stack. # You may assume that all operations are valid (for example, no pop or peek # operations will be called on an empty queue). class MyQueue: def __init__(self): """ Initialize your data structure here. """ self.inStack, self.outStack = [], [] def push(self, x: int) -> None: """ Push element x to the back of queue. """ self.inStack.append(x) def transfer(self): for _ in range(len(self.inStack)): self.outStack.append(self.inStack.pop()) def pop(self) -> int: """ Removes the element from in front of queue and returns that element. """ if self.outStack: return self.outStack.pop() if self.inStack: self.transfer() return self.pop() raise ValueError("No more element") def peek(self) -> int: """ Get the front element. """ if self.outStack: return self.outStack[-1] if self.inStack: self.transfer() return self.peek() raise ValueError("No element") def empty(self) -> bool: """ Returns whether the queue is empty. """ return not self.inStack and not self.outStack # Your MyQueue object will be instantiated and called as such: # obj = MyQueue() # obj.push(x) # param_2 = obj.pop() # param_3 = obj.peek() # param_4 = obj.empty() def solve(): obj = MyQueue() assert obj.empty() obj.push(1) obj.push(2) assert not obj.empty() assert obj.peek() == 1 # not 2 assert not obj.empty() assert obj.pop() == 1 # not 2 assert obj.pop() == 2 assert obj.empty()
true
44bd4d30acfddb690556faaf26174f6a6faee6fe
Carvanlo/Python-Crash-Course
/Chapter 8/album.py
412
4.15625
4
def make_album(artist_name, album_title, track=''): """Return a dictionary of information of an album.""" album = {'artist': artist_name, 'title': album_title} if track: album['track'] = track return album album_1 = make_album('Adam Levine', 'Begin Again', 3) print(album_1) album_2 = make_album('Emma Stevens', 'Enchanted') print(album_2) album_3 = make_album('Blake Shelton', 'Based on a True Story') print(album_3)
true
94d9bca02dd044b5574522ef5f3185f8223a74e0
kumk/python_code
/donuts.py
593
4.15625
4
#Strings Exercise 1: Donuts # # Given an int count of a number of donuts, return a string of the form 'Number # #of donuts: <count>', where <count> is the number passed in. However, if the # #count is 10 or more, then use the word 'many' instead of the actual count. # So #donuts(5) returns 'Number of donuts: 5' and donuts(23) returns # 'Number of #donuts: many' import sys def numberofdonuts(count): if count < 10: print ("Number of donuts: ", count) else: print ("Number of #donuts: many") if __name__ == '__main__': numberofdonuts((int)(sys.argv[1]))
true
7b418a8b46b44fe6913f808024e6c2ba683885d2
loknath0502/python-programs
/28_local_global_variable.py
374
4.25
4
a=8 # global variable def n(): a=10 print("The local variable value is:",a) # local variable n() print("The global variable value is:",a) '''Note: The value of the global variable can be used by local function variable containing print . But the value of the local variable cannot be used by the global function variable containing print. '''
true
db8502678f3b850ad743cc8464436efcc6e01b20
ryanfirst/NextGen
/problem_types_set2.py
799
4.15625
4
# first_num = input('enter first number') # second_num = input('enter second number') # third_num = input('enter third number') # print(int(first_num) * int(second_num)) # print(int(first_num) * int(second_num) / int(third_num)) # num = input('pick a number') # print(int(num) % 2 == 0) # money = input('how much money will you be taking with you on vacation?') # print('you will have', end=' ') # print(int(money) * .86) # print(7 > 5 and 'b' > 'd') # print(7+5 and 'b' + 'd') # print(7 * 5 or 'b' * 'd') # name = input('what is your name?') # print(ord(name[0])) # word = input('pick any word') # print(word, 'is a great word') # ques = input('do you like that word') # # print('i agree') # # print(pow(4,2)) # # print(sum((3,5,2))) # a=8 # print(isinstance(a, int)) # print(vars()) # print(id(a))
true
2d7b0d2c2cca6e975e6d212ac961cfbd3773195e
Luciano-A-Vilete/Python_Codes
/BYU_codes/Vilete_009.py
1,865
4.25
4
#Python Code 009 #Starting: print('You buy a sea trip around the asia continent, but someday your trip is over … and you woke up on an isolated island, alone … ') print('When you look around, you see nothing and no one else with you … You see just 3 things:') #The GAME: print('The items that you see are: \n1. ROCK \n2. WOOD STICK \n3. A ROPE. \nWhat of them will you choose? ') choice_1 = input('Choose between a ROCK, a WOOD STICK or a ROPE: ') if choice_1.upper() in ('ROCK','WOOD STICK','ROPE'): print(f'Ok. Good choice. With {choice_1} let\'s see what we can do now...') if choice_1.upper() in 'ROCK': choice_2 = input(f'With {choice_1} you can: \nMAKE FIRE \nor \nTRY TO FIND AN ANIMAL TO KILL \nWhat do you want to do? ') if choice_2.upper() in 'MAKE FIRE': choice_2_1 = input('Now, with FIRE, something very bad happens: \nYou have called the attention of cannibal tribes that live in this island. What will you do? \nRUN \nor \nDIE: ') if choice_2_1.upper() in 'RUN': print('You try to RUN off from the cannibals, but they know that field very well. You\'ve failed. Sorry.') else: print('Try again another time! See you!') elif choice_2.upper() in 'FIND AN ANIMAL TO KILL': choice_2_2 = input('Can you tell me where will you hunt that animal? You can Choose between: \nFOREST \nand \nCAVE: \n') if choice_2_2.upper() in 'FOREST': print('When you search in the forest for some wild animal, you get caught on a trap of the cannibal tribes. Try again.') elif choice_2_2.upper() in 'CAVE': print('In the caves, you were attacked by a horde of bats until your death. Bye bye!') else: print('You can just choose between the 3 items that you have see...')
false
09c8da67245a500ea982344061b5d25dbc1d0a58
olive/college-fund
/module-001/Ex1-automated.py
1,456
4.25
4
# 1*.1.1) Rewrite the following function so that instead of printing strings, # the strings are returned. Each print statement should correspond to # a newline character '\n' in the functiono's output. def bar_print(a, b, c): if a == b: print("1") elif b == c: print("2") if a == c: print("3") return else: print("4") print("5") def bar_string(a, b, c): return "" # Example rewrite: def foo_print(a, b): if a == b: print("1") return else: print("2") if a == 1: print("3") print("4") def foo_string(a, b): result = "" if a == b: result += "1\n" return result else: result += "2\n" if a == 1: result += "3\n" result += "4\n" return result def test_equals(s, answ): lines = s.split('\n')[:-1] if lines == answ: print("PASS") else: print("FAIL") def main(): test_equals(bar_string(1,1,2), ["1","4","5"]) test_equals(bar_string(2,1,1), ["2","4","5"]) test_equals(bar_string(1,2,1), ["3"]) # 1*.1.2) Write another call to test_equals that prints PASS using func. # 1*.1.3) The second argument to test_equals must be distinct from the # above three. # 1*.1.4) Write 3 distinct calls to test_equals that pass for foo_string # instead of bar_string if __name__ == '__main__': main()
true
e1146f7a613892b9d79b70a5fdf218eafd812681
AjayKumar2916/python-challenges
/047-task.py
280
4.15625
4
''' Write a program which can filter() to make a list whose elements are even number between 1 and 20 (both included). Hints: Use filter() to filter elements of a list. Use lambda to define anonymous functions. ''' e = range(1, 21) a = filter(lambda x:x%2==0, e) print(list(a))
true
ed08b421996fab5b1db393c23496aff72939db24
svukosav/crm
/database.py
1,603
4.375
4
import sqlite3 db = sqlite3.connect("database") cursor = db.cursor() # cursor.execute("""DROP TABLE users""") if db: # Create a table cursor.execute("""CREATE TABLE users(id INTEGER PRIMARY KEY, name TEXT, phone TEXT, email TEXT unique, password TEXT)""") db.commit() name1 = 'Andres' phone1 = '3366858' email1 = 'user@example.com' password1 = '12345' name2 = 'John' phone2 = '5557241' email2 = 'johndoe@example.com' password2 = 'abcdef' # Inserting new entries cursor.execute("""INSERT INTO users(name, phone, email, password) VALUES (?,?,?,?)""", (name1, phone1, email1, password1)) id = cursor.lastrowid print("First user inserted") print("last row id: %d" % id) cursor.execute("""INSERT INTO users(name, phone, email, password) VALUES (?,?,?,?)""", (name2, phone2, email2, password2)) id = cursor.lastrowid print("Second user inserted") print("last row id: %d" % id) db.commit() # Reading entries cursor.execute("""SELECT name, email, phone FROM users""") # Get one user # user1 = cursor.fetchone() # print("Name: " + user1[0]) # Get all users for row in cursor: print('{0} : {1} , {2}'.format(row[0], row[1], row[2])) # Selecting one predefined user # user_id = 3 # cursor.execute("""SELECT name, email, phone FROM users WHERE id=?""", (user_id,)) # user = cursor.fetchone() # Updating users newphone = '3113093164' userid = 1 cursor.execute("""UPDATE users SET phone = ? WHERE id = ?""", (newphone, userid)) # Delete users userid = 2 cursor.execute(""" DELETE FROM users WHERE id = ?""", (userid,)) db.commit() # Drop a table cursor.execute("""DROP TABLE users""") db.commit() db.close()
true
184de35590496bb68c5b206432a49f9b240d2a46
joe-bq/algorithms
/sortings/bubble/bubble_rampUp_lowToHighIter.py
702
4.375
4
####################### # File: # bubbleSort_rampUp_lowToHighIter.py # Author: # Administrator # Description: # this program will show you how to write the insertion sort with the Python code. ####################### import sys def bubble_rampUp(a): length = len(a) for i in range(length-1, -1,-1): for j in range(0, i): if a[j] > a[j+1]: temp = a[j] a[j] = a[j+1] a[j+1] = temp def printArray(a): for x in range(len(a)): print a[x], print if __name__ == "__main__": stock_prices = [5, 10, 12, 3, 8, 18, 1, 14] bubble_rampUp(stock_prices) # a = stock_prices # temp = a[2] # a[2] = a[3] # a[3] = temp printArray(stock_prices)
false
8fcb7b82752f768c0f992df69857b9cde803f8d4
singhujjwal/python
/fastapi/things-async.py
695
4.625
5
#!/usr/bin/python3 # # # yield example # yield applies to the generators and is now used to do async programming as well. def test_yield(some_list): for i in some_list: if i%2 == 0: yield i # Normal list iterator mylist = [x*x for x in range(3)] for i in mylist: print (i) for i in mylist: print (i) for i in mylist: print (i) # now this is generator iter_list = (x*x for x in range(3)) for i in iter_list: print (i) for i in iter_list: print (i) # if __name__ == "__main__": # print ("this is the main function...") # test_list = [1,2,3,4,5,6,7,8,10,12] # evens = test_yield(test_list) # for i in evens: # print (i)
false
4dd828096a5eb69c493930c8381a4b0bb6e7f9ca
si20094536/Pyton-scripting-course-L1
/q4.py
673
4.375
4
## 4. Given a list of non-empty tuples, return a list sorted in increasing order by the last element in each tuple. ##e.g. [(1, 7), (1, 3), (3, 4, 5), (2, 2)] yields [(2, 2), (1, 3), (3, 4, 5), (1, 7)] ## Hint: use a custom key= function to extract the last element form each tuple. ##i. [(1, 3), (3, 2), (2, 1)] ##ii. [(1, 7), (1, 3), (3, 4, 5), (2, 2)] l1=[(1, 7), (1, 3), (3, 4, 5), (2, 2)] l2= [(1, 3), (3, 2), (2, 1)] l3= [(1, 7), (1, 3), (3, 4, 5), (2, 2)] def func(abc): print("The list before being sorted is : ",abc) abc.sort(key=lambda x: x[1]) print("The list are being sorted is : ",abc) func(l1) func(l2) func(l3)
true
9acba907b818c3e591571dbadaf3bdb751b91d99
kishan-pj/python_lab_exercise_1
/pythonproject_lab2/temperature.py
323
4.5
4
# if temperature is greater than 30, it's a hot day other wise if it's less than 10; # it's a cold day;otherwise,it's neither hot nor cold. temperature=int(input("enter the number: ")) if temperature>30: print("it's hot day") elif temperature<10: print("it's cold day") else: print("it's neither hot nor cold")
true
8d8fff8b1f4ac7d1e6b2e77857d855380769d878
kishan-pj/python_lab_exercise_1
/pythonproject_lab2/Qno.5positive_negative_zero.py
277
4.40625
4
# for given integer x print true if it is positive,print false if it is negative and print # zero if it is 0. x=int(input("enter the number: ")) if x>0: print("the number is positive ") elif x<0: print("the number is negative ") else: print("the number is zero ")
true
1d32702262eea6ddd58d869c713f7089361a5947
cwkarwisch/CS50-psets
/vigenere/vigenere.py
2,383
4.4375
4
import sys from cs50 import get_string def main(): # Test if the user has only input two strings (the name of the program and the keyword) if len(sys.argv) != 2: print("Usage: ./vigenere keyword") sys.exit(1) # Test if the keyword is strictly alphabetic if not sys.argv[1].isalpha(): print("Usage: ./vigenere keyword") sys.exit(1) # Ask the user to input plaintext text = get_string("plaintext: ") # Set numeric value of each keyword letter # Adjust the default number given by ASCII table # Once done a = 0, b = 1, c = 2, etc. # Uppercase letters will have same value as lc key = [] for i in range(len(sys.argv[1])): if sys.argv[1][i].islower(): key.append(ord(sys.argv[1][i]) - ord('a')) elif sys.argv[1][i].isupper(): key.append(ord(sys.argv[1][i]) - ord('A')) # Shift each alphabetic character in the plaintext cipher = [] key_counter = 0 for i in range(len(text)): if text[i].isalpha(): cipher.append(shift(text[i], key[key_counter])) key_counter += 1 if key_counter == len(sys.argv[1]): key_counter = 0 else: cipher.append(text[i]) # Join the elements of the cipher list into a str cipher_str = "".join(cipher) # Print out the ciphertext where key has been applied print("ciphertext: ", cipher_str) # Apply key to each alphabetic value in the ciphertext array def shift(text, key): # Check if the values are alphabetic # If the values are alphabetic, apply the key cipher = "" # Test if, once key applied, character is lowercase and would exceed z on ASCII # If so, subtract 26 (# of chars in alphabet to functionally loop around) if text.islower() and (ord(text) + key) > ord('z'): cipher = cipher + chr(ord(text) + key - 26) # Test if, once key applied, character is uppercase and would exceed Z on ASCII # If so, subtract 26 (# of chars in alphabet to functionally loop around) elif text.isupper() and (ord(text) + key) > ord('Z'): cipher = cipher + (chr(ord(text) + key - 26)) # If we don't need to deal with those situations # simply apply the key else: cipher = cipher + (chr(ord(text) + key)) return cipher if __name__ == "__main__": main()
true
eb6b446a8af08b0593c2f8c63511193d0355285b
eMintyBoy/pyLabs
/Tanya/LR5/lr5_zad1.py
841
4.1875
4
# Дан одномерный массив, состоящий из N вещественных элементов. Ввести массив с клавиатуры. Найти и вывести минимальный по модулю элемент. Вывести массив на экран в обратном порядке. list = [] N = int(input("Введите количество элементов списка: ")) print("Введите элементы списка: ") for i in range(N): a = int(input()) list.append(a) abs_min = abs(list[0]) for i in range(len(list)): if abs(list[i]) < abs_min: abs_min = abs(list[i+1]) print("Минимальный по модулю элемент списка: ", abs_min) list.reverse() print("Список в обратном порядке", list) input()
false
ce6a09f9e1b13bc8456bb3410a58aa051e553b6d
JordanKeller/data_structures_and_algorithms_python
/climbing_stairs.py
489
4.21875
4
def climbing_stairs(n): """Input a positive integer n. Climb n steps, taking either a single stair or two stairs with each step. Output the distinct ways to climb to the top of the stairs.""" a = 1 b = 2 if n == 1: return a if n == 2: return b # n >= 3 for i in range(n - 2): c = a + b a = b b = c return b # O(n) complexity. The Fibonacci sequence in disguise, since # the count C(n) satisfies the Fibonacci recursion formula: # F(n) = F(n - 1) + F(n - 2).
true
bbdc9a562338830d393ffaa290329b92f730b274
manimaran1997/Python-Basics
/ch_08_OOP/Projects/ch_04_Inheritance/ex_inheritance.py
2,861
4.125
4
# coding: utf-8 # In[42]: class Employee: employeeCounter = 0; def __init__(self,firstName,lastName): self.firstName = firstName self.lastName = lastName Employee.employeeCounter += 1 print(" hello i employee") def displayEmployeeName(self): print(self.firstName + " " + self.lastName) def displayHello(self): print("hello from Employee class") # In[3]: emp = Employee("ahmed","khalifa") # In[4]: print(Employee.employeeCounter) # In[5]: emp.displayEmployeeName() # # ex_01.Inheritance # In[6]: class Developer(Employee): pass # # 1.1 take care with constructor parameters of parent # In[7]: dev = Developer() # In[8]: dev = Developer("ahmed","khalifa") # # 1.2 working with class variable in Inheritance # In[9]: print(Employee.employeeCounter) # In[10]: print(Developer.employeeCounter) # In[11]: Developer.employeeCounter = 10 # In[12]: print(Developer.employeeCounter) # In[13]: print(Employee.employeeCounter) # # 1.3 working with instance variable in Inheritance # In[14]: print(dev.firstName) # # 1.4 working with Methods in Inheritance # In[15]: dev.displayEmployeeName() # # ex_02.Inheritance # # In[43]: class SoftwareEngineer(Employee): employeeCounter = 0 def __init__(self, fullName,department): self.fullName = fullName self.department = department SoftwareEngineer.employeeCounter += 1 print(" i am software engineer ") def displaySoftwareEngName(self): print(self.fullName + " worked at " + self.department ) # # 2.1 take care with constructor parameters # In[44]: sw = SoftwareEngineer("ahmed khalifa","web") # In[18]: print(SoftwareEngineer.employeeCounter) # In[19]: print(Employee.employeeCounter) # In[20]: emp3 = Employee("a","z") # In[21]: print(SoftwareEngineer.employeeCounter) # In[22]: print(Employee.employeeCounter) # In[23]: print(Developer.employeeCounter) # In[24]: dev2 = Developer("zxc" , "asd") # In[25]: print(Employee.employeeCounter) print(Developer.employeeCounter) print(SoftwareEngineer.employeeCounter) # # 2.3 working with instance variable in Inheritance # In[31]: print(sw.fullName) # In[32]: print(sw.firstName) # # 2.4 working with Methods in Inheritance # In[33]: sw.displaySoftwareEngName() # In[34]: sw.displayEmployeeName() # In[45]: sw.displayHello() # # ex_03_Inheritance # In[73]: class Desinger(Employee): def __init__(self,age,firstName,department,lastName): self.age = age self.firstName = firstName self.department = department self.lastName = lastName print(" hello i designer") # In[75]: d = Desinger(25,'lala','photoshop','nana') # In[76]: d.displayEmployeeName() # In[ ]:
true
1f2aecc0de33c798ece74a255b1eb8c10b6e2909
manimaran1997/Python-Basics
/ch_07_Data Structures in Python/ch_02_Sequence Types/ch_01_List/Project/01_Basics Of List/pythonList.py
1,658
4.1875
4
# coding: utf-8 # # 1.Create List # In[1]: #1.1 by brackets # In[2]: list1 = [1,2,3,4] # In[3]: print(list1) # In[4]: list2 = [1,2.5,3+5j,"ahmed"] # In[5]: print(list2) # In[6]: #1.2 By Constructor # In[7]: list3 = list((1,2,3,"hello world")) # In[8]: print(list3) # # 2.add Item # In[10]: list4 = [1,2,3,5] # In[11]: #1.add new item in last position # In[12]: list4.append(6) # In[13]: print(list4) # In[14]: #2.add new item in index position # In[15]: list4.insert(3,4) # In[16]: print(list4) # In[17]: #3.add iterable # In[18]: list5 = [7,8,9,10] # In[19]: list4.extend(list5) # In[20]: print(list4) # # 3.remove item # In[21]: #3.1 remove first item which match this value # In[22]: list6 = [ 1,2,3,4,1,2,3,4] # In[23]: list6.remove(1) # In[24]: print(list6) # In[25]: #3.2 remove item in certain index # In[26]: list6.pop(3) # In[27]: print(list6) # # 4.information and access # In[ ]: #1.access # In[28]: x = list6[0] # In[29]: y = list6[1] # In[30]: z = x + y # In[31]: print(z) # In[32]: #2.update # In[33]: list6[2] = 100 # In[34]: print(list6) # In[37]: #3.write in index out of range # In[36]: list6[6] = 1000 # In[38]: #4.get size or length of the list # In[39]: print(len(list6)) # In[40]: #5. number of copies of this value # In[42]: list6.count(3) # In[ ]: # # General Functions # In[43]: listWithDifferentTypes = [1,2,3,4,5,"ahmed","khalifa","zzz"] # In[44]: listOfString = ["ahmed","khalifa","zzz"] # In[45]: listOfNumber = [1,2,3,4,5] # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]:
false
c380edaae8661d21363c2ea2fe90f59d3879306c
efitzpatrick/Tkinter
/firstRealExample.py
2,121
4.375
4
# www.tkdocs.com/tutorial/firstexample.html #tells python that we need the modlues tkinter and ttk # tkinter is the standard binding to Tk (what is a binding?) # ttk is Python's binding to the newer themed widgets that were added to 8.5 from tkinter import * from tkinter import ttk #calculate procedure def calculate(*args): try: #feet is the text variables value = float(feet.get()) meters.set ((0.3048 * value * 10000.0 + 0.5)/10000.0) except ValueError: pass root = Tk() root.title("Feet to Meters") # gives window title feet to meters #creates frame widget mainframe = ttk.Frame(root, padding= "3 3 12 12") mainframe.grid (column= 0, row = 0, sticky = (N, W, E, S)) # tells tkinker that if the main window is resized, the frame should expand to take up the extra space mainframe.columnconfigure (0, weight = 1) mainframe.rowconfigure(0, weight = 1) #create three widgets in program: entry to feet, a label, and the button #do two things for a widget: #1. create widget 2. put it on the screen #all 3 widgets are children of content window # the .grid parts places them in the screen #sticky option says how to line up in cell feet = StringVar() meters = StringVar() feet_entry = ttk.Entry(mainframe,width = 7, textvariable = feet) feet_entry.grid (column = 2, row =1, sticky = (W, E)) ttk.Label(mainframe, textvariable = meters).grid (column = 2, row=2, stick = (W, E)) ttk.Button(mainframe, text = "Calculate", command = calculate).grid(column=3, row = 3, sticky = W) ttk.Label(mainframe, text = 'feet').grid (column = 3, row =1, sticky = W) ttk.Label(mainframe, text = "is equivalent to").grid(column = 1, row = 2, sticky = E) ttk.Label(mainframe, text = "meters"). grid(column = 3, row = 2, sticky = W) #finishing touches #this line walks through all of the widgets that are children and add a bit of padding for child in mainframe.winfo_children(): child.grid_configure(padx=5, pady=5) # cursor starts in feet intry feet_entry.focus() #when enter button is presed, it calls calculate root.bind("<Return>", calculate) #tells tk to enter event loop which makes everthing run root.mainloop()
true
f1d9667058f1fc7d1dfdf70c4bf7dad6bc195bf7
ManSleen/Graphs
/projects/ancestor/ancestor.py
2,980
4.15625
4
from collections import deque class Graph: """Represent a graph as a dictionary of vertices mapping labels to edges.""" def __init__(self): self.vertices = {} self.visited = set() def __repr__(self): for vertex in self.vertices: return f"{vertex}" def add_vertex(self, vertex_id): self.vertices[vertex_id] = set() def add_edge(self, v1, v2): if v1 in self.vertices and v2 in self.vertices: self.vertices[v1].add(v2) else: raise IndexError("That vertex does not exist!") def get_neighbors(self, vertex_id): return self.vertices[vertex_id] def dfs(self, starting_vertex, destination_vertex): """ Return a list containing a path from starting_vertex to destination_vertex in depth-first order. """ # Create an empty stack and push A PATH TO the starting vertex ID stack = deque() stack.append([starting_vertex]) # Create a Set to store visited vertices visited = set() # While the stack is not empty: while len(stack) > 0: # Pop the first PATH current_path = stack.pop() # print("current path: ", current_path) # Grab the last vertex from the PATH last_vertex = current_path[-1] # If that vertex has not been visited... if last_vertex not in visited: # Check if it's the target if last_vertex == destination_vertex: return current_path # If so, return path # Mark it as visited visited.add(last_vertex) # Then add A PATH TO its neighbors to the top of the stack for neighbor in self.get_neighbors(last_vertex): new_path = [*current_path, neighbor] stack.append(new_path) # Copy the path # Append the neighbor to the back def earliest_ancestor(ancestors, starting_node): g = Graph() paths = [] for ancestor in ancestors: (person1, person2) = (ancestor[0], ancestor[1]) g.add_vertex(person1) g.add_vertex(person2) for pair in ancestors: g.add_edge(pair[0], pair[1]) for vertex in g.vertices: if g.dfs(vertex, starting_node) is not None: paths.append(g.dfs(vertex, starting_node)) all_paths = sorted(paths, key=len, reverse=True) lowest = all_paths[0][0] for x in all_paths: if len(x) == len(all_paths[0]): if x[0] < lowest: lowest = x[0] if lowest == starting_node: return -1 else: return lowest test_ancestors = [(1, 3), (2, 3), (3, 6), (5, 6), (5, 7), (4, 5), (4, 8), (8, 9), (11, 8), (10, 1), (14, 10), (15, 4), (16, 15), (12, 10), (17, 15)] print(earliest_ancestor(test_ancestors, 3))
true
6635b9b2744114746ca1e5992162291bb8b9b946
sanjit961/Python-Code
/python/p_20_logical_operator.py
671
4.34375
4
#Logical Operator in Python: #If applicant has high income AND good credit #then he is eligible for loan # Logical and operator ----> both condition should be true # Logical or operator ----> at least one condition should be true. # Logica not operator ----> it converses the value True ---> False, False ---> True #Program: Logical AND Operator has_high_income = True has_good_credit = True if has_high_income and has_good_credit: print("Eligible for loan :)") #Prangram: Logical or operator has_good_credit = False has_high_income = True if has_good_credit or has_high_income: print("You are Eligible for loan buddy...!!! Enjoy :)")
true
0ac6446ca514c2308ac7db5a1db3f8ca268d44c6
sanjit961/Python-Code
/python/p_13.Arithmetic_Operator.py
647
4.6875
5
#Arithmetic Operator in Python: print(10 - 3) #Subtraction print(10 + 4) #Addition print( 10 / 5) #Division print( 10 // 5) #This prints the Quotient with interger value only print( 10 % 3) #This % (Modulo Operator) prints the remainder print(10 * 5) #Mutltiplication operator * ("Asterisk") print(10 ** 5) #Exponent Operator --> ** ----> Power 5 --> Square print(2 ** 3) #Augmented Assignment Operator: x = 10 x = x + 3 print(x) #Similarly we can also write this as: a = 5 a += 3 #Increment Operator print(a) #Augmented derement operator: b = 10 b -= 3 #Decrement Operator print(b)
true
f4c66c7312983e0e669251890946b7d68c65f4fb
MrCQuinn/Homework-2014-15
/CIS_211_CS_II/GUI turn in/flipper.py
1,146
4.40625
4
#Flippin' Cards program #By Charlie Quinn from tkinter import * from random import randint from CardLabel import * side = ["back","front","blank"] n = 0 a = 2 def flip(): """ Function that runs when "Flip" button is pressed. a is a value that starts at 0 and goes to 8 before going back to 0 w and n are both dependent upon a w starts at 1, repeats at 1 three times then goes to 2, repeats three times, and 3 three times w is used to so that each card knows what side to display w is derived by using integer division, dividing a by 3 n has a pattern of 0,1,2,0,1,2,... in order to alternate between cards every click """ global a, n, card a = (a + 1) % 9 w = a // 3 n = a % 3 #print(a,n,w) card[n].display(side[w], randint(0,51)) root = Tk() CardLabel.load_images() card = [] for i in range(3): card.append(CardLabel(root)) card[i].grid(row = 0, column = i) root.rowconfigure(0, minsize = 115) root.columnconfigure(0, minsize=85) button = Button(root, text = "Flip", command =flip) button.grid(row=1,column=1, pady =10) if __name__ == "__main__": root.mainloop()
true
c06e676609489425c5f00e15778a2acc831e37cf
Dvshah13/Machine-and-Deep-Learning-Code-Notes
/data_munging_basics-categorical.py
1,701
4.28125
4
## You'll be working often with categorical data. A plus point is the values are Booleans, they can be seen as the presence or absence of a feature or on the other side the probability of a feature having an exhibit (has displayed, has not displayed). Since many ML algos don't allow the input to be categorical, boolean features are often used to encode categorical features as numerical values. ## This process maps a feature with each level of the categorical feature. On;y one binary feature reveals the presence of the categorical feature, the others remain 0. This operation is called dummy coding. import pandas as pd categorical_features = pd.Series(['sunny', 'rainy', 'cloudy', 'snowy']) mapping = pd.get_dummies(categorical_features) print mapping # this output is a DataFrame that contains the categorical levels as column lables and the respective binary features along the column. ## Here you can map a categorical value to a list of numerical ones print mapping['sunny'] print mapping['cloudy'] ## you can use Scikit learn to do the same operation although the process is a bit more complex as you must convert text to categorical indices but the result is the same ## SK lean example from sklearn.preprocessing import OneHotEncoder from sklearn.preprocessing import LabelEncoder le = LabelEncoder() ohe = OneHotEncoder() levels = ['sunny', 'rainy', 'cloudy', 'snowy'] # your features fit_levs = le.fit_transform(levels) # maps the text to 0-to-N integer number ohe.fit([[fit_levs[0]], [fit_levs[1]], [fit_levs[2]], [fit_levs[3]]]) # mapped to four binary variables print ohe.transform([le.transform(['sunny'])]).toarray() print ohe.transform([le.transform(['cloudy'])]).toarray()
true
b4a49e0d08e0e8e0710f3014e2ccb28b6d9017e9
stevenfisher22/python-exercises
/Homework 14 Nov 2018/guess-a-number.py
1,645
4.125
4
# STEP 1: GUESS A NUMBER # secret_number = 2 # answer = 0 # while answer != secret_number: # answer = int(input('I\'m thinking of a number between 1 and 10. What\'s the number? ')) # if answer != secret_number: # print('Nope, try again ') # print('You win!') # STEP 2: GIVE A HIGH-LOW HINT # secret_number = 2 # answer = 0 # while answer != secret_number: # answer = int(input('I\'m thinking of a number between 1 and 10. What\'s the number? ')) # if answer < secret_number: # print('Too low!') # if answer > secret_number: # print('Too high!') # print("You Win!") # STEP 3: RANDOMLY GENERATED SECRET NUMBER # import random # secret_number = random.randint(1, 10) # answer = 0 # while answer != secret_number: # answer = int(input('I\'m thinking of a number between 1 and 10. What\'s the number? ')) # if answer < secret_number: # print('Too low!') # if answer > secret_number: # print('Too high!') # print("You Win!") # STEP 4: LIMIT NUMBER OF GUESSES # import random # secret_number = random.randint(1, 10) # answer = 0 # guesses_taken = 0 # while answer != secret_number: # answer = int(input('I\'m thinking of a number between 1 and 10. What\'s the number? ')) # if answer < secret_number: # print('Too low!') # guesses_taken += 1 # if answer > secret_number: # print('Too high!') # guesses_taken += 1 # if guesses_taken == 5: # break # if answer == secret_number: # print('You Win!') # if answer != secret_number: # print('Sorry. You ran out of guesses. The number was %d.' % (secret_number))
true
60d45067426464abb0f20b20a665dc3d6741b1a5
Mohan-Zhang-u/From_UofT
/csc148/pycharm/csc148/labs/lab5/nested.py
2,226
4.15625
4
def nested_max(obj): """Return the maximum item stored in <obj>. You may assume all the items are positive, and calling nested_max on an empty list returns 0. @type obj: int | list @rtype: int >>> nested_max(17) 17 >>> nested_max([1, 2, [1, 2, [3], 4, 5], 4]) 5 >>> nested_max([4, 99, [12, 2, [11], 4, 5], 1]) 99 """ if isinstance(obj, int): return obj else: a = 0 for i in obj: b = nested_max(i) if a < b: a = b return a def length(obj): """Return the length of <obj>. The *length* of a nested list is defined as: 1. 0, if <obj> is a number. 2. The maximum of len(obj) and the lengths of the nested lists contained in <obj>, if <obj> is a list. @type obj: int | list @rtype: int >>> length(17) 0 >>> length([1, 2, [1, 2], 4]) 4 >>> length([1, 2, [1, 2, [3], 4, 5], 4]) 5 """ if isinstance(obj, int): return 0 else: a = len(obj) b = 0 for i in obj: c = length(i) if b < c: b = c if a > b: return a else: return b def add_all(lst): """ @param obj: @return: >>> add_all(3) 3 >>> add_all([3, [1, 2]]) 6 >>> add_all([1, 2, [1, 2], 4]) 10 """ if isinstance(lst, int): return lst else: s = 0 for i in lst: s = s + add_all(i) return s def equal(obj1, obj2): """Return whether two nested lists are equal, i.e., have the same value. Note: order matters. @type obj1: int | list @type obj2: int | list @rtype: bool >>> equal(17, [1, 2, 3]) False >>> equal([1, 2, [1, 2], 4], [1, 2, [1, 2], 4]) True >>> equal([1, 2, [1, 2], 4], [4, 2, [2, 1], 3]) False """ if isinstance(obj1, int) or isinstance(obj2, int): return obj1 == obj2 else: if len(obj1) != len(obj2): return False else: for i in range(len(obj1)): if equal(obj1[i], obj2[i]) is False: return False return True
true
3f0b740dc0a0d881af1346b6064f498e84f5f984
servesh-chaturvedi/FunGames
/Rock, Paper, Scissors/Rock Paper Scissors.py
1,003
4.1875
4
import random import time options={1:"rock", 2:"paper", 3: "scissors"} #build list try: again="y" while(again == "y"): player=int(input("Enter:\n 1 for Rock\n 2 for Paper\n 3 for Scissors\n")) #take player input print("You entered:", options[player]) comp=random.randint (1, 3) #take computer input print("Computer picked:", options[comp]) score=player-comp if score in (-2,1): print("You win! :)") elif score in (-1,2): print("Computer wins :(") else: print("Tie") again=input("Do you want to play again?? \n Press y to continue \n Any other key to exit \n") if again != "y": print("Thanks for playing!!!") time.sleep(1) except: #input validation print("Input invalid, program will exit") time.sleep(1)
true
223608bba840a65ed2c953ede96c797f4ad9cd63
SiddhartLapsiwala/Software_Testing_Assign2
/TestTriangle.py
1,990
4.3125
4
# -*- coding: utf-8 -*- """ Updated Jan 21, 2018 The primary goal of this file is to demonstrate a simple unittest implementation @author: jrr @author: rk """ import unittest from Triangle import classifyTriangle # This code implements the unit test functionality # https://docs.python.org/3/library/unittest.html has a nice description of the framework class TestTriangles(unittest.TestCase): # define multiple sets of tests as functions with names that begin """Positive""" def testEquilateralTriangles(self): """ test for Equilateral triangle """ self.assertEqual(classifyTriangle(3,3,3),'Equilateral','3,3,3 should be equilateral') def testIsoscelesTriangles(self): """ test for Isosceles triangle """ self.assertEqual(classifyTriangle(3, 3, 5), 'Isosceles', '3,3,5 should be Isoceles') def testScaleneTriangles(self): """ test for Scalene triangle """ self.assertEqual(classifyTriangle(3, 4, 6), 'Scalene', '3,4,6 should be Scalene') def testRightTriangleA(self): """ test for Right triangle """ self.assertEqual(classifyTriangle(3,4,5),'Right','3,4,5 is a Right triangle') def testRightTriangleB(self): """ test for Right triangle """ self.assertEqual(classifyTriangle(5,3,4),'Right','5,3,4 is a Right triangle') """Negative""" def testNotTriangle(self): """ test for side does not form triangle """ self.assertEqual(classifyTriangle(2,3,9),'NotATriangle','2,3,9 is a not triangle') def testNegativeSides(self): """ test for negative side """ self.assertEqual(classifyTriangle(-2,-3,-9),'InvalidInput','-2,-3,-9 is a not valid input') def testMorethan200(self): """ test for side more than 200 """ self.assertEqual(classifyTriangle(201, 301, 901), 'InvalidInput', '201,301,901 is a not valid input as more than 200') if __name__ == '__main__': print('Running unit tests') unittest.main()
true
0bf34cfec95bf6ab35d4c1b80ec42ea73dfb61ef
RiikkaKokko/JAMK_ohjelmoinnin_perusteet
/examples/13-collections/set.py
1,047
4.28125
4
# declare set of names and print nameset = {"Joe", "Sally", "Liam", "Robert", "Emma", "Isabella"} print("Contents of nameset is: ", nameset) # print contents of the set in for loop for name in nameset: print(name) # check length of the set print("Length of the set is: ", len(nameset)) # check if certain item is in the set name = "Sally" print(name + " is in set: ", name in nameset) # items in set cannot be modified but can be added and removed # use add function to add new item nameset.add("Bella") print("Contents of nameset after add is: ", nameset) # update function allows to add multiple items to the set nameset.update({"Harry", "Elisa", "Pocahontas"}) print("Contents of nameset after update is: ", nameset) # items can be removed with remove or discard function # remove function will raise an error if item is not in a set # discard function works the same as remove but will not raise an error # if item is not found nameset.remove("Liam") #nameset.discard("Liam") print("Contents of nameset after remove is: ", nameset)
true
25c16ff3deb8922b8c80f1cd92e067134e627c3f
tyerq/checkio
/most-wanted-letter.py
975
4.21875
4
def checkio(text): text = text.lower() max_freq = 0 max_letter = '' for letter in text: if letter.isalpha(): num = text.count(letter) if num > max_freq or num == max_freq and letter < max_letter: max_freq = num max_letter = letter print(max_letter) return max_letter if __name__ == '__main__': # These "asserts" using only for self-checking and not necessary for auto-testing assert checkio(u"Hello World!") == "l", "Hello test" assert checkio(u"How do you do?") == "o", "O is most wanted" assert checkio(u"One") == "e", "All letter only once." assert checkio(u"Oops!") == "o", "Don't forget about lower case." assert checkio(u"AAaooo!!!!") == "a", "Only letters." assert checkio(u"abe") == "a", "The First." print("Start the long test") assert checkio(u"a" * 9000 + u"b" * 1000) == "a", "Long." print("The local tests are done.")
true
8336c2ce6d87cc7718a3b2af83d3bba7d7ab82b5
KhadarRashid/2905-60-Lab5
/sql_db.py
2,844
4.28125
4
import sqlite3 db = 'records_db.sqlite' def main(): # calling functions in the order they should execute menu() drop_table() create_table() data() def menu(): # Creating a super simple menu choice = input('\nPlease choose one of the following here \n 1 to add \n 2 to delete\n 3 to show all \n 4 to update \nAny other key to exit: ') if choice == '1': create_new_record() elif choice == '2': delete_record() elif choice == '3': display_data() elif choice == '4': update_record() else: SystemExit() def drop_table(): # Clearing the table so ots clean with sqlite3.connect(db) as conn: conn.execute('DROP table if exists records') conn.close() def create_table(): # creating a anew table with 3 columns with sqlite3.connect(db) as conn: conn.execute('create table if not exists records (name text, country text, catches int)') conn.close() def data(): # Inserting some data to work with with sqlite3.connect(db) as conn: conn.execute('INSERT INTO records values ("James", "Finland", 98)') conn.execute('INSERT INTO records values ("Ian", "Canada", 99)') conn.execute('INSERT INTO records values ("Aaron", "Canada", 98)') conn.execute('INSERT INTO records values ("Chad", "USA", 99)') conn.close() def display_data(): # Displaying all the data in the table currently conn = sqlite3.connect(db) results = conn.execute('SELECT * FROM records') print('All Records: ') for row in results: print(row) conn.close() menu() def update_record(): # Getting the info for updating the records records name = input('Please enter the record name you wish to update: ') catches = int(input('Please enter the new number of catches: ')) with sqlite3.connect(db) as conn: conn.execute('UPDATE records SET catches = ? WHERE name = ?', (catches, name)) conn.close() menu() def create_new_record(): # Getting the data to make a brand new record name = input('Please enter the new name for the record: ') country = input('Please enter their country: ') catches = int(input('Please enter the number of catches: ')) # Inserting them into the database with an INSERT statement with sqlite3.connect(db) as conn: conn.execute(f'INSERT INTO records VALUES(?, ?, ?)', (name, country, catches)) conn.close() menu() def delete_record(): # Getting the name of the record to delete delete_name = input('Please enter the name: ') # Deleting from the database with the DELETE statement with sqlite3.connect(db) as conn: conn.execute('DELETE from records WHERE name = ?' , (delete_name,)) conn.close() menu() main()
true
424d1d4a40d34097b15d71f502fdf5979d95d6c7
jamesmmatt/Projects
/Python/FizzBuzz.py
570
4.375
4
""" Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz" """ def fizzBuz(lastNumber): numRange = range(1, (lastNumber + 1)) for num in numRange: if (num%3 == 0 and (num%5 == 0)): num = "FizzBuzz" elif (num%3 == 0): num = "Fizz" elif (num%5 == 0): num = "Buzz" print(num) print("Choose the last number: ") fizzLastNumber = int(input()) fizzBuz(fizzLastNumber)
true
8594a9a864bcf64953d418b4220eb6f98c5a1070
francisco-igor/ifpi-ads-algoritmos2020
/G - Fabio 2a e 2b - Condicionais/G - Fabio 2a - Condicionais/G_Fabio_2a_q18_operações.py
1,190
4.21875
4
'''Leia dois valores e uma das seguintes operações a serem executadas (codificadas da seguinte forma: 1 – Adição, 2 – Subtração, 3 – Multiplicação e 4 – Divisão). Calcule e escreva o resultado dessa operação sobre os dois valores lidos.''' # ENTRADA def main(): valor1 = int(input('Digite um valor: ')) valor2 = int(input('Digite outro valor: ')) valor3 = int(input('Digite um número entre 1 e 4: ')) operação(valor1, valor2, valor3) # PROCESSAMENTO def operação(valor1, valor2, valor3): if 1 > valor3 or valor3 > 4: print('O número da operação não é válido.') elif valor3 == 1: soma = valor1 + valor2 print(f'O resultado da soma dos valores é {soma}.') elif valor3 == 2: subtração = valor1 - valor2 print(f'O resultado da subtração dos valores é {subtração}.') elif valor3 == 3: multiplicação = valor1 * valor2 print(f'O resultado da multiplicação dos valores é {multiplicação}.') elif valor3 == 4: divisão = valor1 / valor2 print(f'O resultado da divisão dos valores é {divisão}.') # SAÍDA main()
false
f8cf1b25f2f1d6d6567057734546c79fc2b7bf94
francisco-igor/ifpi-ads-algoritmos2020
/G - Fabio 2a e 2b - Condicionais/G - Fabio 2a - Condicionais/G_Fabio_2a_q29_quadrado_perfeito.py
823
4.15625
4
'''Um número é um quadrado perfeito quando a raiz quadrada do número é igual à soma das dezenas formadas pelos seus dois primeiros e dois últimos dígitos. Exemplo: √9801 = 99 = 98 + 01. O número 9801 é um quadrado perfeito. Escreva um algoritmo que leia um número de 4 dígitos e verifique se ele é um quadrado perfeito.''' # ENTRADA def main(): num = int(input('Número a ser verificado: ')) quad_perf(num) # PROCESSAMENTO def quad_perf(num): dig12 = num // 100 dig34 = num % 100 r = num ** (1/2) if r % 1 == 0: if dig12 + dig34 == r: print('O número é um quadrado perfeito.') else: print('O número não é um quadrado perfeito.') else: print('O número não é um quadrado perfeito.') # SAÍDA main()
false
c8d583db90939476c5a02e41b49f0d086400f4c7
vivia618/Code-practice
/Reverse words.py
593
4.3125
4
# Write a function that reverses all the words in a sentence that start with a particular letter. sentence = input("Which sentence you want to reverse? : ").lower() letter = input("Which letter you want to reverse? : ").lower() word_in_sentence = sentence.split(" ") new_sentence = [] def special_reverse(x, y): x = word_in_sentence y = letter for i in word_in_sentence: if i[0] == y: i = i[::-1] new_sentence.append(i) else: new_sentence.append(i) return ' '.join(new_sentence) print(special_reverse(sentence, letter))
true
c759b9b0b77b38d773482210b6b86685f67b224d
TejshreeLavatre/CrackingTheCodingInterview
/Data Structures/Chpt1- Arrays and Strings/3-URLify.py
871
4.3125
4
""" Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end to hold the additional characters, and that you are given the "true" length of the string. (Note: If implementing in Java, please use a character array so that you can perform this operation in place.) EXAMPLE Input: "Mr 3ohn Smith 13 Output: "Mr%203ohn%20Smith" """ def replace_spaces(s, length): s = list(s) count = 0 for i in range(length): if s[i] == " ": count += 1 index = length + count*2 for i in range(length-1, -1, -1): if s[i] == " ": s[index-1] = "0" s[index-2] = "2" s[index-3] = "%" index -= 3 else: s[index-1] = s[i] index -= 1 return print("".join(s)) replace_spaces("Mr 3ohn Smith ", 13)
true
d56969b05ab1673ebae52b003332e6f53e4003dd
CaosMx/100-Python-Exercises
/011.py
606
4.28125
4
""" Create a script that generates and prints a list of numbers from 1 to 20. Please do not create the list manually. """ x = range(1,21) print(list(x)) # Create a script that generates and prints a list of numbers from 1 to 20. Please do not create the list manually. # 1 Punto # El truco es castear el resultado com lista """ range() is a Python built-in function that generates a range of integers. However, range() creates a Python range object. To get a real list object, you need to use the list() function to convert the range object into a list object. Syntax range(start, stop, step) """
true
bee12643fb9c7979b52d053d7c3ac2946c26d765
NiraliSupe/Sample-Python-Programs
/Sqlite3/Database.py
1,660
4.8125
5
''' Program created to learn sqlite3 ''' import sqlite3 class Database: def __init__(self): self.conn = sqlite3.connect('UserInfo.db') self.cur = self.conn.cursor() print("success") def createTable(self): table_exists = 'SELECT name FROM sqlite_master WHERE type="table" AND name="USERS"' sql = 'CREATE TABLE USERS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, CITY TEXT NOT NULL)' if not self.cur.execute(table_exists).fetchone(): self.cur.execute(sql) self.conn.commit() def insertRecord(self, name, city): sql = 'INSERT INTO USERS (NAME, CITY) VALUES (?,?)' self.cur.execute(sql,(name, city)) self.conn.commit() def getRecord(self): sql = 'SELECT * FROM USERS' for row in self.cur.execute(sql): print (row) self.conn.commit() def updateRecord(self, name, id): sql = 'UPDATE USERS SET NAME = ? WHERE ID = ?' self.cur.execute(sql,(name, id)) self.conn.commit() ''' The SQLite ALTER TABLE statement is used to add, modify, or drop/delete columns in a table. Also used to rename a table. Doesn't support AUTOINCREMENT''' def deleteRecord(self, name): sql = 'DELETE FROM USERS WHERE NAME = ?' # sqlGetlMaxId = 'SELECT MAX(ID) FROM USERS' # sqlResetId = 'ALTER TABLE USERS AUTOINCREMENT = ?' self.cur.execute(sql, (name,)) # for maxId in self.cur.execute(sqlGetlMaxId): # self.cur.execute(sqlResetId, (maxId[0],)) self.conn.commit() def connClose(self): conn.close() database = Database() database.createTable() database.insertRecord("Nirali", "NY") database.getRecord() database.updateRecord("KP", 2) database.deleteRecord("Nirali") database.connClose()
true
e54b29af4b636fa822a4915dbe5180cffb6dc12b
aabeshov/PP2
/String3.py
305
4.28125
4
b = "Hello, World!" print(b[2:5]) # show symbold on the 2th 3th 4th positions a = "Hello, World!" print(b[:5]) # show symbols til the 5th position b = "Hello, World!" print(b[2:]) # show symbold from 2th position til the end b = "Hello, World!" # Its the same but it starts from the ending print(b[-5:-2])
true
64c2a87d7e11c7b5a097feb609cb293626690133
rojcewiczj/Javascript-Python-practice
/Python-Practice/acode_break.py
597
4.21875
4
code = "asoidjfiej;akfgnrgjwalkaslkdjhfaasdfj;asdkjf;gforwarddhjfajkhfthendfijaifgturndksoejkgorightsdfupsdfasdfgg" words= ["walk", "forward", "then", "turn", "right"] # function for finding a message consisting of given words hidden in a jumbled string def find_message(code, words): inc = 0 dictionary = {} print(code) while inc < len(code): for word in words: if code[inc : inc + len(word)] == word : dictionary[code[inc : inc + len(word)]] = [inc, inc + len(word)] inc +=1 print(dictionary) find_message(code, words)
false
3664d30966db44495bf24bc707f34715795552b6
rolandoquiroz/holbertonschool-higher_level_programming
/0x0B-python-input_output/4-append_write.py
491
4.46875
4
#!/usr/bin/python3 """ This module contains a function that appends a string at the end of a text file (UTF8) and returns the number of characters added. """ def append_write(filename="", text=""): """ append_write- Appends a string at the end of a text file (UTF8). Args: filename(str): filename text(str): text Returns: The number of characters added. """ with open(filename, 'a+', encoding='utf-8') as f: return f.write(text)
true
bf9d7fee49b488567c0e8319f138487c0455116c
eujonas/Python
/Aula 03/questao09.py
936
4.28125
4
"""9 - Gere as seguintes listas utilizando for e o metodo range(): Uma lista de ímpares de 10 a 12o Uma lista pares de 2 a 1000 Uma lista de multiplos de 2 em um intervalo de decrescente de 100 até 40 Uma lista de primos de 44 até 99 OBS: Pesquise pelo método append() na documentação """ #IMPARES impares = [] for i in range(10, 20): if i % 2 != 0: impares.append(i) print("IMPARES:",impares) #PARES pares = [] for i in range(2, 15): if i % 2 == 0: pares.append(i) print("\nPARES:",pares) #MULTIPLOS multiplos = [] for i in range(1,60): if i % 7 == 0: multiplos.append(i) multiplos.reverse() #reverse é utilizado para imprimir na ordem decrescente print("\nMULTIPLOS:",multiplos) #PRIMOS primos = [] for x in range(1,25): cont=0 for y in range(1, x+1): if x % y == 0: cont += 1 if cont <= 2: primos.append(x) print("\nPRIMOS:",primos)
false
6fbff7a74b6fcfd9489b5939b089dcf5f245629d
dgellerup/laminar
/laminar/laminar_examples.py
1,574
4.25
4
import pandas as pd def single_total(iterable, odd=False): """This example function sums the data contained in a single iterable, i.e. a list, tuple, set, pd.Series, etc. Args: iterable (list, tuple, set, pd.Series, etc): Any iterable that holds data that can be added together. Returns: total (int): Sum of passed iterable. """ total = 0 for item in iterable: if odd: if item % 2 != 0: total += int(item) else: total += int(item) return total def multi_tally(pddf): """This example function sums each row of a Pandas DataFrame, then increases the total count if the sum is greater than 25. Args: pddf (:obj: pd.DataFrame): Pandas DataFrame. laminar_examples.laminar_df may be used as an example. It contains 3 columns ['Col1', 'Col2', 'Col3'], each of which contains integer values. Returns: total (int): Number of rows in pddf that summed to greater than 25. """ total = 0 for i in range(len(pddf)): if sum(pddf.iloc[i]) > 25: total += 1 return total __df = pd.DataFrame({'Col1': [1, 2, 3, 4, 5], 'Col2': [6, 7, 8, 9, 10], 'Col3': [11, 12, 13, 14, 15]}) __increasing_df = [__df*i for i in range(1, 10)] laminar_df = pd.concat(__increasing_df) laminar_df.reset_index(drop=True, inplace=True) iris = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv')
true
39d5bd7a475870006014f9f9ee2906ebe35c3271
navarr393/a-lot-of-python-projects
/6_7.py
474
4.125
4
information = {'first_name':'David', 'last_name': 'Navarro', 'age':21, 'city':'Los Angeles'} information2 = {'first_name':'Maria', 'last_name': 'Lopez', 'age':25, 'city':'Fullerton'} information3 = {'first_name':'Steph', 'last_name': 'Kun', 'age':23, 'city':'Palos Verdes'} people = [information, information2, information3] for person in people: print(person['first_name'], person['last_name'], "is", person['age'], "and lives in the city of", person['city'],)
false
4a4127a94f0b510000be3724caa6f204ac602025
leqingxue/Python-Algorithms
/Lecture01/Labs/Lab01/rec_cum_solution.py
715
4.125
4
# Write a recursive function which takes an integer and computes the cumulative sum of 0 to that integer # For example, if n=4 , return 4+3+2+1+0, which is 10. # This problem is very similar to the factorial problem presented during the introduction to recursion. # Remember, always think of what the base case will look like. # In this case, we have a base case of n =0 (Note, you could have also designed the cut off to be 1). # In this case, we have: n + (n-1) + (n-2) + .... + 0 def rec_sum(n): # Base case if n == 0: return 0 # Recursion else: return n + rec_sum(n-1) ############################################################ result = rec_sum(4) print(result) # 10
true