blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
346d3af90d21411c4265d7e232786fc4078f82fc
Tanay-Gupta/Hacktoberfest2021
/python_notes1.py
829
4.4375
4
print("hello world") #for single line comment '''for multi line comment''' #for printing a string of more than 1 line print('''Twinkle, twinkle, little star How I wonder what you are Up above the world so high Like a diamond in the sky Twinkle, twinkle little star How I wonder what you are''') a=20 b="hello" c=39.9 #here a is variable and its datatype is integer print(a) #how to print the datatype of a print(type(a)) print(type(c)) #how to print arithmetic results a=5 b=3 print ("the sum of a+b is",a+b) print ("the diff of a-b is",a-b) print ("the product of a*b is",a*b) # comparison operators a=(82<=98) print(a) # type conversion and type casting a="45" #this is a string # to convert into int a=int(a) print(type(a)) b= 34 print(type(b)) b=str(b) print(type(b))
true
f9f7e50a92722a94b0d387c61b00a216e556219d
KarlLichterVonRandoll/learning_python
/month01/code/day01-04/exercise03.py
1,842
4.1875
4
""" 录入商品单价 再录入数量 最后获取金额,计算应该找回多少钱 """ # price_unit = float(input('输入商品单价:')) # amounts = int(input('输入购买商品的数量:')) # money = int(input('输入你支付了多少钱:')) # # Change = money - amounts * price_unit # print('找回%.2f元' % Change) """ 获取分钟、小时、天 计算总秒数 """ # minutes = int(input('输入分钟:')) # hours = int(input('输入小时:')) # days = int(input('输入天数:')) # # seconds = minutes * 60 + hours * 3600 + days * 86400 # print('总共是%d秒' % seconds) """ 一斤10两 输入两,计算几斤几两 """ # weights = int(input('输入几两:')) # result1 = weights // 10 # result2 = weights % 10 # print("%d两是%d斤%d两" % (weights, result1, result2)) """ 录入距离、时间、初速度 计算加速度 x = v0 + 1/2 * a * (t^2) """ # distance = float(input('输入距离:')) # speed0 = float(input('输入初速度:')) # time = float(input('输入时间:')) # # Acceleration = (distance - speed0) * 2 / (time ** 2) # print('加速度为%.2f' % Acceleration) """ 录入四位整数 计算每位数相加的和 """ # number = int(input('输入一个四位整数:')) # number1 = number % 10 # number2 = number % 100 // 10 # number3 = number // 100 % 10 # number4 = number // 1000 # sum = number1 + number2 + number3 + number4 # # print('%d+%d+%d+%d=%d' % (number4, number3, number2, number1, sum)) # ========================================================================== # number_str = input('输入一个四位整数:') # result = 0 # for i in number_str: # result += int(i) # print(result) # sex = input('输入性别:') # if sex == "男": # print("你好,先生!") # elif sex == "女": # print("你好,女士!") # else: # print("输入有误!")
false
bbcf509fc54e792f44a9ff9dc57aea493cd7d89c
KarlLichterVonRandoll/learning_python
/month01/code/day14/exercise02.py
1,511
4.25
4
""" 创建Enemy类对象,将对象打印在控制台 克隆Enemy类对像 """ # class Enemy: # # def __init__(self, name, hp, atk, defense): # self.name = name # self.hp = hp # self.atk = atk # self.defense = defense # # def __str__(self): # return "%s 血量%d 攻击力%d 防御力%d" % (self.name, self.hp, self.atk, self.defense) # # def __repr__(self): # return 'Enemy("%s",%d,%d,%d)' % (self.name, self.hp, self.atk, self.defense) # # # enemy = Enemy("灭霸", 100, 80, 60) # print(enemy) # # str01 = repr(enemy) # print(str01) # enemy02 = eval(str01) # enemy02.name = "洛基" # print(enemy02) """ 运算符重载 """ class Vector1: def __init__(self, x): self.x = x def __str__(self): return "一唯向量的分量是 %d" % self.x def __add__(self, other): return Vector1(self.x + other) def __iadd__(self, other): self.x += other return self def __sub__(self, other): return Vector1(self.x - other) def __mul__(self, other): return Vector1(self.x * other) def __radd__(self, other): return Vector1(self.x + other) def __rsub__(self, other): return Vector1(self.x - other) def __rmul__(self, other): return Vector1(self.x * other) vec01 = Vector1(2) print(vec01) print(vec01 + 3) print(vec01 - 4) print(vec01 * 5) print() print(3 + vec01) print(4 - vec01) print(5 * vec01) vec01 += 1 print(vec01)
false
f284bdf3b3929131be1fe943b3bd5761119f4c2e
sydney0zq/opencourses
/byr-mooc-spider/week4-scrapy/yield.py
1,088
4.53125
5
#! /usr/bin/env python3 # -*- coding: utf-8 -*- """ The first time the for calls the generator object created from your function, it will run the code in your function from the beginning until it hits yield, then it'll return the first value of the loop. Then, each other call will run the loop you have written in the function one more time, and return the next value, until there is no value to return. The generator is considered empty once the function runs but does not hit yield anymore. It can be because the loop had come to an end, or because you do not satisfy an "if/else" anymore. """ def gen(n): print("outside") for i in range(8): print ("inside") yield i ** 2 for i in gen(5): print (i, " ") print ("*" * 50) def gen2(n): print("outside") for i in range(n): print ("inside") yield i ** 2 n = 3 for i in gen2(n): #n = 10 this statement does NO effect print (i) print ("*" * 50) def square(n): print ("inside") ls = [i**2 for i in range(n)] return ls for i in square(5): print(i)
true
88806f1c3ee74fe801b26a11b0f66a3c7d6c881d
Kajabukama/bootcamp-01
/shape.py
1,518
4.125
4
# super class Shape which in herits an object # the class is not implemented class Shape(object): def paint(self, canvas): pass # class canvas which in herits an object # the class is not implemented class Canvas(object): def __init__(self, width, height): self.width = width self.height = height self.data = [[' '] * width for i in range(height)] # setter method which sets row and column def setpixel(self, row, col): self.data[row][col] = '*' # getter method that will get the values of row and column def getpixel(self, row, col): return self.data[row][col] def display(self): print "\n".join(["".join(row) for row in self.data]) # the subclass Rectangle which inherits from the Shape Superclass # inheritance concept class Rectangle(Shape): def __init__(self, x, y, w, h): self.x = x self.y = y self.w = w self.h = h # a method to draw a horizontal line def hline(self, x, y, w): self.x = x self.y = y self.w = w # another method that will draw a vertical line def vline(self, x, y, h): self.x = x self.y = y self.h = h # this method calls the other three methods # and draws the respective shapes on a camnvas def paint(self, canvas): hline(self.x, self.y, self.w) hline(self.x, self.y + self.h, self.w) vline(self.x, self.y, self.h) vline(self.x + self.w, self.y, self.h)
true
157b4ad717a84f91e60fb5dc108bcab8b2a21a12
jwu424/Leetcode
/RotateArray.py
1,275
4.125
4
# Given an array, rotate the array to the right by k steps, where k is non-negative. # 1. Make sure k < len(nums). We can use slice but need extra space. # Time complexity: O(n). Space: O(n) # 2. Each time pop the last one and inset it into the beginning of the list. # Time complexity: O(n^2) # 3. Reverse the list three times. # Time complexity: O(n) class Solution: def rotate1(self, nums: List[int], k: int) -> None: """ Do not return anything, modify nums in-place instead. """ k %= len(nums) nums[:] = nums[-k:] + nums[:-k] def rotate2(self, nums: List[int], k: int) -> None: """ Do not return anything, modify nums in-place instead. """ k %= len(nums) for _ in range(k): nums.insert(0, nums.pop()) def rotate3(self, nums: List[int], k: int) -> None: """ Do not return anything, modify nums in-place instead. """ k %= len(nums) self.reverse(nums, 0, len(nums)-1) self.reverse(nums, 0, k-1) self.reverse(nums, k, len(nums)-1) def reverse(self, nums, left, right): while left < right: nums[left], nums[right] = nums[right], nums[left] left += 1 right -= 1
true
da8890ff1f941e97b8174bc6e111272b6ffa0b20
OliverMorgans/PythonPracticeFiles
/Calculator.py
756
4.25
4
#returns the sum of num1 and num 2 def add(num1, num2): return num1 + num2 def divide(num1, num2): return num1 / num2 def multiply(num1, num2): return num1 * num2 def minus (num1, num2): return num1 - num2 #*,-,/ def main(): operation = input("what do you want to do? (+-*/): ") if(operation != "+" and operation != "-" and operation != "*" and operation != "/"): #invalid operation print("You must enter a valid operation (+-*/)") else: num1 = int(input("Enter num1: ")) num2 = int(input("Enter num2: ")) if(operation == "+"): print(add(num1, num2)) elif(operation == "-"): print(minus(num1, num2)) elif(operation == "*"): print(multiply(num1, num2)) elif(operation == "/"): print(divide(num1, num2)) main()
true
261a8ec6e763de736e722338241d2cf39a34c9b0
Rggod/codewars
/Roman Numerals Decoder-6/decoder.py
1,140
4.28125
4
'''Problem: Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost digit and skipping any 0s. So 1990 is rendered "MCMXC" (1000 = M, 900 = CM, 90 = XC) and 2008 is rendered "MMVIII" (2000 = MM, 8 = VIII). The Roman numeral for 1666, "MDCLXVI", uses each letter in descending order. Example: solution('XXI') # should return 21 ''' def solution(roman): """complete the solution by transforming the roman numeral into an integer""" values = {'I' : 1 ,'V' : 5, 'X' : 10, 'L' : 50, 'C' : 100, 'D' : 500, 'M' : 1000} sum = 0 count = 0 while(count < len(roman)): cur = values.get(roman[count],' ') if count == len(roman) -1 or (cur >= values.get(roman[count+1],' ')): sum = sum + cur else: sum = sum +(values.get(roman[count+1],' ')-cur) count = count +1 count = count +1 return sum
true
a7ee00fd9f9dac5ec77d96e7b1ab8c1a1dbe1b4f
Rggod/codewars
/is alphanumerical/solution.py
592
4.15625
4
''' In this example you have to validate if a user input string is alphanumeric. The given string is not nil, so you don't have to check that. The string has the following conditions to be alphanumeric: At least one character ("" is not valid) Allowed characters are uppercase / lowercase latin letters and digits from 0 to 9 No whitespaces/underscore ''' #Solution def alphanumeric(string): for letter in string: if letter.isalpha(): continue elif letter.isdigit(): continue else: return False return True
true
9b1c1c56bdd3f47af1d3e818c85ef9601180904a
7dongyuxiaotang/python_code
/study_7_23.py
1,687
4.21875
4
# class Parent1(object): # x = 1111 # # # class Parent2(object): # pass # # # class Sub1(Parent1): # 单继承 # pass # # # class Sub2(Parent1, Parent2): # 多继承 # pass # # # print(Sub1.x) # print(Sub1.__bases__) # print(Sub2.__bases__) # ps:在python2中有经典类与新式类之分 # 新式类:继承了object类的子类,以及该子类的子类 # 经典:没有继承object类的子类,以及该子类的子类 # ps:在python3中没有继承任何类,默认继承object类 # 所以python3中所有类都是新式类 # class School: # school = '广东技术师范大学' # # def __init__(self, name, age, gender): # self.name = name # self.age = age # self.gender = gender # # # class Student(School): # # def choose_course(self): # print('%s 正在选课' % self.name) # # # class Teacher(School): # # def __init__(self, name, age, gender, salary, level): # School.__init__(self, name, age, gender) # self.salary = salary # self.level = level # # def score(self): # print('%s老师 正在给学生打分' % self.name) # class Foo: # # def __f1(self): # print('foo.f1') # # def f2(self): # print('foo.f2') # self.__f1() # # # class Bar(Foo): # # def f1(self): # print('bar.f1') # # # obj = Bar() # # obj.f2() class A: def test(self): print('from A') class B(A): def test(self): print('from B') class C(A): def test(self): print('from C') class D(B, C): pass print(D.mro()) # 类以及该类的对象访问属性都是参照该类的mro列表 # obj = D() # obj.test()
false
57813ddd83679b08db0ca6b7d29ad27d25e32252
falondarville/practicePython
/birthday_dictionary/months.py
495
4.5625
5
# In the previous exercise we saved information about famous scientists’ names and birthdays to disk. In this exercise, load that JSON file from disk, extract the months of all the birthdays, and count how many scientists have a birthday in each month. import json from collections import Counter with open("info.json", "r") as f: info = json.load(f) # print the months, which will be added to a list for each in info["birthdays"]: birthday_month = each["month"] print(birthday_month)
true
9b505fd7c9d15fedb84b90c9c8443e791d8a9e61
falondarville/practicePython
/birthday_dictionary/json_bday.py
696
4.46875
4
# In the previous exercise we created a dictionary of famous scientists’ birthdays. In this exercise, modify your program from Part 1 to load the birthday dictionary from a JSON file on disk, rather than having the dictionary defined in the program. import json with open("info.json", "r") as f: info = json.load(f) print('Welcome to the birthday dictionary. We know the birthdays of:') for each in info["birthdays"]: print(each["name"]) print('Whose birthday do you want to know?') query = str(input()) print(f'You want to know the birthday of {query}.') for i in info["birthdays"]: if i["name"] == query: birthday = i["birthday"] print(f"{query}'s birthday is on {birthday}")
true
fe8c35b13ecc12fd043023795917be731beda765
alexdistasi/palindrome
/palindrome.py
937
4.375
4
#Author: Alex DiStasi #File: palindrome.py #Purpose: returns True if word is a palindrome and False if it is not def checkPalindrome(inputString): backwardsStr ="" #iterate through inputString backwards for i in range(len(inputString)-1,-1,-1): #create a reversed version of inputString backwardsStr+=(inputString[i]).lower() #iterate through inputString and compare to the reverse string. If an element has a different value, it is not a palindrome for i in range(0, len(inputString)): if inputString[i]!=backwardsStr[i]: return False return True #Ask user for a word to check until user writes 'stop': userWord = input("Enter a word to see if it is a palindrome. Type 'stop' to exit: ") while (userWord.lower() != "stop"): print (checkPalindrome(userWord)) userWord = input("Enter a word to see if it is a palindrome. Type 'stop' to exit: ")
true
353b341eb43b497f5e6618cd93a7ac169e03ccb7
JennyCCDD/fighting_for_a_job
/LC 反转字符串.py
1,064
4.125
4
# -*- coding: utf-8 -*- """ @author: Mengxuan Chen @description: 反转字符串 编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给出。 不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。 你可以假设数组中的所有字符都是 ASCII 码表中的可打印字符。 @revise log: 2021.01.11 创建程序 解题思路:双指针 """ class Solution(object): def reverseString(self, s): """ :type s: List[str] :rtype: None Do not return anything, modify s in-place instead. """ slow = 0 fast = len(s)-1 while slow < fast: #################################### s[fast], s[slow] = s[slow], s[fast] #################################### slow +=1 fast -=1 return s solution = Solution() result = solution.reverseString(["h","e","l","l","o"]) print(result)
false
8ebfcdfeba3a5e2a8adc7f70ea6bf85a3e423e68
abrambueno1992/Intro-Python
/src/fileio.py
526
4.40625
4
# Use open to open file "foo.txt" for reading object2 = open('foo.txt', 'r') # Print all the lines in the file # print(object) # Close the file str = object2.read() print(str) object2.close() # Use open to open file "bar.txt" for writing obj_bar = open("bar.txt", 'w') # Use the write() method to write three lines to the file obj_bar.write("Python is a great language.\nYeah its great!!\n New line") # Close the file obj_bar.close() objec_read = open('bar.txt', 'r') str2 = objec_read.read() print(str2) objec_read.close()
true
81cb9114c1fdd16e8b12863531fdaf860080943b
udbhavkanth/Algorithms
/Find closest value in bst.py
1,756
4.21875
4
#in this question we have a bst and #a target value and we have to find # which value in the bst is closest #to our target value. #First we will assign a variable closest #give it some big value like infinity #LOGIC: #we will find the absolute value of (target-closest) And # (target - tree value) # if the absoulte value of target-closest is larger than #absolute value of target - tree value than we will update our #closest and #than compare the tree value to target value if tree value is #greater than target then we only have to traverse left side of #tree if its lower than rigt side of tree #RECURSIVE WAY :- def findClosestValueInBst(tree, target): return findClosestValueInBstHelper(tree,target,float("inf")) def findClosestValueInBstHelper(tree,target,closest): if tree is None: return closest if abs(target-closest) > abs(target-tree.value): closest = tree.value if target < tree.value: return findClosestValueInBstHelper(tree.left,target,closest) elif target > tree.value: return findClosestValueInBstHelper(tree.right, target, closest) else: return closest def findClosestValueInBSt_1(tree, target): return findClosestValueInBstHelper1(tree,target,float("inf")) def findClosestValueInBstHelper1(tree,target,closest): currentNode = tree while currentNode is not None: if abs(target-closest) > abs(target-tree.value): closest = currentNode.value if target < currentNode.value: currentNode = currentNode.left elif target > currentNode.value: currentNode = currentNode.right else: break return closest
true
f132e65fb3e884765ab28eded1b9ededdb09a1b1
artalukd/Data_Mining_Lab
/data-pre-processing/first.py
1,964
4.40625
4
#import statement https://pandas.pydata.org/pandas-docs/stable/dsintro.html import pandas as pd #loading dataset, read more at http://pandas.pydata.org/pandas-docs/stable/io.html#io-read-csv-table df = pd.read_csv("iris.data") #by default header is first row #df = pd.read_csv("iris.data", sep=",", names=["petal_length","petal_width","sepal_length", "sepal_width", "category"]) #size of df df.shape() df.head() #df.tail(3) ''' Entire table is a data frame and The basics of indexing are as follows: Operation Syntax Result Select column df[col] Series Select row by label df.loc[label] Series Select row by integer location df.iloc[loc] Series Slice rows df[5:10] DataFrame Select rows by boolean vector df[bool_vec] DataFrame ''' #frame[colname] #df.frame["category"] #Acess particular element :df.loc[row_indexer,column_indexer] #df.loc[123,"petal_length"] #df.loc[123,"petal_length"] = <value of appropriate dtype> #assign always returns a copy of the data, leaving the original DataFrame untouched. #df.assign(sepal_ratio = df['sepal_width'] / df['sepal_length']).head()) ''' Simple python programming constructs: FOR loop: for item in sequence: # commands else: #commands example: word = "Hello" for character in word: print(character) While loop: while (condition): # commands else: # commands example: i = 0 while (i < 3): print("Knock") i += 1 print("Penny!") if-else in python example: option = int(input("")) if (option == 1): result = a + b elif (option == 2): result = a - b elif (option == 3): result = a * b elif (option == 4): result = a / b if option > 0 and option < 5: print("result: %f" % (result)) else: print("Invalid option") print("Thank you for using our calculator.") '''
true
988dab09d39206865788bc0f8d7c3088b551b337
VictoriaEssex/Codio_Assignment_Contact_Book
/part_two.py
2,572
4.46875
4
#Define a main function and introduce the user to the contact book #The function is executed as a statement. def main(): print("Greetings! \nPlease make use of my contact book by completing the following steps: \na) Add three new contacts using the following format: Name : Number \nb) Make sure your contacts have been arranged in alphebetical order.\nc) Delete a contact.\nd) Search for an existing contact.") #Create two variables made up of an array of strings. #The first variable represents the name of an indiviudal and the second is their contact number. Name = ['Victoria', 'Andrew'] print(Name) Number = ['0849993016', '0849879074'] print(Number) #Create a third variable, which is made of an empty array. contacts = [] print(contacts) #Create a loop which will continue to run until it reaches the length of array. #Make use of the append method to add a new contact to the end of the list. for i in range(len(Name)): contacts.append(Name[i] + ' : ' + Number[i]) #concatenation of the two different arrays. #Introduce a while loop to run until the statement is false, where the number of contacts has reached maximum number of 5. while len(contacts) < 5: details = input('Please enter a name and number of an individual to create a new contact.\n') # name : number contacts.append(details) print(contacts) #The sort method is used to arrange all your exisitng contacts into alphabetical order. contacts.sort() print(contacts) #A input is used to inform the user that they can delete a contact by inputting their name. name_to_delete = input('Which contact do you want to delete? ') #Delete a contact based on what it starts with. index_to_delete = 0 for c in range(len(contacts)): contact_name = contacts[c] if contact_name.startswith(name_to_delete): index_to_delete = c #The pop method is used to delete a contact in a specific index position. print('Index to delete: ' + str(index_to_delete)) contacts.pop(index_to_delete) print(contacts) #Search for a contact based on what their name starts with. name_search = input('Search contact: ') for search in range(len(contacts)): contact_name = contacts[search] if contact_name.startswith(name_search): print(contact_name) if __name__ == "__main__": main() #Close main function.
true
757b60fbc021114cc77faa07b7e828a12ea00072
aholyoke/language_experiments
/python/Z_combinator.py
1,285
4.28125
4
# ~*~ encoding: utf-8 ~*~ # Implementation of recursive factorial using only lambdas # There are no recursive calls yet we achieve recursion using fixed point combinators # Y combinator # Unfortunately this will not work with applicative order reduction (Python), so we will use Z combinator # Y := λg.(λx.g (x x)) (λx.g (x x)) Y = (lambda g: (lambda x: g(x(x)))(lambda x: g(x(x)))) # Z combinator # Like the Y combinator except it has an extra "thunking" step to prevent infinite reduction # Z = λf.(λx.f (λv.x x v)) (λx.f (λv.x x v)) Z = (lambda f: (lambda x: f(lambda v: x(x)(v)))(lambda x: f(lambda v: x(x)(v)))) # The definition of factorial # Takes a continuation r which will be the recursive definition of factorial # λr. λn.(1, if n = 0; else n × (r (n−1))) G = (lambda r: (lambda n: 1 if n == 0 else n * (r(n - 1)))) # Z(G) = factorial # The definition of factorial G is passed to Z as argument f # Since Z is a fixed point combinator it satisfies Z(G) = G(Z(G)) # G(Z(G)) tells us that parameter r of G is passed the recursive definition of factorial factorial = (lambda f: (lambda x: f(lambda v: x(x)(v)))(lambda x: f(lambda v: x(x)(v))))( lambda r: (lambda n: 1 if n == 0 else n * (r(n - 1)))) # demonstration print(factorial(5)) print(factorial(6))
true
89c5d7aa305f0ed3de08ff8ed66075ad1863a117
heersaak/opdrachtenPython
/Opdrachten/Les 5/5_1.py
763
4.25
4
##Schrijf een functie convert() waar je een temperatuur in graden Celsius (als parameter van deze ##functie) kunt omzetten naar graden Fahrenheit. Je kunt de temperatuur in Fahrenheit berekenen met ##de formule T(°F) = T(°C) × 1.8 + 32. Dus 25 °C = 25 * 1.8 + 32 = 77 °F. ##Schrijf nu ook een tweede functie table() waarin je met een for-loop van -30 °C t/m 40 °C in stappen ##van 10 graden de temperatuur in Fahrenheit print. Zorg middels een geformatteerde output voor ##dezelfde precisie en uitlijning als het voorbeeld hieronder: def convert(Celcius): fah = Celcius * 1.8 +32 return fah def table(): print(' {:7} {}'.format("F", "X")) for x in range(-30, 50, 10): print( '{:5} {:5}'.format(convert(x), x)) print(table())
false
40224c5ba455fb7e03e135ff2cb35e94c150e351
lyoness1/Calculator-2
/calculator.py
1,772
4.25
4
""" calculator.py Using our arithmetic.py file from Exercise02, create the calculator program yourself in this file. """ from arithmetic import * def intergerize(str_list): """returns a list of integers from a list of strings""" return map(int, str_list) def read_string(): """reads the input to determine which function in arithmetic.py to use""" token_list = raw_input().split() #original code: # if token_list[0] == "+": # return add(int(token_list[1]), int(token_list[2])) #code for taking multiple inputs - adjusted in arithmetic.py: # if token_list[0] == "+": # return add(map(int, token_list[1:])) if token_list[0] == "+": # code for using reduce() for multiple nums return my_reduce(add, intergerize(token_list[1:])) if token_list[0] == "-": return subtract(int(token_list[1]), int(token_list[2])) if token_list[0] == "*": return multiply(int(token_list[1]), int(token_list[2])) if token_list[0] == "/": return divide(int(token_list[1]), int(token_list[2])) if token_list[0] == "square": return square(int(token_list[1])) if token_list[0] == "cube": return cube(int(token_list[1])) if token_list[0] == "pow": return power(float(token_list[1]), float(token_list[2])) if token_list[0] == "mod": return mod(int(token_list[1]), int(token_list[2])) else: print "invalid operation" #my version of reduce() def my_reduce(func, iterable, initialzer=None): if initialzer is not None: answer = initialzer else: answer = iterable[0] iterable = iterable[1:] for i in iterable: answer = func(answer, i) return answer print "Your answer is {}".format(float(read_string()))
true
1e3e4a200bf8e1db120c6d21463a9186f26b19a5
ashwinimanoj/python-practice
/findSeq.py
805
4.1875
4
'''Consider this puzzle: by starting from the number 1 and repeatedly either adding 5 or multiplying by 3, an infinite amount of new numbers can be produced. How would you write a function that, given a num- ber, tries to find a sequence of such additions and multiplications that produce that number? For example, the number 13 could be reached by first multiplying by 3 and then adding 5 twice, whereas the number 15 cannot be reached at all.''' def findSeq(start, history, target) -> str: if start == target: return f'({history} = {str(target)})' elif start > target: return 0 else: return findSeq(5 + start, f'({history} + 5)', target)\ or findSeq(3 * start, f'({history} * 3)', target) num = int(input("Enter number: ")) print(findSeq(1, "1", num))
true
c71327e6285ac5f58b8fed3f95dd458037d016cb
vladimirkaldin/HomeTask
/1.2.py
613
4.4375
4
#2. Пользователь вводит время в секундах. Переведите время в часы, минуты и секунды и выведите в формате чч:мм:сс. # Используйте форматирование строк. seconds_time = int(input("Введите время в секундах")) print(f'Время {seconds_time} секунд') hours = seconds_time // 3600 minutes = int((seconds_time % 3600) / 60) seconds = int((seconds_time % 3600) % 60) print(f'Время {seconds_time} секунд составляет {hours}:{minutes}:{seconds}')
false
bbb273a9b1dce01c6c53f0f739272490f1455859
vladimirkaldin/HomeTask
/1.1.py
609
4.28125
4
#1. Поработайте с переменными, создайте несколько, выведите на экран, запросите у пользователя несколько чисел и #строк и сохраните в переменные, выведите на экран. age = 0 age = int(input("Введите возраст")) print(f'Возраст пользователя - {age}') name = 'Имя пользователя не задано' print(name) name = input("Введите имя пользователя") print(f'Имя пользователя - {name}, возраст {age} лет')
false
1377c3aabb11ba82fd0337b1ef56f0baf0c6de21
yunge008/LintCode
/6.LinkedList/[E]Nth to Last Node in List.py
1,236
4.1875
4
# -*- coding: utf-8 -*- __author__ = 'yunge008' """ Find the nth to last element of a singly linked list. The minimum number of nodes in list is n. Example Given a List 3->2->1->5->null and n = 2, return node whose value is 1. """ class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next class Solution: """ @param head: The first node of linked list. @param n: An integer. @return: Nth to last node of a singly linked list. """ def nthToLast(self, head, n): current = head return_node = head for i in xrange(n - 1): current = current.next if current: while current.next: current = current.next return_node = return_node.next return return_node n15 = ListNode(5) n14 = ListNode(6, n15) n13 = ListNode(7, n14) n12 = ListNode(8, n13) n11 = ListNode(9, n12) n19 = ListNode(1) n20 = ListNode(1, n19) n21 = ListNode(1, n20) n22 = ListNode(1, n21) n23 = ListNode(1, n22) s = Solution() head2 = s.nthToLast(n11, 0) while head2: print head2.val, print "->", head2 = head2.next print "None"
true
846b0924cec1a3fd9dfb225af2b22404d1ca5268
yunge008/LintCode
/6.LinkedList/[M]Convert Sorted List to Balanced BST.py
1,053
4.125
4
# -*- coding: utf-8 -*- __author__ = 'yunge008' """ Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. 2 1->2->3 => / \ 1 3 """ class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next class TreeNode(object): def __init__(self, val): self.val = val self.left, self.right = None, None class Solution: """ @param head: The first node of linked list. @return: a tree node """ def sortedListToBST(self, head): # write your code here pass n15 = ListNode(5) n14 = ListNode(6, n15) n13 = ListNode(7, n14) n12 = ListNode(8, n13) n11 = ListNode(9, n12) n19 = ListNode(1) n20 = ListNode(1, n19) n21 = ListNode(1, n20) n22 = ListNode(1, n21) n23 = ListNode(1, n22) s = Solution() head2 = s.sortedListToBST(n11) while head2: print head2.val, print "->", head2 = head2.next print "None"
true
eb856747b12ad9296e4309679c763175f2cfc018
Marusya-ryazanova/Lesson_2
/Vasya.py
747
4.25
4
speed = float(input("Средняя скорость: ")) time = int(input("Верям в пути: ")) point = time * speed # Вычисляем точку остановки if point > 100: print("поехал по второму кругу, пройденное растояние = ", point) elif point < 0: print("велосипедист едет назад уже", point , "километров") elif point == 0: print("Велосипедист ни куда не едет, скорость = " , speed) else: print("Велосипидист на ", point, ) # Выводим итог input("Нажмите Enter для выхода") # Просим нажать кнопку для завершения программы
false
896841b93741f2b09cd36c09ff494f1bb6851059
simplifiedlearning/dummy
/function.py
1,739
4.375
4
######################FUNCTIONS#################### #SYNTAX #using def keyword #without parameters def greet(): print("hello") greet() ###add two number #with parameters def add1(x,y): z=x+y print(z) add1(2,3) ####default arguments def add2(b,c,a=12): print(a+b+c) add2(5,5) ####abritriy arguments it is represented by * it is used when the programmer doesnt know how many arguments def read(*n): for x in n: print(x) read(1,2,3) #####RECURSION #Recursion doesnt have loops and do not use loops #takes a lot of space """def fact(n): if(n==1): return 1 else: return n*fact(n-1) r=fact(5) print(r)""" ### #fact(5) n!=1 so else statement is excuted #which gives 5*fact(4) and is not equal to 1 #again 4*fact(3) n!=1 #3*fact(2) n!=1 #2*fact(1) n==1 #soo returns 5*4*3*2*1=120 ##############X RAISED TO Y """x=int(input("enter the value of x")) y=int(input("enter the value of y")) def xtoy():""" ########WAP TO CHECK NUMBER IS PALINDROME OR NOT################# """n=int(input("enter the number")) r=0 m=n while(n>0): d=n%10 r=r*10+d n=n//10 if(m==r): print("its a palindrome") else: print("its not a palindrome")""" ########WAP TO CHECK IF NUMBER IS PRIME OR NOT################### """n=int(int("enter the number to be checked\n")) for i in range(2,n//2): if(n%i)==0: flag=0 break if(flag==0): print("is not prime number") else: print("prime")""" ####REVERSE USING FUNCTIONS """n=int(input("enter the number to be reversed\n")) def rev(n): r=0 while(n>0): d=n%10 r=r*10+d n=n//10 print(r) rev(n)"""
true
c0620531c0aea733e89fda828f42333573c5dcde
naomi-rc/PythonTipsTutorials
/generators.py
638
4.34375
4
# generators are iterators that can only be iterated over once # They are implemented as functions that yield a value (not return) # next(generator) returns the next element in the sequence or StopIteration error # iter(iterable) returns the iterable's iterator def my_generator(x): for i in range(x): yield i print(next(my_generator(10))) print() for i in my_generator(10): print(i) print() try: my_string = "Hi" iterator = iter(my_string) print(next(iterator)) print(next(iterator)) print(next(iterator)) except: print("No more elements left - Threw a StopIteration exception as expected")
true
2f7d869fdcce5a45fd4003d771984b3c871bb921
naomi-rc/PythonTipsTutorials
/enumerate.py
417
4.3125
4
# enumerate : function to loop over something and provide a counter languages = ["java", "javascript", "typescript", "python", "csharp"] for index, language in enumerate(languages): print(index, language) print() starting_index = 1 for index, language in enumerate(languages, starting_index): print(index, language) print() language_tuple = list(enumerate(languages, starting_index)) print(language_tuple)
true
b6edcfc7160d348fedf295982a0bfdb7a421aee2
E-voldykov/python_for_beginners
/les3/hmwrk6.py
1,054
4.3125
4
""" Реализовать функцию int_func(), принимающую слово из маленьких латинских букв и возвращающую его же, но с прописной первой буквой. Например, print(int_func(‘text’)) -> Text. Продолжить работу над заданием. В программу должна попадать строка из слов, разделенных пробелом. Каждое слово состоит из латинских букв в нижнем регистре. Сделать вывод исходной строки, но каждое слово должно начинаться с заглавной буквы. Необходимо использовать написанную ранее функцию int_func(). """ def int_func(slovo=str): slovo = slovo[0].upper() + slovo[1:] return slovo fraza = input(f"Введите фразу:\n") fraza = fraza.split(" ") for item in fraza: print(int_func(item), end=" ")
false
fbc9bbfbb0b4c12eb7af244cdf85a96fb726b2b2
RayGar7/AlgorithmsAndDataStructures
/Python/diagonal_difference.py
581
4.25
4
# Given a square matrix, calculate the absolute difference between the sums of its diagonals. # For example, the square matrix is shown below: # 1 2 3 # 4 5 6 # 9 8 9 # The left-to-right diagonal = 1 + 5 + 9 = 15. The right to left diagonal = 3 + 5 + 9 = 17. Their absolute difference is abs(15 - 17) = 2. def diagonalDifference(arr): n = len(arr) left_diagonal_sum = 0 right_diagonal_sum = 0 for i in range(0, n): left_diagonal_sum += arr[i][i] right_diagonal_sum += arr[i][n-1-i] return abs(left_diagonal_sum - right_diagonal_sum)
true
64466b637b49b744d34c0d37cacd212998177a0b
mohitarora3/python003
/sum_of_list.py
376
4.125
4
def sumList(list): ''' objective: to compute sum of list input parameters: list: consist of elemnts of which sum has to be found return value: sum of elements of list ''' #approach: using recursion if list == []: return 0 else: return(list[0]+sumList(list[1:])) print(sumList([1,2,3]))
true
5cecdc3cb4373a598efbe015f6446f84ee950501
lsalgado97/My-Portfolio
/python-learning/basics/guess-a-number.py
2,369
4.34375
4
# This is a code for a game in which the player must guess a random integer between 1 and 100. # It was written in the context of a 2-part python learning course, and is meant to introduce # basic concepts of Python: variables, logic relations, built-in types and functions, if and # for loops, user input, program output (via print()), string formating, importing and random # number generation. import random def run(): print("********************************") print("** Welcome to Guess-a-Number! **") print("********************************") print("") points = 1000 lost_points = 0 total_tries = 0 secret_number = random.randint(1, 100) print("Set the difficulty level") print("(1) Easy (2) Normal (3) Hard") level = int(input("Chosen level: ")) if level == 1: print("You are playing on easy mode") total_tries = 20 elif level == 2: print("You are playing on normal mode") total_tries = 10 else: print("You are playing on hard mode") total_tries = 5 print("") for current_round in range(1, total_tries+1): print("Try {} of {}".format(current_round, total_tries)) # string formatting prior to Python 3.6 guess = int(input("Guess a number between 1 and 100: ")) print("You guessed ", guess) if guess < 1 or guess > 100: print("You must guess between 1 and 100!") continue correct = guess == secret_number higher = guess > secret_number smaller = guess < secret_number if correct: print("You got it right :)") print("You made {} points!".format(points)) break else: if higher: print("You missed! Your guess is higher than the number.") elif smaller: print("You missed! Your guess is smaller than the number.") lost_points = abs(secret_number - guess) points = points - lost_points if current_round == total_tries: print("The secret number was {}, you made {} points".format(secret_number, points)) print("GAME OVER") # This prepares this python file to be executed inside another python program. if __name__ == "__main__": run()
true
620395a61e712ecf98438c7c2eff7b663247da51
wzz886/aaaaaa_game
/python 3 Tool/learn_def.py
2,457
4.4375
4
''' Python3 函数 函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段。 函数能提高应用的模块性,和代码的重复利用率。 你已经知道Python提供了许多内建函数,比如print()。 但你也可以自己创建函数,这被叫做用户自定义函数。 语法: def 函数名(参数列表): 函数体 ''' # 参数 ''' 以下是调用函数时可使用的正式参数类型: 1.必需参数 2.关键字参数 3.默认参数 4.不定长参数 ''' # 必需参数 def showInfo(str): "打印任何字符串" print(str) # 调用showInfo,必须传参 showInfo("调用showInfo,必须传参") # 关键字参数 # 使用关键字参数允许函数调用时参数的顺序与声明时不一致 def showInfo(name, age): "打印任何字符串" print(f"name = {name}") print(f"age = {age}") showInfo(age = 29, name = "wzz") # 默认参数 如果没有传递参数,则会使用默认参数 def showInfo(name = "wzz", age = 29): "打印任何字符串" print(f"name = {name}") print(f"age = {age}") showInfo() print("------不定长参数------") # 不定长参数 # 加了星号 * 的参数会以元组(tuple)的形式导入,存放所有未命名的变量参数 def showInfo(name, *vartuple): "打印任何字符串" print(f"name = {name}") print(vartuple) showInfo("wzz") showInfo("wzz", 1, 2, 3) # 加了两个星号 ** 的参数会以字典的形式导入 def showInfo(name = "wzz", **dict): "打印任何字符串" print(f"name = {name}") print(dict) showInfo("wzz", id = 1991, age = 29) print("----参数中星号 * 可以单独出现----") # 参数中星号 * 可以单独出现 def showInfo(a, *, b): "打印任何字符串" print(a) print(b) showInfo(1, b=3) # 匿名函数 lambda ''' 所谓匿名,意即不再使用 def 语句这样标准的形式定义一个函数。 lambda 只是一个表达式,函数体比 def 简单很多。 lambda的主体是一个表达式,而不是一个代码块。仅仅能在lambda表达式中封装有限的逻辑进去。 lambda 函数拥有自己的命名空间,且不能访问自己参数列表之外或全局命名空间里的参数。 虽然lambda函数看起来只能写一行,却不等同于C或C++的内联函数,后者的目的是调用小函数时不占用栈内存从而增加运行效率。 ''' print("----lambda----") sum = lambda a, b : a + b print(f"sum(1, 2) = {sum(1, 2)}")
false
4ed6cf981fd362e21ff59c9abbf24035f2e765a3
manovidhi/python-the-hard-way
/ex13.py
650
4.25
4
# we pass the arguments at the runtime here. we import argument to define it here. from sys import argv script, first, second, third = argv #print("this is script", argv.script) print( "The script is called:", script ) # this is what i learnt from hard way print ("Your first variable is:", first) print ("Your second variable is:", second) print ("Your third variable is:", third) age = input("put input your age]") print("your age is", age) # i put it to check input and argv difference #print("this is script", argv[0]) #this is from mihir #print("this is first", argv[1]) #print("this is 2nd", argv[2]) #print("this is third", argv[3])
true
1ad2cd819e2b9ca0e38435955fdea7a29211eb75
chaerui7967/K_Digital_Training
/Python_KD_basic/List/list_3.py
277
4.3125
4
#리스트 내용 일치 list1 = [1,2,3] list2 = [1,2,3] # == , !=, <, > print(list1 == list2) # 2차원 리스트 list3 = [[1,2,3],[4,5,6],[7,8,9]] #행렬 형식으로 출력 for i in list3: print(i) for i in list3: for j in i: print(j, end="") print()
false
c01b4306131f6fa4bd8a59f7b68ec758e2b16a5c
quynguyen2303/python_programming_introduction_to_computer_science
/Chapter5/wordLength.py
708
4.40625
4
# Average Words Length # wordLength.py # Get a sentence, remove the trailing spaces. # Count the length of a sentence. # Count the number of words. # Calculate the spaces = the number of words - 1 # The average = (the length - the spaces) / the number of words def main(): # Introduction print('The program calculates the average length of words in a sentence.') # Get a sentence sentence = input('Enter a sentence: ').rstrip() # Seperate it into words words = sentence.split() # Calculate the average length of words average = (len(sentence) - (len(words) - 1)) / len(words) # Rule them all print('Your average length of words is {0:.2f}.'.format(average)) main()
true
2afa7c968a716fcca6cdb879880091093f1d22fc
quynguyen2303/python_programming_introduction_to_computer_science
/Chapter11/sidewalk.py
510
4.125
4
# sidewalk.py from random import randrange def main(): print('This program simulates random walk inside a side walk') n = int(input('How long is the side walk? ')) squares = [0]*n results = doTheWalk(squares) print(squares) def doTheWalk(squares): # Random walk inside the Sidewalk n = len(squares) pos = n // 2 while pos >= 0 and pos < n: squares[pos] += 1 x = randrange(-1,2,2) pos += x return squares if __name__ == '__main__': main()
true
393e027c2e80d8a2ca901ef0104ac59c6887770d
quynguyen2303/python_programming_introduction_to_computer_science
/Chapter3/distance.py
467
4.21875
4
# Distance Calculation # distance.py import math def main(): # Instruction print('The program calculates the distance between two points.') # Get two points x1, y1, x2, y2 = eval(input('Enter two points x1, y1, x2, y2:'\ '(separate by commas) ')) # Calculate the distance distance = math.sqrt((y2 - y1) ** 2 + (x2 - x1) ** 2) # Rule them all print('The distance is {0:.2f}.'.format(distance)) main()
true
39c742637396b520ad65097e4a6ac7fc92b16af4
quynguyen2303/python_programming_introduction_to_computer_science
/Chapter8/syracuse.py
447
4.125
4
# syracuse.py # Return a sequence of Syracuse number def main(): # Introduction print('The program returns a sequence of Syracuse number from the first input.') # Get the input x = int(input('Enter your number: ')) # Loop until it comes to 1 while x != 1: if x % 2 == 0: x = x // 2 else: x = 3 * x + 1 print(x, end=', ') if __name__ == '__main__': main()
true
5dd5876363aa431cb73871182406d6da8cef8503
MakeRafa/CS10-poetry_slam
/main.py
1,376
4.25
4
# This is a new python file # random library import random filename = "poem.txt" # gets the filename poem.txt and moves it here def get_file_lines(filename): read_poem = open(filename, 'r') # reads the poem.txt file return read_poem.readlines() def lines_printed_backwards(lines_list): lines_list = lines_list[::-1] #this reverses a line for line in lines_list: #this is used in every function afterwards to pick poem lines print(line) print("*************************************************************************") print("Backwords Poem") lines_printed_backwards(get_file_lines(filename)) # calling the function to be able to print print("*************************************************************************") def lines_printed_random(lines_list): random.shuffle(lines_list) #mixes lines in random order for line in lines_list: print(line) print("Random Line Poem") lines_printed_random(get_file_lines(filename)) print("*************************************************************************") print("Every 5th line Poem") # def lines_printed_custom(): with open('poem.txt') as fifth: for num, line in enumerate(fifth): if num%5 == 0: #chooses every fifth line starting at the first one print(line) print("*************************************************************************")
true
72e84ca9b62056459a760f02f775cd5b59d0d801
palashsharma891/Algorithms-in-Python
/6. Searching and Sorting/bubbleSort.py
309
4.34375
4
def bubbleSort(array): for i in range(len(array)): for j in range(0, len(array) - i - 1): if array[j] > array[j+1]: (array[j], array[j+1]) = (array[j+1], array[j]) data = [-2, 45, 0, 11, -9] bubbleSort(data) print("Sorted array is: ") print(data)
false
5b4161986fe4af26d3a588ecd8a28347212aecbf
lexboom/Testfinal
/Studentexempt.py
2,121
4.375
4
#Prompt the user to enter the student's average. stu_avg = float(input("Please enter student's average: ")) #Validate the input by using a while loop till the value #entered by the user is out of range 0 and 100. while(stu_avg < 0 or stu_avg > 100): #Display an appropriate message and again, prompt #the user to enter a valid average value. print("Invalid average! Please enter a valid " + "average between 0 - 100:") stu_avg = float(input("Please enter student's " + "average: ")) #Prompt the user to enter the number of days missed. num_days_missed = int(input("Please enter the number " + "of days missed: ")) #Validate the input by using a while loop till the #value entered by the user is less than 0. while(num_days_missed < 0): #Display an appropriate message and again, prompt #the user to enter a valid days value. print("Invalid number of days! Please enter valid " + "number of days greater than 0:") num_days_missed = int(input("Please enter the " + "number of days missed: ")) #If the student's average is at least 96, then the #student is exempt. if(stu_avg >= 96): print("Student is exempt from the final exam. " + "Because, the student's average is at least 96.") #If the student's average is at least 93 and number of #missing days are less than 3, then the student is #exempt. elif(stu_avg >= 93 and num_days_missed < 3): print("Student is exempt from the final exam. " + "Because, the student's average is at least 93 " + "and number of days missed are less than 3.") #If the student's average is at least 90 and there is a #perfect attendence i.e., number of missing days is 0, #then the student is exempt. elif(stu_avg >= 90 and num_days_missed == 0): print("Student is exempt from the final exam. " + "Because, the student's average is at least 90 " + "and student has perfect attendence.") #Otherwise, student is not exempt. else: print("Student is not exempt from the final exam.")
true
3196064e2211728cc382913d1f6c6a0b019364c4
micajank/python_challenges
/exercieses/05factorial.py
365
4.40625
4
# Write a method to compute the `factorial` of a number. # Given a whole number n, a factorial is the product of all # whole numbers from 1 to n. # 5! = 5 * 4 * 3 * 2 * 1 # # Example method call # # factorial(5) # # > 120 # def factorial(num): result = 1 for i in range(result, (num + 1)): result = result * i return result print(factorial(5))
true
a21ef75e7a1ad5af81cada429876d9d06b317e17
Jose1697/crud-python
/16. OperacionesConListas.py
1,284
4.125
4
# + (suma) a = [1,2] b = [2,3] print(a+b) #[1,2,2,3] # * (multiplicacion) c = [5, 6] print(c*3) #[5, 6, 5, 6, 5, 6] #Añadir un elemento al final de la lista d = [3,5,7] d.append(9) print(d) #[3, 5, 7, 9] print(len(d)) #4 el tamaño de la lista #Para sacar el ultimo elemento de la lista, tambien se puede utilizar un indice e = [3,9,10,11] f = e.pop() #Elimina el 11 y lo guarda en f print(f) print(e) #[3, 9, 10] #Si quieres eliminar y sabes el indice puedes utilizar 'del' g = [4,8,12,16,17.19] del g[3] #se tendria que eliminar 16 print(g) #[4, 8, 12, 17.19] #Si quieres eliminar y sabes que elemento quieres eliminar pero no su indice: 'remove' paises = ['peru','chile','argentina','uruguay'] paises.remove('chile') print(paises) #['peru', 'argentina', 'uruguay'] #ordenar en una lista: sorted import random random_numbers = [] for i in range(10): random_numbers.append(random.randint(0, 15)) print(random_numbers) #[6, 13, 11, 12, 2, 6, 12, 13, 14, 5] ordered_numbers = sorted(random_numbers) #Sirve para ordenar print(ordered_numbers) #[2, 5, 6, 6, 11, 12, 12, 13, 13, 14] nombres = ['zeze','juanita','piero','alejo'] nombres_ordenados = sorted(nombres) print(nombres_ordenados) #['alejo', 'juanita', 'piero', 'zeze'] #lista.sort ----> ordena la lista
false
ab30e8e66f9c5c70b6688770b821f85df5b1017c
LEE2020/leetcode
/coding_100/1669_mergeInBetween.py
1,889
4.625
5
''' 给你两个链表 list1 和 list2 ,它们包含的元素分别为 n 个和 m 个。 请你将 list1 中第 a 个节点到第 b 个节点删除,并将list2 接在被删除节点的位置。 下图中蓝色边和节点展示了操作后的结果: 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/merge-in-between-linked-lists 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 输入:list1 = [0,1,2,3,4,5], a = 3, b = 4, list2 = [1000000,1000001,1000002] 输出:[0,1,2,1000000,1000001,1000002,5] 解释:我们删除 list1 中第三和第四个节点,并将 list2 接在该位置。上图中蓝色的边和节点为答案链表。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/merge-in-between-linked-lists 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 ''' # Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def mergeInBetween(self, list1, a, b, list2): """ :type list1: ListNode :type a: int :type b: int :type list2: ListNode :rtype: ListNode 找到 a,b 对应的node,记录下来。在a.next = list2 , list2.next = b """ left = ListNode(None) right = ListNode(None) cnt = 0 cur = list1 while cnt!= a-1: cur = cur.next cnt += 1 left = cur cnt = 0 cur = list1 while cnt != b+1: cur = cur.next cnt += 1 right = cur left.next = list2 cur = list2 while cur.next: cur = cur.next cur.next = right return list1
false
2501c35e44be4af82b2d46b48d92125109bb245f
DevYam/Python
/filereading.py
967
4.125
4
f = open("divyam.txt", "rt") # open function will return a file pointer which is stored in f # mode can be rb == read in binary mode, rt == read in text mode # content = f.read(3) # Will read only 3 characters # content = content + "20" # content += "test" # content = f.read(3) # Will read next 3 characters # print(content) # content = f.read() # print(content) # for abc in content: # print(abc) # Will print character by character # For printing line by line we can iterate over the pointer f # for ab in f: # print(ab) # This prints a new line character at the end of each line because that is present in text file # # for ab in f: # print(ab, end=" ") # This prints line by line # print(f.readline(), end=" ") # This space in end=" " makes the second line move a little further # print(f.readline()) # print(f.readline()) content = f.readline() content += f.readline() print(content) # print(f.readlines()) f.close()
true
e7ddc640319e91b422cbee450ecb6ce69c13f534
DevYam/Python
/lec10.py
1,270
4.375
4
# Dictionary is a data structure and is used to store key value pairs as it is done in real life dictionaries d1 = {} print(type(d1)) # class dict ==> Dictionary (key value pair) d2 = {"Divyam": "test", "test2": "testing", "tech": "guru", "dict": {"a": "dicta", "b": "dictb"}} print(d2) print(d2["Divyam"]) # Keys of dictionary are case sensitive # print(d2["0"]) ==> Error print(d2["dict"]["b"]) # queering nested dictionary # The values in the key value pair of dictionary can be a list, tuple, # dictionary etc but the key should be of immutable type . e.g String or numbers # Adding new items to dictionary d2["added"] = "newlyAdded" print(d2) # dictionary keys can be numbers as well d2[420] = "I am 420" print(d2) # deleting key 420 from dictionary del d2[420] print(d2) # Element with key 420 got deleted d3 = d2 # here it will behave as pass by reference del d3["added"] print(d2) # key with element added got deleted from d2 as well # To avoid this we will use copy function d4 = d2.copy() del d4["Divyam"] print(d2) # not deleted from original dictionary print(d4) # Deleted from copy print(d2.get("Divyam")) d2.update({"opem": "sankore"}) print(d2) print(d2.keys()) print(d2.values()) print(d2.items()) # prints full key value pairs
true
a42e4fce2736ca3bcf39aa3076ade26519b55472
DevYam/Python
/lec16.py
393
4.5
4
# for loop in python list1 = ["Divyam", "Kumar", "Singh"] for item in list1: print(item) # Iterating through list of lists (Unpacking list of lists) list2 = [["divyam", 23], ["kumar", 36], ["singh", 33]] for item, weight in list2: print(item, weight) dict1 = dict(list2) print(dict1) for item in dict1: print(item) for item, weight in dict1.items(): print(item, weight)
false
69c56249896e306fe80e40ce278505d5be077cc4
minwuh0811/DIT873-DAT346-Techniques-for-Large-Scale-Data
/Programming 1/Solution.py
928
4.25
4
# Scaffold for solution to DIT873 / DAT346, Programming task 1 def fib (limit) : # Given an input limit, calculate the Fibonacci series within [0,limit] # The first two numbers of the series are always equal to 1, # and each consecutive number returned is the sum of the last two numbers. # You should use generators for implementing this function # See https://docs.python.org/3/howto/functional.html#generator-expressions-and-list-comprehensions # Your code below a,b=0,1 while (a<=limit): yield a a,b=b,a+b def list_fib(limit) : # Construct a list of Fibonacci series list = [] # Your code below num=fib(limit) for nu in num: list.append(nu) return list # The following is called if you execute the script from the commandline # e.g. with python solution.py if __name__ == "__main__": assert list_fib(20) == [0, 1, 1, 2, 3, 5, 8, 13]
true
6dbf182ee4624e998d86436c9123e497ba6343ab
Arshad221b/Python-Programming
/multipleinheritance.py
714
4.34375
4
# In python we can use mutiple inheritance class A: def __init__(self) -> None: super().__init__() self.mike = "Mike" self.name = "Class A" class B: def __init__(self) -> None: super().__init__() self.bob = "bob" self.name = "Class B" class C(A, B): # multiple inheritance def __init__(self) -> None: super().__init__() def multiinherit(self): print(self.mike) print(self.bob) print(self.name) # it will print Class A because the class A is passed before B to class C, would print Class B if we pass C(B, A) c = C() print(c.multiinherit()) print(C.__mro__) # method resolution order
false
a509f3fa6ed91012ceb290f7f3e98d6acde69578
FredC94/MOOC-Python3
/UpyLab/UpyLaB 3.06 - Instructions conditionnelles.py
949
4.1875
4
""" Auteur: Frédéric Castel Date : Mars 2020 Projet : MOOC Python 3 - France Université Numérique Objectif: Écrire un programme qui imprime la moyenne géométrique \sqrt{a.b} (la racine carrée du produit de a par b) de deux nombres positifs a et b de type float lus en entrée. Si au moins un de ces nombres est strictement négatif, le programme imprime le texte « Erreur ». Consignes: Attention, nous rappelons que votre code sera évalué en fonction de ce qu’il affiche, donc veillez à n’imprimer que le résultat attendu. En particulier, il ne faut rien écrire à l’intérieur des appels à input (float(input()) et non float(input("Entrer un nombre : ")) par exemple), ni ajouter du texte dans ce qui est imprimé (print(res) et non print("résultat:", res) par exemple). """ import math a = float(input()) b = float(input()) if a < 0 or b < 0: print("Erreur") else: print(math.sqrt(a * b))
false
dd8ec5954a400f30b2af555dc79650c1712437c7
FredC94/MOOC-Python3
/Exercices/20200430 Sudoku Checker.py
1,672
4.15625
4
# Function to check if all the subsquares are valid. It will return: # -1 if a subsquare contains an invalid value # 0 if a subsquare contains repeated values # 1 if the subsquares are valid. def valid_subsquares(grid): for row in range(0, 9, 3): for col in range(0,9,3): temp = [] for r in range(row,row+3): for c in range(col, col+3): if grid[r][c] != 0: temp.append(grid[r][c]) # Checking for invalid values. if any(i < 0 and i > 9 for i in temp): print("Invalid value") return -1 # Checking for repeated values. elif len(temp) != len(set(temp)): return 0 return 1 # Function to check if the board invalid. def valid_board(grid): # Check each row and column. for i in range(9): res1 = valid_row(i, grid) res2 = valid_col(i, grid) # If a row or column is invalid then the board is invalid. if (res1 < 1 or res2 < 1): print("The board is invalid") return # If the rows and columns are valid then check the subsquares. res3 = valid_subsquares(grid) if (res3 < 1): print("The board is invalid") else: print("The board is valid") def print_board(grid): for row in grid: print(row) board = [[1, 4, 7, 0, 0, 0, 0, 0, 3], [2, 5, 0, 0, 0, 1, 0, 0, 0], [3, 0, 9, 0, 0, 0, 0, 0, 0], [0, 8, 0, 0, 2, 0, 0, 0, 4], [0, 0, 0, 4, 1, 0, 0, 2, 0], [9, 0, 0, 0, 0, 0, 6, 0, 0], [0, 0, 3, 0, 0, 0, 0, 0, 9], [4, 0, 0, 0, 0, 2, 0, 0, 0], [0, 0, 1, 0, 0, 8, 0, 0, 7]] print_board(board) valid_board(board)
true
7cee4c3d7df7f1adc67ef7482d0cf9aa3a0b1093
FredC94/MOOC-Python3
/UpyLab/UpyLaB 3.18 - Boucle For.py
1,959
4.375
4
""" Date : Avril 2020 Projet : MOOC Python 3 - France Université Numérique Objectif: Écrire un programme qui lit un nombre entier strictement positif n et imprime une pyramide de chiffres de hauteur n (sur n lignes complètes, c'est-à-dire toutes terminées par une fin de ligne). La première ligne imprime un “1” (au milieu de la pyramide). La ligne i commence par le chiffre i % 10 et tant que l’on n’est pas au milieu, le chiffre suivant a la valeur suivante ((i+1) % 10). Après le milieu de la ligne, les chiffres vont en décroissant modulo 10 (symétriquement au début de la ligne). Notons qu’à la dernière ligne, aucune espace n’est imprimée avant d’écrire les chiffres 0123.... Consignes: Attention, nous rappelons que votre code sera évalué en fonction de ce qu’il affiche, donc veillez à n’imprimer que le résultat attendu. En particulier, il ne faut rien écrire à l’intérieur des appels à input (int(input()) et non int(input("Entrer un nombre : ")) par exemple), ni ajouter du texte dans ce qui est imprimé. Conseils: Pour tester votre code, UpyLaB va l’exécuter plusieurs fois en lui fournissant à chaque test des nombres différents en entrée. Il vérifiera alors que le résultat affiché par votre code correspond à ce qui est attendu. N’hésitez donc pas à tester votre code en l’exécutant plusieurs fois dans PyCharm avec des valeurs différentes en entrée y compris supérieure à 10. """ N=int(input()) for i in range(1,N+1): for j in range(N,i,-1): print(" ", end='') for k in range(1,i+1): if i == 1: print(i%10, end='') else: print(i%10, end='') i=i+1 for q in range(i-1,0,-1): if (i != j): i=i-1 if i == j == k == q == N: break else: print((i-1)%10,end="") print()
false
b441d9cbcccdfa77932e707e4e9c4490cb0e4c78
Shyonokaze/mysql.py
/mysql.py
2,656
4.21875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Mar 7 12:41:02 2018 @author: pyh """ ''' This class is for creating database and table easier by using pymysql ''' import pymysql class mysql_data: def __init__(self,user_name,password): self.conn=pymysql.connect(host='127.0.0.1', port=3306, user=user_name, passwd=password, charset='utf8') self.cursor=self.conn.cursor() def create_DATABASE(self,db_name): self.cursor.execute('drop database if exists '+db_name) self.cursor.execute('create database '+db_name) self.cursor.execute('use '+db_name) def delete_DATABASE(self,db_name): self.cursor.execute('drop database if exists '+db_name) def use_DATABASE(self,db_name): try: self.cursor.execute('use '+db_name) except: print('use new database failed') def show_DATABASE(self): self.cursor.execute('show databases') return self.cursor.fetchall() def create_TABLE(self,name,content): self.cursor.execute('drop table if exists '+name) self.cursor.execute('create table '+name+'('+content+')') def insert_TABLE(self,table,value): self.cursor.execute('insert into '+table+' values('+value+')') self.conn.commit() def insert_all_TABLE(self,table,value): self.cursor.execute('insert into '+table+' values'+value) self.conn.commit() def delete_TABLE(self,table_name): self.cursor.execute('drop table if exists '+table_name) def show_TABLE(self,table_name): self.cursor.execute('select * from '+table_name) return self.cursor.fetchall() def show_une(self,table_name,require): self.cursor.execute('select U,N,E from '+table_name+' where '+require) U=[] N=[] E=[] data=self.cursor.fetchall() for i in range(len(data)): U.append(data[i][0]) N.append(data[i][1]) E.append(data[i][2]) return U,N,E def close(self): self.cursor.close() self.conn.close() if __name__=='__main__': db=mysql_data('root','622825') db.create_DATABASE('test5') db.use_DATABASE('test1') db.create_TABLE('hh','id int,name varchar(20) charset utf8') db.insert_all_TABLE('hh(id,name)',"(11,'苏打'),(12,'苏打')") db.insert_TABLE('hh(id,name)',"12,'sss'") print(db.show_DATABASE()) print(db.show_TABLE('hh')) db.delete_TABLE('hh') db.close()
true
62eb7a775f5d75af407ea7dba1ea4266dab00b89
carlosfabioa/TDS_exercicios_logica_programacao
/5- Matriz de uma dimensao - aplicacao pratica/05exercicio.py
1,052
4.125
4
''' e. Ler duas matrizes do tipo vetor A com 20 elementos e B com 30 elementos. Construir uma matriz C, sendo esta a junção das duas outras matrizes. Desta forma, C deverá ter a capacidade de armazenar 50 elementos. Apresentar os elementos da matriz C em ordem decrescente. ''' TAMANHO_A = 20 TAMANHO_B = 30 a = [] b = [] c = [] #ler matriz A com 20 elementos print('ELEMENTOS DA MATRIZ A') for i in range(TAMANHO_A): n = int(input('Entre com elemento para matriz A: ')) a.append(n) c.append(n) #elementos de A adicionados ao final da matriz C #ler matriz B com 30 elementos print('ELEMENTOS PARA A MATRIZ B') for i in range(TAMANHO_B): n = int(input('Entre com elemento para matriz B: ')) b.append(n) c.append(n) #elementos de B adicionados ao final da matriz C #Apresentação da matriz C em ordem decrescente for i in range(len(c)): for j in range(i): if c[i] > c[j]: aux = c[i] c[i] = c[j] c[j] = aux print('Elementos de C ordenados em ordem decrescente') print(c)
false
7fe0d3a00eb4d208cc68115f43c0aa15dc21e386
carlosfabioa/TDS_exercicios_logica_programacao
/5- Matriz de uma dimensao - aplicacao pratica/04exercicio.py
1,502
4.28125
4
''' d. Ler uma matriz A com 12 elementos. Após a sua leitura, colocar os seus elementos em ordem crescente. Depois ler uma matriz B também com 12 elementos. Colocar os elementos de B em ordem crescente. Construir uma matriz C, onde cada elemento de C é a soma do elemento correspondente de A com B. Colocar em ordem crescente a matriz C e apresentar os seus valores ''' TAMANHO = 12 a = [] b = [] c = [] #entrada elementos matriz A print('ELEMENTOS DE A') for i in range(TAMANHO): a.append(int(input('Entre com elementos de A: '))) #ordenar elementos matriz A for i in range(TAMANHO): for j in range(i): if a[i] < a[j]: aux = a[i] a[i] = a[j] a[j] = aux print('Elementos de A ordenados') print(a) #entrada elementos matriz B print('ELEMENTOS DE B: ') for i in range(TAMANHO): b.append(int(input('Entre com os elementos de B: '))) #ordenar elementos matriz B for i in range(TAMANHO): for j in range(i): if b[i] < b[j]: aux = b[i] b[i] = b[j] b[j] = aux print('Elementos de B ordenados') print(b) #cria matriz C (soma dos elementos de A com elementos de B) for i in range(TAMANHO): c.append(a[i] + b[i]) print('Matriz c criada a partir da soma dos elementos: ', c) #ordenar elementos matriz C for i in range(TAMANHO): for j in range(i): if c[i] < c[j]: aux = c[i] c[i] = c[j] c[j] = aux print('Elementos de C ordenados') print(c)
false
342e208d29d4ab099b5efc8c79fff7f53b16dd5d
carlosfabioa/TDS_exercicios_logica_programacao
/5- Matriz de uma dimensao - aplicacao pratica/07exercicio.py
942
4.15625
4
''' g. Ler 20 elementos de uma matriz A tipo vetor e construir uma matriz B da mesma dimensão com os mesmos elementos de A acrescentados de mais 2. Colocar os elementos da matriz B em ordem crescente. Montar uma rotina de pesquisa, para pesquisar os elementos armazenados na matriz B. ''' TAMANHO = 20 a =[]; b=[] #Matriz A for i in range(TAMANHO): a.append(int(input('Entre com um elemento: '))) #matriz B com o valor do cubo de cada elemento de A for i in range(TAMANHO): n = a[i] + 2 b.append(n) #ordenar elementos matriz B for i in range(TAMANHO): for j in range(i): if b[i] < b[j]: aux = b[i] b[i] = b[j] b[j] = aux print('Elementos de C ordenados') print(b) #busca o elemento no vetor B busca = int(input('Entre com um numero a ser pesquisado: ')) for i in range(len(b)): if b[i] == busca: print('O elemento ', b[i], ' foi localizado na posição ', i)
false
061b1f29b6c5bc4f2717b07a554e3dd5eac13dab
metehankurucu/data-structures-and-algorithms
/Algorithms/Sorting/BubbleSort/BubbleSort.py
399
4.21875
4
def bubbleSort(arr): n = len(arr) for i in range(n): swapped = False #Every iteration, last i items sorted for j in range(n-i-1): if(arr[j] > arr[j+1]): swapped = True arr[j], arr[j+1] = arr[j+1],arr[j] # One loop without swapping means that array already sorted if(not swapped): break
true
b6940f7168dfdea5713ec979dab30c5a77d993b9
NayeemH/Data-Structure-python
/Sorting Algorithms/Merge-Sort/MergeSort.py
1,193
4.375
4
def mergeSort(arr): if len(arr)>1: # Finding the mid of the array mid = len(arr)//2 # Dividing the array elements left_array = arr[:mid] right_array = arr[mid:] # Sorting the first half mergeSort(left_array) # Sorting the second half mergeSort(right_array) i = 0 #for left array j = 0 # for right array k = 0 # merge array index # Copy data to temp arrays Left_array[] and Right_array[] while i<len(left_array) and j<len(right_array): if left_array[i] < right_array[j]: arr[k] = left_array[i] i += 1 else: arr[k] = right_array[j] j += 1 k += 1 # Checking if any element was left while i< len(left_array): arr[k] = left_array[i] i += 1 k += 1 while j< len(right_array): arr[k] = right_array[j] j += 1 k += 1 arr = [12, 11, 13, 5, 6, 7] print("Given array is", end="\n") print(arr) mergeSort(arr) print("Sorted array is: ", end="\n") print(arr)
false
fdc1e38708d2d91acaad06ea6cb73545921f6305
jonathan-pasco-arnone/ICS3U-Unit5-02-Python
/triangle_area.py
1,075
4.15625
4
#!/usr/bin/env python3 # Created by: Jonathan Pasco-Arnone # Created on: December 2020 # This program calculates the area of a triangle def area_of_triangle(base, height): # calculate area area = base * height / 2 print("The area is {}cm²".format(area)) def main(): # This function calls gets inputs, checks them for errors and # calls the specified functions print("") print("This program calculates the area of a triangle") print("") print("Please input the base and height") print("") base_from_user_str = input("Base: ") print("") height_from_user_str = input("Height: ") print("") try: base_from_user = int(base_from_user_str) height_from_user = int(height_from_user_str) except Exception: print("Please enter a real base and height") else: if base_from_user > 0 and height_from_user > 0: area_of_triangle(base_from_user, height_from_user) else: print("Please enter positive values for base and height") if __name__ == "__main__": main()
true
32a7acb3d2d77e31c343d09d2f1b1d60d289d77f
asurendrababu/nehprocpy
/alphabetRangoli.py
714
4.15625
4
# You are given an integer, . Your task is to print an alphabet rangoli of size . (Rangoli is a form of Indian folk art based on creation of patterns.) # # Different sizes of alphabet rangoli are shown below: # # #size 3 # # ----c---- # --c-b-c-- # c-b-a-b-c # --c-b-c-- # ----c---- import string alphaArr = list(string.ascii_lowercase) def print_rangoli(size): for i in range(size - 1, 0, -1): print(("-".join(alphaArr[i: size][:: - 1] + alphaArr[i + 1: size])).center((4 * size) - 3, "-")) for i in range(1, size): print(("-".join(alphaArr[i: size][:: - 1] + alphaArr[i + 1: size])).center((4 * size) - 3, "-")) if __name__ == '__main__': n = int(input()) print_rangoli(n)
false
a80210552c4810d0b9d7a1b710934aaddda73b9d
lindagrz/python_course_2021
/day5_classwork.py
2,850
4.46875
4
# 1. Confusion T # he user enters a name. You print user name in reverse (should begin with capital letter) then extra # text: ",a thorough mess is it not ", then the first name of the user name then "?" Example: Enter: Valdis -> # Output: Sidlav, a thorough mess is it not V? # # # 2. Almost Hangman # Write a program to recognize a text symbol The user (first player) enters the text. Only # asterisks instead of letters are output. Assume that there are no numbers, but there may be spaces. The user (i.e. # the other player) enters the symbol. If the letter is found, then the letter is displayed in ALL the appropriate # places, all other letters remain asterisks. # Example: First input: Kartupeļu lauks -> ********* ***** Second input: # a -> *a****** *a*** # # In principle, this is a good start to the game of hangman. # https://en.wikipedia.org/wiki/Hangman_(game) # # # 3. Text conversion # Write a program for text conversion Save user input Print the entered text without changes # Exception: if the words in the input are not .... bad, then the output is not ... bad section must be changed to # is good def confusion(): name = input("Enter a name: ") print(name[::-1].title()) def almost_hangman(): word = input("First player, enter the text: ") # word = "Kartupeļu lauks" guessed = "*" * len(word) letter = " " # to add back the spaces before starting while not letter == "0": for i, c in enumerate(word): if c.lower() in letter.lower(): # guesses are not case sensitive guessed = guessed[:i] + c + guessed[i + 1:] if guessed.find("*") == -1: print("Good job!") break print(guessed) letter = input("Player 2: Guess a letter (or input 0 to give up): ") print(f"The answer was: {word}") def text_conversion(): text = input("Input text: ") # text = "The weather is not bad" # text = "The car is not new" # text = "This cottage cheese is not so bad" # text = "That was pretty bad, was in not my friend?" # text = "This sport is not badminton!" start = "not" tail = "bad" alternative = "good" # # for the Latvian language variation # text = "Laikapstākļi nav slikti" # text = "Mašīna nav jauna" # text = "Kartupeļu biezenis nav nemaz tik slikts" # start = "nav" # tail = "slikt" # alternative = "ir lab" if text.find(start) != -1 and text.find(tail, text.find(start)) != -1 and text.split(tail)[1][0].isspace(): starting_text = text.split(start)[0] ending_text = text.split(tail)[1] print(f"Result: {starting_text}{alternative}{ending_text}") else: print(f"Nothing to convert: {text}") def main(): # confusion() # almost_hangman() text_conversion() if __name__ == "__main__": main()
true
2b7a758e15f6cd2be76e6cf416a07860663da96b
emilybee3/deployed_whiteboarding
/pig_latin.py
1,611
4.3125
4
# Write a function to turn a phrase into Pig Latin. # Your function will be given a phrase (of one or more space-separated words). #There will be no punctuation in it. You should turn this into the same phrase in Pig Latin. # Rules # If the word begins with a consonant (not a, e, i, o, u), #move first letter to end and add "ay" to the end #if word begins with a vowel, add "yay" to the end ########################################################################################### ########################################################################################### #first function will turn words into pig latin #Example input: # "Hello" = "Ellohey" # "Android" = "Androidyay" def pig_latin(word): #create a list of vowels for function to check the first letter #of input word against vowels = ["a", "e", "i", "o", "u"] #first letter = vowel condition if word[0] in vowels: return word + "yay" #first letter = consenent condition else: return word[1:] + word[0] + "ay" #second function will pig latin all the words in a phrase #example input: #"Hello my name is so and so" = "ellohey ymay amenay isyay osay andyay osay" def pig_phrase(phrase): #split phrase into words so that pig_latin can work on each part split_phrase = phrase.split(" ") #create a list to put all the pig latined words: piggied_words = [] #apply pig_latin to each word for word in split_phrase: piggied_words.append(pig_latin(word)) #join list to return full phrase print " ".join(piggied_words) pig_phrase("I am a sentence")
true
55a100f8658a25e2003a382f91c430f993c11a21
findango/Experiments
/linkedlist.py
1,407
4.21875
4
#!/usr/bin/env python import sys class Node: def __init__(self, value=None, next=None): self.value = value self.next = next def __str__(self): return "[Node value=" + str(self.value) + "]" class SortedList: def __init__(self): self.head = None def insert(self, value): prev = None current = self.head while current is not None and current.value <= value: prev = current current = current.next new_node = Node(value, current) if prev is None: self.head = new_node else: prev.next = new_node def find(self, value): node = self.head while (node is not None): if node.value == value: return node node = node.next return None def __str__(self): string = "" node = self.head while (node is not None): string += str(node.value) if node.next is not None: string += ", " node = node.next return string def main(argv=None): list = SortedList() list.insert(5) list.insert(2) list.insert(7) list.insert(9) list.insert(4) list.insert(3) print list print "find 6:", list.find(6) print "find 7:", list.find(7) if __name__ == "__main__": sys.exit(main())
true
cdfbeaf2c417826e26dc3016f9d42916712fb341
luiscarm9/Data-Structures-in-Python
/DataStructures/LinkedList_def/Program.py
627
4.21875
4
from LinkedList_def.LinkedList import LinkedList; LList=LinkedList() #Insert Elements at the start (FATS) LList.insertStart(1) LList.insertStart(2) LList.insertStart(3) LList.insertStart(5) #Insert Elements at the end (SLOW) LList.insertEnd(8) LList.insertEnd(13) LList.insertEnd(21) LList.insertEnd(34) LList.insertEnd(55) LList.insertEnd(89) print("----------------------------------------------------------------------") #Print what is in our list LList.traverseList() print("----------------------------------------------------------------------") #Remove first element (FATS) LList.remove(55) LList.traverseList()
true
243b689861bcfa9dd4fd2ce32d7912aa8ba1c8b9
Priyanshuparihar/make-pull-request
/Python/2021/1stOct_KunalJaiswal-17.py
645
4.25
4
def is_prime(num): if num > 1: for i in range(2, num // 2 + 1): if (num % i) == 0: return False else: return True else: return False def fibonacci(num): num1, num2 = 1, 1 count = 0 if num == 1: print(num1) else: while count < num: if not is_prime(num1) and num1 % 5 != 0: print(num1, end=' ') else: print(0, end=' ') num3 = num1 + num2 num1 = num2 num2 = num3 count += 1 num = int(input()) fibonacci(num)
false
d5e2382900b729a2e3392882cf95a006a36e57b9
Priyanshuparihar/make-pull-request
/Python/2021/1stOct_IshaSah.py
835
4.34375
4
'''Take input the value of 'n', upto which you will print. -Print the Fibonacci Series upto n while replacing prime numbers, all multiples of 5 by 0. Sample Input : 12 27 Sample Output : 1 1 0 0 0 8 0 21 34 0 0 144 1 1 0 0 0 8 0 21 34 0 0 144 0 377 0 987 0 2584 4181 0 10946 17711 0 46368 0 121393 196418''' import math n=int(input()) n1=1 n2=1 count=0 def isprime(num): if num<=1: return False if num==2: return True if num>2 and num%2==0: return False x=int(math.sqrt(num)) for i in range(3,x,2): if(num%i==0): return False return True if n==1: print(n1) else: while (count<n): if not isprime(n1) and n1%5!=0: print(n1,end=' ') else: print(0,end=' ') sum=n1+n2 n1=n2 n2=sum count=count+1
true
82a0b63b6b46dbc1b0fb456cf23d1554814c3b04
Priyanshuparihar/make-pull-request
/Python/2021/1stOct_devulapallisai.py
922
4.1875
4
# First take input n # contributed by Sai Prachodhan Devulapalli Thanks for giving me a route # Program to find whether prime or not def primeornot(num): if num<2:return False else: #Just checking from 2,sqrt(n)+1 is enough reduces complexity too for i in range(2,int(pow((num),1/2)+1)): if num%i == 0: return False return True # Program to find multiple of 5 or not def multipleof5(n): if(n % 5 == 0): return True return False n = int(input('Enter the value of n please')) # Check whether n=0 or any invalid if(n <= 0): print('Enter a number greater than 1 because there are no zero terms :(') else: n1 = 0 n2 = 1 count=0 while(count < n): if(multipleof5(n2) or primeornot(n2)): print(0,end=" ") else: print(n2,end=" ") nth = n1 + n2 # update values n1 = n2 n2 = nth count=count+1
true
0319816ef3a65374eaa7dd895288b6eff0f42f4a
Priyanshuparihar/make-pull-request
/Python/2021/2ndOct_RolloCasanova.py
1,276
4.3125
4
# Function to print given string in the zigzag form in `k` rows def printZigZag(s, k): # Creates an len(s) x k matrix arrays = [[' ' for x in range (len(s))] for y in range (k)] # Indicates if we are going downside the zigzag down = True # Initialize the row and column to zero col, row = 0, 0 # Iterate over all word's letters for l in s[:]: arrays[row][col] = l # col always increases col = col + 1 # If going down, increase row if down: row = row + 1 # Already at the bottom? let's go up if row == k: row = k-2 down = False # If going up, decrease row else: row = row - 1 # Already at top, let's go down if row == -1: row = 1 down = True # Iterate over all k arrays in matrix for arr in arrays[:]: # Set str to empty string str = "" # Iterate over each letter in array for l in arr[:]: # Concatenate letters on array str = str + l # Print str print(str) # if __name__ == '__main__': # s = 'THISZIGZAGPROBLEMISAWESOME' # k = 3 # printZigZag(s, k)
true
5a840100907d0fe49012b75d8707ee142ba80738
Priyanshuparihar/make-pull-request
/Python/2021/2ndOct_Candida18.py
703
4.125
4
rows = int(input(" Enter the no. of rows : ")) cols = int(input(" Enter the no. of columns : ")) print("\n") for i in range(1,rows+1): print(" "*(i-1),end=" ") a = i while a<=cols: print(a , end="") b = a % (rows-1) if(b==0): b=(rows-1) a+=(rows-b)*2 print(" "*((rows-b)*2-1),end=" ") print("\n") """ Output: Enter the no. of rows : 7 Enter the no. of columns : 16 1 13 2 12 14 3 11 15 4 10 16 5 9 6 8 7 """
true
d2d56f7fc126004e97d41c53f9b3704d61978473
alexsmartens/algorithms
/stack.py
1,644
4.21875
4
# This stack.py implementation follows idea from CLRS, Chapter 10.2 class Stack: def __init__(self): self.items = [] self.top = 0 self.debug = True def is_empty(self): return self.top == 0 def size(self): return self.top def peek(self): if self.top > 0: return self.items[self.top - 1] else: return None def push(self, new_item): self.items.append(new_item) self.top += 1 if self.debug: self.print() def pop(self): if self.is_empty(): print("Attention: stack underflow") return None else: new_item = self.items[self.top - 1] self.items = self.items[:self.top - 1] # the last list item is not included self.top -= 1 if self.debug: self.print() return new_item def print(self): print(self.items) # Running simple examples myStack = Stack() print("is_empty: " + str(myStack.is_empty())) print("top: " + str(myStack.top)) myStack.push(15) myStack.push(6) myStack.push(2) myStack.push(9) print("is_empty: " + str(myStack.is_empty())) print("top: " + str(myStack.top)) myStack.push(17) myStack.push(3) print("size " + str(myStack.size())) print("peek " + str(myStack.peek())) myStack.pop() print("top: " + str(myStack.top)) myStack.pop() myStack.pop() myStack.pop() myStack.pop() print("top: " + str(myStack.top)) myStack.pop() print("top: " + str(myStack.top)) myStack.pop() myStack.pop()
true
58fa55150c3bc3735f3f63be5193eb2433eddd28
Catboi347/python_homework
/fridayhomework/homework78.py
211
4.1875
4
import re string = input("Type in a string ") if re.search("[a-z]", string): print ("This is a string ") elif re.search("[A-Z]", string): print ("This is a string") else: print ("This is an integer")
true
9bb7603cfd3c9595b0142a4f4d575b1c50d5e5bf
karngyan/Data-Structures-Algorithms
/String_or_Array/Sorting/Bubble_Sort.py
784
4.46875
4
# bubble sort function def bubble_sort(arr): n = len(arr) # Repeat loop N times # equivalent to: for(i = 0; i < n-1; i++) for i in range(0, n-1): # Repeat internal loop for (N-i)th largest element for j in range(0, n-i-1): # if jth value is greater than (j+1) value if arr[j] > arr[j+1]: # swap the values at j and j+1 index # Pythonic way to swap 2 variable values -> x, y = y, x arr[j], arr[j+1] = arr[j+1], arr[j] arr = [64, 34, 25, 12, 22, 11, 90] print('Before sorting:', arr) # call bubble sort function on the array bubble_sort(arr) print('After sorting:', arr) """ Output: Before sorting: [64, 34, 25, 12, 22, 11, 90] After sorting: [11, 12, 22, 25, 34, 64, 90] """
false
c3358ef21e7393f7f57fb5238cea8dc63bdf5729
karngyan/Data-Structures-Algorithms
/String_or_Array/Sorting/Selection_Sort.py
423
4.3125
4
# selection sort function def selection_sort(arr): n = len(arr) for i in range(0, n): for j in range(i+1, n): # if the value at i is > value at j -> swap if arr[i] > arr[j]: arr[i], arr[j] = arr[j], arr[i] # input arr arr = [3, 2, 4, 1, 5] print('Before selection sort:', arr) # call selection sort function selection_sort(arr) print('After selection sort:', arr)
false
5e0bf04f50e383157a0f4d476373353342f3385e
karngyan/Data-Structures-Algorithms
/Tree/BinaryTree/Bottom_View.py
1,305
4.125
4
# Print Nodes in Bottom View of Binary Tree from collections import deque class Node: def __init__(self, data): self.data = data self.left = None self.right = None def bottom_view(root): if root is None: return # make an empty queue for BFS q = deque() # dict to store bottom view keys bottomview = {} # append root in the queue with horizontal distance as 0 q.append((root, 0)) while q: # get the element and horizontal distance elem, hd = q.popleft() # update the last seen hd element bottomview[hd] = elem.data # add left and right child in the queue with hd - 1 and hd + 1 if elem.left is not None: q.append((elem.left, hd - 1)) if elem.right is not None: q.append((elem.right, hd + 1)) # return the bottomview return bottomview if __name__ == '__main__': root = Node(20) root.left = Node(8) root.right = Node(22) root.left.left = Node(5) root.left.right = Node(3) root.right.left = Node(4) root.right.right = Node(25) root.left.right.left = Node(10) root.left.right.right = Node(14) bottomview = bottom_view(root) for i in sorted(bottomview): print(bottomview[i], end=' ')
true
8fd74242f802dd8438d622312f8bfd0f246826cc
karngyan/Data-Structures-Algorithms
/String_or_Array/Sorting/Insertion_Sort.py
567
4.34375
4
def insertion_sort(arr): n = len(arr) for i in range(1, n): x = arr[i] j = i - 1 while j >= 0 and arr[j] > x: # copy value of previous index to index + 1 arr[j + 1] = arr[j] # j = j - 1 j -= 1 # copy the value which was at ith index to its correct sorted position arr[j + 1] = x arr = [12, 11, 13, 5, 6] print('Before sort arr: ', arr) insertion_sort(arr) print('Sorted arr: ', arr) """ Output: Before sort arr: [12, 11, 13, 5, 6] Sorted arr: [5, 6, 11, 12, 13] """
false
487d70507adea1986e7c35271ced0d4f702f1897
karngyan/Data-Structures-Algorithms
/String_or_Array/Searching/Linear_Search.py
480
4.125
4
# Function for linear search # inputs: array of elements 'arr', key to be searched 'x' # returns: index of first occurrence of x in arr def linear_search(arr, x): # traverse the array for i in range(0, len(arr)): # if element at current index is same as x # return the index value if arr[i] == x: return i # if the element is not found in the array return -1 return -1 arr = [3, 2, 1, 5, 6, 4] print(linear_search(arr, 1))
true
1643160b78a5aefdb07225a4fa6ab56c11bcdcc7
ashwini-8/PythonUsing_OOP_Concept
/dictionariesImplementation.py
1,183
4.28125
4
d ={101:"Ashwini", 103:"Jayashree" , 104:"Rajkumar" ,102:"Abhijit" , 105:"Patil"} #created dict print(d) print(list(d)) #print list of keys print(sorted(d)) #print keys in sorted order print(d[101]) #accessing element using key print(d[104]) Dict1 = {} # empty dict print("empty dictionary") print(Dict1) Dict1[0] = "bksub" #updated the value Dict2 = dict({101:"Ashwini", 103:"Jayashree" , 104:"Rajkumar"}) #created dict using dict method print(Dict2) Dict3 = {1: 'Rajkumar', 2: 'Jayshree', 3:{'A' : 'Ashwini', 'B' : 'Abhijit', 'C' : 'Mithoo'}} #nested dictionaries print(Dict3) Dict3[4] = "ksihrhi" #updated an element print(Dict3) print(Dict3.get(3)) # Accessig element using get method #del Dict3[4] # deleting #print(Dict3) #print(Dict3.pop(4)) #popping #print(Dict3) print(Dict3.popitem()) #popping key and value both print(Dict3)
false
8cd285463fa90df622467e4b634e03e3d738b052
VinicciusSantos/CeV-Python
/Mundo1/ex008.py
277
4.1875
4
# Escreva um programa que leia um valor em metros e o exiba convertido em centímetros e milímetros. m = float(input("Digite uma distância em metros: ")) print(f'{m/1000}Km') print(f'{m/100}hm') print(f'{m/10}dam') print(f'{m*10}dm') print(f'{m*100}cm') print(f'{m*1000}mm')
false
674ba225acb3cb441f1dfbd4d32a8713cfc8ba9a
VinicciusSantos/CeV-Python
/Mundo1/ex022.py
504
4.15625
4
# Crie um programa que leia o nome completo de uma pessoa e mostre: # – O nome com todas as letras maiúsculas e minúsculas. # – Quantas letras ao todo (sem considerar espaços). # – Quantas letras tem o primeiro nome. nome = str(input('Qual o seu nome? ')).strip() print(f'Seu nome em letras maiúsculas: {nome.upper()}') print(f'Seu nome em letras maiúsculas: {nome.lower()}') print(f'Seu nome tem ao todo {len(nome) - nome.count(" ")} letras') print(f'Seu primeiro nome tem {nome.find(" ")}')
false
d87e3ccfe1dcebc2ba0e3d030b0704c68b52d684
dominiquecuevas/dominiquecuevas
/05-trees-and-graphs/second-largest.py
1,720
4.21875
4
class BinaryTreeNode(object): def __init__(self, value): self.value = value self.left = None self.right = None def insert_left(self, value): self.left = BinaryTreeNode(value) return self.left def insert_right(self, value): self.right = BinaryTreeNode(value) return self.right ''' go right if has a right attr, copy value of previous Node if current has a left, reassign value and return it else go left and reassign value to current and return ''' def find_largest(node): if node.right: return find_largest(node.right) return node.value def second_largest(node): ''' >>> root = BinaryTreeNode(5) >>> ten = root.insert_right(10) >>> seven = ten.insert_left(7) >>> eight = seven.insert_right(8) >>> six = seven.insert_left(6) >>> find_largest(root) 10 >>> second_largest(root) 8 5 10 7 6 8 >>> root = BinaryTreeNode(5) >>> three = root.insert_left(3) >>> two = three.insert_left(2) >>> four = three.insert_right(4) >>> find_largest(root) 5 >>> second_largest(root) 4 5 3 2 4 ''' if node.left and not node.right: return find_largest(node.left) if node.right and not node.right.left and not node.right.right: return node.value return second_largest(node.right) # time complexity is O(h) and space is O(h) # cut down to O(n) space if didn't use recursion if __name__ == '__main__': import doctest if doctest.testmod(verbose=True).failed == 0: print('ALL TESTS PASSED')
true
ad6fc102c4ad03ca32dc29b84cdffb1d6108147e
VitaliiUr/wiki
/wiki
2,978
4.15625
4
#!/usr/bin/env python3 import wikipedia as wiki import re import sys import argparse def get_random_title(): """ Find a random article on the Wikipadia and suggests it to user. Returns ------- str title of article """ title = wiki.random() print("Random article's title:") print(title) ans = input( "Do you want to read it?\n (Press any key if yes or \"n\" if you want to see next suggestion)\n\ Press \"q\" to quit") if ans in ("n", "next"): return get_random_title() elif ans == "q": print("sorry for that") sys.exit(0) else: return title def search_title(search): """ Looks for the article by title Parameters ---------- search : str query for the search Returns ------- str title of the article """ titles = wiki.search(search) print(">>> We found such articles:\n") print(*[f"\"{t}\","for t in titles[:5]], "\n") for title in titles: print(">>> Did you mean \"{}\"?\n Press any key if yes or \"n\"".format(title), "if you want to see next suggestion") ans = input("Press \"q\" to quit") if ans in ("n", "next"): continue elif ans == "q": print(">>> Sorry for that. Bye") sys.exit(0) else: return title def split_paragraphs(text): # Remove bad symbols text = re.sub(r"\s{2,}", " ", text.strip()) text = re.sub(r"\n{2,}", "\n", text) # Split article to the paragraphs pat = re.compile( r"(?:(?:\s?)(?:={2,})(?:\s*?)(?:[^=]+)(?:\s*?)(?:={2,}))") paragraphs = pat.split(text) # Get titles of the paragraphs pat2 = re.compile( r"(?:(?:\s?)(?:={2,})(?:\s?)([^=]+)(?:\s?)(?:={2,}))") titles = list(map(lambda x: x.strip(), ["Summary"] + pat2.findall(text))) # Create a dictionary of the paragraphs and return it result = dict(zip(titles, paragraphs)) if "References" in result: del result["References"] return result if __name__ == "__main__": # Get arguments parser = argparse.ArgumentParser() parser.add_argument("search", type=str, nargs='?', help="search wiki article by title") args = parser.parse_args() if args.search: name = search_title(args.search) # search article by title else: name = get_random_title() # get random article if name: print(">>> Article is loading. Please, wait...") page = wiki.page(name) else: print(">>> Please, try again") sys.exit(0) paragraphs = split_paragraphs(page.content) print("\n===== ", name, " =====") for title in paragraphs: print("\n") print("=== ", title, " ===") print(paragraphs[title]) ans = input( "Press any key to proceed, \"q\" to quit") if ans == "q": sys.exit(0)
true
b2b22e8264799467c43b2051c63228d1304533f6
rdcorrigan/bmiCalculatorApp
/bmi_calculator.py
1,070
4.125
4
# BMI Calculator # by Ryan # Python 3.9 using Geany Editor # Windows 10 # BMI = weight (kilograms) / height (meters) ** 2 import tkinter # toolkit interface root = tkinter.Tk() # root.geometry("300x150") // OPTIONAL root.title("BMI Calculator") # Create Function(s) def calculate_bmi(): weight = float(entry_weight.get()) height = float(entry_height.get()) bmi = round(weight / (height ** 2), 2) label_result['text'] = f"BMI: {bmi}" # Create GUI (Graphical User Interface) label_weight = tkinter.Label(root, text="WEIGHT (KG): ") label_weight.grid(column=0, row=0) entry_weight = tkinter.Entry(root) entry_weight.grid(column=1, row=0) label_height = tkinter.Label(root, text="HEIGHT (M): ") label_height.grid(column=0, row=1) entry_height = tkinter.Entry(root) entry_height.grid(column=1, row=1) button_calculate = tkinter.Button(root, text="Calculate", command=calculate_bmi) button_calculate.grid(column=0, row=2) label_result = tkinter.Label(root, text="BMI: ") label_result.grid(column=1, row=2) root.mainloop()
false
80d0e021194a67ff06851523210bc9f7ca635833
jimboowens/python-practice
/dictionaries.py
1,131
4.25
4
# this is a thing about dictionaries; they seem very useful for lists and changing values. # Dictionaries are just like lists, but instead of numbered indices they have english indices. # it's like a key greg = [ "Greg", "Male", "Tall", "Developer", ] # This is not intuitive, and the placeholders give no indication as to what they represent # Key:value pair greg = { "name": "Greg", "gender": "Male", "height": "Tall", "job": "Developer", } # make a new dictionary zombie = {}#dictionary zombies = []#list zombie['weapon'] = "fist" zombie['health'] = 100 zombie['speed'] = 10 print zombie # zombie stores the items it comprises in random order. print zombie ['weapon'] for key, value in zombie.items():#key is basically an i, and I don't get how it iterated because both change...? print "zombie has a key of %s with a value of %s" % (key, value) zombies.append({ 'name': "Hank", 'weapon': "baseball bat", 'speed': 10 }) zombies.append({ 'name': "Willy", 'weapon': "axe", 'speed': 3, 'victims': ['squirrel', 'rabbit', 'Hank'] }) print zombies[1]['victims'][1]
true
28914773c6065a3d262aa995274281503d42cca4
Finveon/PythonLern
/lesson_2_15.py
478
4.34375
4
#1 print ("1) My name is {}".format("Alexandr")) #2 my_name = "Alexandr" print("2) My name is {}".format(my_name)) #3 print("3) My name is {} and i'm {}".format(my_name, 38)) #4 print("4) My name is {0} and i'm {1}".format(my_name, 38)) #5 print("5) My name is {1} and i'm {0}".format(my_name, 38)) #6 pi = 3.1415 print("6) Pi equals {pi:1.2f}".format(pi=pi)) #7 name = "Alexandr" age = 38 print(f"7) My name is {name} and I'm {age}") #8 print(f"8) Pi equals {pi:1.2f}")
false
735222b563750bceca379969e5cff58224ddf83e
nlin24/python_algorithms
/BinaryTrees.py
1,982
4.375
4
class BinaryTree: """ A simple binary tree node """ def __init__(self,nodeName =""): self.key = nodeName self.rightChild = None self.leftChild = None def insertLeft(self,newNode): """ Insert a left child to the current node object Append the left child of the current node to the new node's left child """ if self.leftChild == None: self.leftChild = BinaryTree(newNode) else: t = BinaryTree(newNode) t.leftChild = self.leftChild self.leftChild = t def insertRight(self, newNode): """ Insert a right child to the current node object Append the right child of the current node to the new node's right child """ if self.rightChild == None: self.rightChild = BinaryTree(newNode) else: t = BinaryTree(newNode) t.rightChild = self.rightChild self.rightChild = t def getRightChild(self): """ Return the right child of the root node """ return self.rightChild def getLeftChild(self): """ Return the left child of the root node """ return self.leftChild def setRootValue(self,newValue): """ Set the value of the root node """ self.key = newValue def getRootValue(self): """ Return the key value of the root node """ return self.key if __name__ == "__main__": r = BinaryTree('a') print(r.getRootValue()) #a print(r.getLeftChild()) #None r.insertLeft('b') print(r.getLeftChild()) #binary tree object print(r.getLeftChild().getRootValue()) #b r.insertRight('c') print(r.getRightChild()) #binary tree object print(r.getRightChild().getRootValue()) #c r.getRightChild().setRootValue('hello') print(r.getRightChild().getRootValue()) #hello
true
d22dd3d84f34487598c716f13af578c3d2752bc4
aduV24/python_tasks
/Task 19/example.py
1,720
4.53125
5
#************* HELP ***************** #REMEMBER THAT IF YOU NEED SUPPORT ON ANY ASPECT OF YOUR COURSE SIMPLY LEAVE A #COMMENT FOR YOUR MENTOR, SCHEDULE A CALL OR GET SUPPORT OVER EMAIL. #************************************ # =========== Write Method =========== # You can use the write() method in order to write to a file. # The syntax for this method is as follows: # file.write("string") - writes "string" to the file # ************ Example 1 ************ # Before you can write to a file you need to open it. # You open a file using Python's built-in open() function which creates a file called output.txt (it doesn't exist yet) in write mode. # Python will create this file in the directory/folder that our program is automatically. ofile = open('output.txt', 'w') # We ask the user for their name. When they enter it, it is stored as a String in the variable name. name = input("Enter your name: ") # We use the write method to write the contents of the variable name to the text file, which is represented by the object ofile. # Remember, you will learn more about objects later but for now, think of an object as similar to a real-world object # such as a book, apple or car that can be distinctly identified. ofile.write(name+"\n") # You must run this Python file for the file 'output.txt' to be created with the output from this program in it. ofile.write("My name is on the line above in this text file.") # When we write to the file again, the current contents of the file will not be overwritten. # The new string will be written on the second line of the text file. ofile.close() # Don't forget to close the file! # ****************** END OF EXAMPLE CODE ********************* #
true
473237b007ea679c7b55f3c4c7b5895bdf150ae5
aduV24/python_tasks
/Task 11/task2.py
880
4.34375
4
shape = input("Enter the shape of the builing(square,rectangular or round):\n") if shape == "square": length = float(input("Enter the length of one side:\n")) area = round(length**2,2) print(f"The area that will be taken up by the building is {area}sqm") #=================================================================================# elif shape == "rectangle": length = float(input("Enter the length of one side:\n")) width =float(input("Enter the width:\n")) area = round(length*width,2) print(f"The area that will be taken up by the building is {area}sqm") #=================================================================================# elif shape == "round": import math radius = float(input("Enter the radius:\n")) area = round((math.pi)*(radius**2),2) print(f"The area that will be taken up by the building is {area}sqm")
true
3427a7d78131b4d26b633aa5f70e2dc7a7dab748
aduV24/python_tasks
/Task 17/disappear.py
564
4.78125
5
# This program asks the user to input a string, and characters they wish to # strip, It then displays the string without those characters. string = input("Enter a string:\n") char = input("Enter characters you'd like to make disappear separated by a +\ comma:\n") # Split the characters given into a list and loop through them for x in char.split(","): # Check if character is in string and replace it if x in string: string = string.replace(x, "") else: print(f"'{x}' is not in the string given") print("\n" + string)
true
55d2392b17d505045d5d80d209dc5635c47657f6
aduV24/python_tasks
/Task 17/separation.py
298
4.4375
4
# This program asks the user for a sentence and then displays # each character of that senetence on a new line string = input("Enter a sentence:\n") # split string into a list of words words = string.split(" ") # Iterate thorugh the string and print each word for word in words: print(word)
true
28488c65d5d977cb9b48772d64be224bdce8d0bf
aduV24/python_tasks
/Task 11/task1.py
702
4.25
4
num1 =60 num2 = 111 num3 = 100 if num1 > num2: print(num1) else: print(num2) print() if num1 % 2 == 0: print("The first number is even") else: print("The first number is odd") print() print("Numbers in descending order") print("===================================") if (num1 > num2) and (num1 > num3 ): if num2 > num3: print(f"{num1}\n{num2}\n{num3}") else: print(f"{num1}\n{num3}\n{num2}") elif (num2 > num1) and (num2 > num3 ): if num1 > num3: print(f"{num2}\n{num1}\n{num3}") else: print(f"{num2}\n{num3}\n{num1}") else: if num1 > num2: print(f"{num3}\n{num1}\n{num2}") else: print(f"{num3}\n{num2}\n{num1}")
false
40df8c8aa7efb4fc8707f712b94971bae08dacea
aduV24/python_tasks
/Task 21/john.py
344
4.34375
4
# This program continues to ask the user to enter a name until they enter "John" # The program then displays all the incorrect names that was put in wrong_inputs = [] name = input("Please input a name:\n") while name != "John": wrong_inputs.append(name) name = input("Please input a name:\n") print(f"Incorrect names:{wrong_inputs}")
true
aa382979b4f5bc4a8b7e461725f59a802ffe3a4e
aduV24/python_tasks
/Task 14/task1.py
340
4.59375
5
# This python program asks the user to input a number and then displays the # times table for that number using a for loop num = int(input("Please Enter a number: ")) print(f"The {num} times table is:") # Initialise a loop and print out a times table pattern using the variable for x in range(1,13): print(f"{num} x {x} = {num * x}")
true
ab8491166133deadd98d2bbbbb40775f95c7091b
aduV24/python_tasks
/Task 24/Example Programs/code_word.py
876
4.28125
4
# Imagine we have a long list of codewords and each codeword triggers a specific function to be called. # For example, we have the codewords 'go' which when seen calls the function handleGo, and another codeword 'ok' which when seen calls the function handleOk. # We can use a dictionary to encode this. def handleGo(x): return "Handling a go! " + x def handleOk(x): return "Handling an ok!" + x # This is dictionary: codewords = { 'go': handleGo, # The KEY here is 'go' and the VALUE it maps to is handleGo (Which is a function!). 'ok': handleOk, } # This dictionary pairs STRINGS (codewords) to FUNCTIONS. # Now, we see a codeword given to us: codeword = "go" # We can handle it as follows: if codeword in codewords: answer = codewords[codeword]("Argument") print(answer) else: print("I don't know that codeword.")
true
ee04a317415c9a0c9481f712e8219c92fb719ce0
hackettccp/CIS106
/SourceCode/Module2/formatting_numbers.py
1,640
4.65625
5
""" Demonstrates how numbers can be displayed with formatting. The format function always returns a string-type, regardless of if the value to be formatted is a float or int. """ #Example 1 - Formatting floats amount_due = 15000.0 monthly_payment = amount_due / 12 print("The monthly payment is $", monthly_payment) #Formatted to two decimal places print("The monthly payment is $", format(monthly_payment, ".2f")) #Formatted to two decimal places and includes commas print("The monthly payment is $", format(monthly_payment, ",.2f")) print("The monthly payment is $", format(monthly_payment, ',.2f'), sep="") #********************************# print() #Example 2 - Formatting ints """ weekly_pay = 1300 annual_salary = weekly_pay * 52 print("The annual salary is $", annual_salary) print("The annual salary is $", format(annual_salary, ",d")) print("The annual salary is $", format(annual_salary, ",d"), sep="") """ #********************************# print() #Example 3 - Scientific Notation """ distance = 567.465234 print("The distance is", distance) print("The distance is", format(distance, ".5e")) """ #********************************# print() #Example 4 - Formatting floats # This example displays the following # floating-point numbers in a column # with their decimal points aligned. """ num1 = 127.899 num2 = 3465.148 num3 = 3.776 num4 = 264.821 num5 = 88.081 num6 = 799.999 # Display each number in a field of 7 spaces # with 2 decimal places. print(format(num1, '7.2f')) print(format(num2, '7.2f')) print(format(num3, '7.2f')) print(format(num4, '7.2f')) print(format(num5, '7.2f')) print(format(num6, '7.2f')) """
true
3d2c8b1c05332e245a7d3965762b2a746d6e5c3d
hackettccp/CIS106
/SourceCode/Module4/loopandahalf.py
899
4.21875
4
""" Demonstrates a Loop and a Half """ #Creates an infinite while loop while True : #Declares a variable named entry and prompts the user to #enter the value z. Assigns the user's input to the entry variable. entry = input("Enter the value z: ") #If the value of the entry variable is "z", break from the loop if entry == "z" : break #Prints the text "Thank you!" print("Thank you!") #********************************# print() """ #Creates an infinite while loop while True: #Declares a variable named userNum and prompt the user #to enter a number between 1 and 10. #Assigns the user's input to the user_number variable. user_number = int(input("Enter a number between 1 and 10: ")) #If the value of the userNumber variable is correct, break from the loop if user_number >= 1 and user_number <= 10 : break #Prints the text "Thank you!" print("Thank you!") """
true
824f4f86eaef9c87c082c0f471cb7a68cc72a44f
hackettccp/CIS106
/SourceCode/Module2/converting_floats_and_ints.py
1,055
4.71875
5
""" Demonstrates converting ints and floats. Uncomment the other section to demonstrate the conversion of float data to int data. """ #Example 1 - Converting int data to float data #Declares a variable named int_value1 and assigns it the value 35 int_value1 = 35 #Declares a variable named float_value1 and assigns it #int_value1 returned as a float float_value1 = float(int_value1) #Prints the value of int_value1. The float function did not change #the variable, its value, or its type. print(int_value1) #Prints the value of float_value1. print(float_value1) #********************************# print() #Example 2 - Converting float data to int data """ #Declares a variable named float_value2 and assigns it the value 23.8 float_value2 = 23.8 #Declares a variable named int_value2 and assigns it #float_value2 returned as an int int_value2 = int(float_value2) #Prints the value of float_value2. The int function did not change #the variable, its value, or its type. print(float_value2) #Prints the value of int_value2 print(int_value2) """
true
98868a37e12fc16d5a1e0d49cb8e076a5ffb107d
hackettccp/CIS106
/SourceCode/Module10/button_demo.py
866
4.15625
4
#Imports the tkinter module import tkinter #Imports the tkinter.messagebox module import tkinter.messagebox #Main Function def main() : #Creates the window test_window = tkinter.Tk() #Sets the window's title test_window.wm_title("My Window") #Creates button that belongs to test_window that #calls the showdialog function when clicked. test_button = tkinter.Button(test_window, text="Click Me!", command=showdialog) #Packs the button onto the window test_button.pack() #Enters the main loop, displaying the window #and waiting for events tkinter.mainloop() #Function that displays a dialog box when it is called. def showdialog() : tkinter.messagebox.showinfo("Great Job!", "You pressed the button.") #Calls the main function/starts the program main()
true