blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
1ba7db67af680cd2ee96252009f47fe72fe1ecc7 | saurabhgupta2104/Coding_solutions | /GFG/Max_length_chain.py | 1,409 | 4.375 | 4 | # https://practice.geeksforgeeks.org/problems/max-length-chain/1
"""
You are given N pairs of numbers. In every pair, the first number is always smaller than the second number. A pair (c, d) can follow another pair (a, b) if b < c. Chain of pairs can be formed in this fashion. You have to find the longest chain which can be formed from the given set of pairs.
Example 1:
Input:
N = 5
P[] = {5 24 , 39 60 , 15 28 , 27 40 , 50 90}
Output: 3
Explanation: The given pairs are { {5, 24}, {39, 60},
{15, 28}, {27, 40}, {50, 90} },the longest chain that
can be formed is of length 3, and the chain is
{{5, 24}, {27, 40}, {50, 90}}
Example 2:
Input:
N = 2
P[] = {5 10 , 1 11}
Output: 1
Explanation:The max length chain possible is only of
length one.
Your Task:
You don't need to read input or print anything. Your task is to Complete the function maxChainLen() which takes a structure p[] denoting the pairs and n as the number of pairs and returns the length of the longest chain formed.
Expected Time Complexity: O(N*N)
Expected Auxiliary Space: O(N)
Constraints:
1<=N<=100
"""
def maxChainLen(p, n):
# Parr: list of pair
#code here
x = []
for i in p:
x.append([i.a, i.b])
x, p = zip(*sorted(zip(x, p)))
l = [1]*n
for i in range(1, n):
for j in range(i):
if p[i].a>p[j].b:
l[i] = max(l[i], l[j]+1)
return(max(l))
| true |
78667fe4120d3841a37ec730a133afad52da244e | saurabhgupta2104/Coding_solutions | /GFG/Merge_two_sorted_linked_lists.py | 1,426 | 4.1875 | 4 | # https://practice.geeksforgeeks.org/problems/merge-two-sorted-linked-lists/1
"""
Given two sorted linked lists consisting of N and M nodes respectively. The task is to merge both of the list (in-place) and return head of the merged list.
Note: It is strongly recommended to do merging in-place using O(1) extra space.
Example 1:
Input:
N = 4, M = 3
valueN[] = {5,10,15,40}
valueM[] = {2,3,20}
Output: 2 3 5 10 15 20 40
Explanation: After merging the two linked
lists, we have merged list as 2, 3, 5,]
10, 15, 20, 40.
Example 2:
Input:
N = 2, M = 2
valueN[] = {1,1}
valueM[] = {2,4}
Output:1 1 2 4
Explanation: After merging the given two
linked list , we have 1, 1, 2, 4 as
output.
Your Task:
The task is to complete the function sortedMerge() which takes references to the heads of two linked lists as the arguments and returns the head of merged linked list.
Expected Time Complexity : O(n+m)
Expected Auxilliary Space : O(1)
Constraints:
1 <= N, M <= 104
1 <= Node's data <= 105
"""
def sortedMerge(a, b):
# code here
h = None
if a.data < b.data:
h = a
a = a.next
else:
h = b
b = b.next
start = h
while(a and b):
if a.data < b.data:
h.next = a
a = a.next
else:
h.next = b
b = b.next
h = h.next
if a is None:
h.next = b
else:
h.next = a
return start
| true |
fc6a234884e527ecb71f0ce9bf1fa5c728c25ece | saurabhgupta2104/Coding_solutions | /GFG/Length_of_the_longest_substring.py | 981 | 4.25 | 4 | # https://practice.geeksforgeeks.org/problems/length-of-the-longest-substring/0
"""
Given a string, find the length of the longest substring without repeating characters. For example, the longest substrings without repeating characters for “ABDEFGABEF” are “BDEFGA” and “DEFGAB”, with length 6.
Input:
The first line of input contains an integer T denoting the number of test cases.
The first line of each test case is str.
Output:
Print the length of longest substring.
Constraints:
1 ≤ T ≤ 20
1 ≤ str ≤ 50
Example:
Input:
2
geeksforgeeks
qwertqwer
Output:
7
5
"""
#code
for _ in range(int(input())):
s = input()
d = {}
ind = {}
mc = 0
count = 0
frm = 0
for i in range(len(s)):
if s[i] not in d:
d[s[i]] = 1
elif ind[s[i]] >= frm:
frm = ind[s[i]]
count = i-frm-1
ind[s[i]] = i
count += 1
mc = max(mc, count)
print(mc)
| true |
fffc9c77e21587a8143ce322aa0e1b8e2685b1dc | zhaochuanshen/leetcode | /Reverse_Linked_List_II.py | 1,304 | 4.15625 | 4 | '''
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,
return 1->4->3->2->5->NULL.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
'''
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param head, a ListNode
# @param m, an integer
# @param n, an integer
# @return a ListNode
def reverse(self, head):
if not head or not head.next:
return head
prev = None
c = head
while c:
nn = c.next
c.next = prev
prev = c
c = nn
return prev
def reverseBetween(self, head, m, n):
dummy = ListNode(x = -999)
dummy.next = head
t = dummy
num = 0
while num < m:
s = t
t = t.next
num += 1
beforem = s
atm = t
while num < n:
t = t.next
num += 1
atn = t
aftern = t.next
atn.next = None
beforem.next = self.reverse(atm)
atm.next = aftern
return dummy.next
| true |
7eb4f90c27b800640dcbe574b86b94f618bc47e9 | zhaochuanshen/leetcode | /Largest_Number.py | 637 | 4.125 | 4 | '''
Given a list of non negative integers, arrange them such that they form the largest number.
For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.
Note: The result may be very large, so you need to return a string instead of an integer.
'''
class Solution:
# @param num, a list of integers
# @return a string
def largestNumber(self, num):
def _compare(a, b):
if a + b < b + a:
return 1
if a + b == b + a:
return 0
return -1
s = map(str, num)
s.sort(cmp = _compare)
return str( int("".join(s)) )
| true |
5319cd3f4e059bce3838e9dea983d983281f7d10 | zhaochuanshen/leetcode | /Valid_Palindrome.py | 1,098 | 4.15625 | 4 | '''
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.
Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.
'''
class Solution:
# @param s, a string
# @return a boolean
def isPalindrome(self, s):
#re.sub(r'\W+', '', your_string)
if not s:
return True
slow = s.lower()
strippedlist = []
for i in xrange(len(slow)):
if (slow[i] <= 'z' and slow[i] >= 'a' ) or (slow[i] <= '9' and slow[i] >= '0' ):
strippedlist.append(slow[i])
else:
continue
#stripped = ''.join(strippedlist)
L = len(strippedlist)
for i in xrange(L/2):
if strippedlist[i] != strippedlist[L-i-1]:
return False
return True
| true |
fc703f8a8fe9905a6bfc555795779acd88bc6338 | DanielMevs/Ascending-Sort-with-Python | /ascendingSort.py | 505 | 4.15625 | 4 | def swap(arr,x,y):
temp = arr[x]
arr[x] = arr[y]
arr[y] = temp
def ascendingSort(arr, N):
print("Original array: ", arr)
n = N-1
count = 0
j = 0
while(n):
print ("n: ",n)
temp = 0
for i in range(1,n+1):
if(arr[i-1] > arr[i]):
swap(arr, i-1, i)
temp = i
j = j +1
print(i, " ", arr)
n=temp
print( j)
arr = [5,4,3,6,7,2]
ascendingSort(arr, len(arr))
| false |
48f29cbde85447ef32602bd2f9bcbc9791f60ab9 | BlackHat-Ashura/Data-Structures-And-Algorithms | /Sorting/Insertion_Sort.py | 935 | 4.5 | 4 | def InsertionSort(ar):
length = len(ar)
for i in range(1, length):
'''
"first" is assigned the second element as the first element is already taken as sorted.
'''
first = ar[i]
j = i-1
'''
"j" moves from last element of sorted values to first element of sorted values.
Example:
ar = [3, 2, 1, 4, 5, 9, 8, 7, 6]
first = 2
2 < 3 --> ar = [3, 3, 1, 4, 5, 9, 8, 7, 6] --> ar = [2, 3, 1, 4, 5, 9, 8, 7, 6]
first = 1
1 < 3 --> ar = [2, 3, 3, 4, 5, 9, 8, 7, 6]
1 < 2 --> ar = [2, 2, 3, 4, 5, 9, 8, 7, 6] --> ar = [1, 2, 3, 4, 5, 9, 8, 7, 6]
so on...
'''
while j >= 0 and first < ar[j]:
ar[j+1] = ar[j]
j -= 1
ar[j+1] = first
ar = [3, 2, 1, 4, 5, 9, 8, 7, 6]
InsertionSort(ar)
print(ar)
| true |
2ae206f77d6111202d4688c53a8b1fedbddf5961 | daiyunchao/stupid_way_learn_python | /笨办法学python/ex_25.py | 1,799 | 4.40625 | 4 | #coding=utf-8
# 更多更多的练习
def break_word(stuff):
""" This function will break up words for us."""
words=stuff.split(' ')
return words
def sort_words(words):
""" Sorts the words."""
return sorted(words)
def print_first_word(words):
"""Prints the first word after popping it off."""
word=words.pop(0)
print word
def print_last_word(words):
"""Print the last word after popping it off."""
word=words.pop(-1)
print word
def sort_sentence(sentence):
"""Takes in a full sentence and returns the sorted words."""
words=break_word(sentence)
return sort_words(words)
def print_first_and_last(sentence):
"""Print the first and last words of the sentence."""
words=break_word(sentence)
print_first_word(words)
print_last_word(words)
def print_first_and_last_sorted(sentence):
"""Sorts the words then prints the first and last one."""
words=sort_sentence(sentence)
print_first_word(words)
print_last_word(words)
# 执行:
# import 导入模块 脚本的名称 名字不能是纯数字 不加后缀
# 导入模块中的方法 可以直接被调用
# import ex_25
# python的文档注释
# def 中的 """Sorts the words then prints the first and last one.""" 部分
# 打印文档注释
# help(ex_25.print_first_and_last_sorted)
# 将 ex_25的全部方法导入
# from ex_25 import *
# 执行模块中的方法 文件名.方法名(参数)
# ex_25.break_word(sentence)
# 学习到的方法:
# str.split(' ') 字符串通过 ' '分隔,分隔后的成为一个数组
# array.sorted() 数组排序
# array.pop(0) 移除数组中的一个值,并返回
# array.pop(-1) 移除数组中的最后一个值,并返回
# 导入自定义模块到python中 import 文件名
# 执行自定义模块的方法 文件名.方法名(参数)
# 退出python exit()
| true |
6f00ddb3cd2ba5fa3c914eda500bfffcb82c728a | JeffersonKaioSouza/Calculadora-While | /Calculadora_while.py | 715 | 4.125 | 4 | # Calculadora usando laço de repetição
while True:
print()
sair = input('Deseja sair?: [s]im ou [n]ão: ')
num1 = input('Digite um número: ')
num2 = input('Digite outro número: ')
operador = input('Digite o Operador ( + - / * ): ')
if sair == 's':
break
if not num1.isnumeric() or not num2.isnumeric():
print('Voce precisa digitar um número. ')
continue
num1 = int(num1)
num2 = int(num2)
if operador == '+':
print(num1 + num2)
elif operador == '-':
print(num1 - num2)
elif operador == '/':
print(num1 / num2)
elif operador == '*':
print(num1 * num2)
else:
print('Operador invalido!') | false |
5b3f1eae23fc46f324cf5206e86374af0014b7b7 | lijianbo0130/My_Python | /python2_Grammer/src/basic/grammer_complex/1_拷贝/1_引用.py | 1,021 | 4.125 | 4 | #coding=utf-8
'''
基本问题讲解 引用
'''
'''
可以说 Python 没有赋值,只有引用。你这样相当于创建了一个引用自身的结构,
所以导致了无限循环。为了理解这个问题,有个基本概念需要搞清楚。
Python 没有「变量」,我们平时所说的变量其实只是「标签」,是引用。
'''
# values = [0, 1, 2]
# values[1] = values
# print values #[0, [...], 2]
'''
执行 values = [0, 1, 2]
的时候,Python 做的事情是首先创建一个列表对象 [0, 1, 2],然后给它贴上名为 values 的标签。
如果随后又执行 values = [3, 4, 5]的话,Python 做的事情是创建另一个列表对象 [3, 4, 5],
然后把刚才那张名为 values 的标签从前面的 [0, 1, 2] 对象上撕下来,重新贴到 [3, 4, 5]
这个对象上。 至始至终,并没有一个叫做 values的列表对象容器存在,
Python 也没有把任何对象的值复制进 values 去。
'''
a = [1,2,3]
b=a
print b is a # a b为同一个对象
| false |
b71a00a371ef7898d5c44e25af875ff8c09ebf2c | rinoguchi/python_sandbox | /src/multiprocessing/server_process_ng_case1.py | 721 | 4.125 | 4 | """
サーバプロセスで管理するオブジェクトを取得して、
そのインスタンス変数を変更してもサーバプロセス上のオブジェクトには反映されない
"""
from multiprocessing import Manager
from typing import List
import dataclasses
MAX_WORKERS = 3
@dataclasses.dataclass
class Num:
num: int
def main():
with Manager() as manager:
nums: List[Num] = manager.list()
nums.append(Num(1))
num_before = nums[0]
print(f'num_before: {num_before.num}')
num_before.num = 9
print(f'num_before: {num_before.num}')
num_after = nums[0]
print(f'num_after: {num_after.num}')
if __name__ == "__main__":
main()
| false |
a744a59c2ec452bcb28e05a686e0a1180026eedf | SMHosseinM/Python | /Challenge5/Iterator.py | 514 | 4.3125 | 4 | # Create a list of items (you may use either strings or numbers in the list)
# then create an iterator using the iter() function.
#
# Use a for loop to loop "n" times, where n is the number of items in your list.
# Each time round the loop, use next() on your list to print the next item.
courses = ["Distributed system", "Java programming", "Maths", "Computation"]
# Making an iterator
courses_iterator = iter(courses)
counter = 0
while counter < len(courses):
print(next(courses_iterator))
counter += 1
| true |
8696fc2120e8d545c0aa180eb960f8cdc6982f6a | skanda9927/year2020 | /27_finding_average_and_percentage_of_subjects.py | 1,010 | 4.15625 | 4 | import array
# initializing array with array values
# initializes array with signed integers
arr = array.array('I', [ ])
total = 0
# printing original array
print ("enter the number of subjects for which average and percentage has to be calculated")
n = int(input());
for i in range (0, n):
#print (arr[i], end=" ")
# using append() to insert new value at end
arr.insert(i,int(input()));
# printing appended array
#print("The appended array is : ", end="")
for i in range (0, n):
print (arr[i])
# using insert() to insert value at specific position
# inserts 5 at 2nd position
#arr.insert(2, 5)
#print("\r")
# printing array after insertion
#print ("The array after insertion is : ", end="")
for i in range (0, n):
total = total + arr[i]
average = float (total/n)
percentage = float ((total/(n*100))*10)
#for i in range (0, 5):
# print (arr[i], end=" ")
print("average is",average,"/n percentage is",percentage)
| true |
e077fb6595c68a949051b94be4e260d2cebd4b4d | skanda9927/year2020 | /43_iterate_over_two_lists_simultaneously.py | 1,046 | 4.34375 | 4 | # Python progam to iterate over 2 lists
#PESUDOCODE
# Step 1 : declare list1 and list2 as type list
# Step 2 : input number of elements in list1
# Step 3 : input elements into list1 using for loop
# Step 4 ; input number of elements in list2
# Step 5 : input elements into list2 using for loop
# Step 6 : using for loop with zip function iterate over values in list1 and list 2
# Step 7 : print lists in iteration
import itertools
list1 = []
list2 = []
print("enter the number of elements in list1")
number1 = int(input())
for index in range(0,number1) :
list1.append(input("enter the element"))
print("enter the number of elements in list2")
number2 = int(input())
for index in range(0,number2) :
list2.append(input("enter the element"))
for (a, b) in zip(list1,list2):
print (a, b)
| true |
dc34dc0166ec7f1ea72a8606972ee22824134e8a | skanda9927/year2020 | /6_printing_prime_numbers_within_range_of_numbers.py | 1,249 | 4.375 | 4 | # Python program to printing the prime numbers within the range of numbers
#PSEUDOCODE
# Step 1 : Input the range of numbers between which the prime number has to be found out
# Step 2 : Check if the each number given in range is divisible by 2 till the input number using mod function
# # Step 3 : If the modulus function does not returns zero then output the number is
# #a prime number
# # Step 4 : Repeat step 2 and step 3 till every number is checked in given range
print("Enter the 2 range of numbers to find prime numbers between the range \n please give range in ascending order\n")
print("Enter the first number\n")
range1 = int(input())
print("Enter the second number\n")
range2 = int(input())
number = range1
index = range1
flag = 0
nflag = 0
for index in range (range1,range2) :
if index > 1 :
for index1 in range(2, index):
if (index % index1) == 0 :
break
else:
print(index, "is a prime number")
flag = flag + 1
break
if flag == 0 :
print("prime numbers between",range1,"and",range2,"does not exist" ) | true |
c66ba72fa375d16fc00f5a60052bfe41016a0832 | skanda9927/year2020 | /38_Write_a_Python_program_to_count_the_number_of_even_and_odd_numbers_from_a_series_of_numbers.py | 1,293 | 4.3125 | 4 | #
# 38. Write a Python program to count the number of even and odd numbers from a series of numbers.
#
#PSEUDOCODE
#1:take input total number of numbers in which number of odd or even numbers has tobe calculated
#2:initialise even and odd number count to zero
#3: input the sequence of numbers
#4: using modulus functiion check the number modulus 2 is equal to zero for each number
#5:if number modulus 2 is equal to zero increment even number count with 1 else increment odd number count with 1
#6:print the even and odd number count
import array
number_list = array.array('I', [ ])
even_number_count = 0
odd_number_count =0
print ("enter the number of numbers in which number of odd or even number has to known")
total_number_of_numbers = int(input());
for index in range (0, total_number_of_numbers):
print("enter the number") #index variable to point subjects in number_list array
number_list.insert(index,int(input()));
for index in range (0, total_number_of_numbers):
if ((number_list[index])%2) == 0 :
even_number_count = even_number_count + 1
else : odd_number_count = odd_number_count + 1
print("total number of even number is ",even_number_count,"total number of odd number count is",odd_number_count) | true |
2806d2ce4ceb59457b0f4bd0b60ae0e1aef0e812 | skanda9927/year2020 | /16_printing_and_setting_ENV_var.py | 1,203 | 4.34375 | 4 | #16. Environment variables in python: Print all key, values from environment.
# Check if a variable TEXT_DATA is set in environment, if so print its value.
# PSEUDOCODE
#Step 1 : retrieve environment variables and store it in environment_variables
#Step 2 : print retrieve environment variables and store it in environment_variables
#step 3 : try printing the environment variable TEXT_DATA ,if not set it gives error
#Step 4 : Set environment variable TEXT_DATA with value
#Step 5 : print newly set environment variable
# importing os module
import os
import pprint
# Get the list of user's
# environment variables
environment_variables = os.environ
# Print the list of user's
# environment variables
print("User's Environment variable:")
pprint.pprint(dict(environment_variables), width = 1)
# checking for environment variable named TEXT_DATA and setting TEXT_DATA if not configured
try:
print("TEXT_DATA", os.environ['TEXT_DATA'])
except KeyError:
os.environ['TEXT_DATA'] = 'www.cliqrtech.com'
print("new env variable configured")
print("TEXT_DATA", os.environ['TEXT_DATA']) | true |
72005727d654678f82d206d15b746f82df5db8a9 | skanda9927/year2020 | /4_detecting_prime.py | 836 | 4.34375 | 4 | # Python program to check whether number is prime or not
# PSEUDOCODE
# Step 1 : Input the number to be checked for prime number
# Step 2 : Check if the number is divisible by 2 till the input number using mod function
# Step 3 : If the modulus function returns zero then output the number is
#not a prime number
# Else print the number is prime number
number = int(input("Enter any number: "))
if number > 1 :
for index in range(2, number):
if (number % index) == 0 :
print(number, "is not a prime number")
break
else:
print(number, "is a prime number")
break
| true |
0f0de794470e98bd5b0af5eb143215f25b901b73 | UMarda/cp19_25 | /sarah.py | 381 | 4.15625 | 4 | ####task ###
import math
num=input("Enter a number: ")
while True:
if num=="x":
break
else:
num=int(num)
sr=int(math.sqrt(num))
if num==sr**2:
print("The num ",num,"is a perfect square of ",sr)
elif num!=sr**2:
print("The num ",num,"is not a perfect square. ")
num=(input("Enter a number: "))
#######
| true |
bed5b75c6d1c6a9ccfa4bbdb3da28870d0a30212 | liaogguoxiong/python_study | /newStudyOfPython/2018-11-29/studyOfObjectOriented/study2.py | 1,792 | 4.46875 | 4 | #!/usr/bin/env python
#!@Author:lgx
#!@时间:2018-11-29 16:46
#!@Filename:study2.py
'''
学习面向对象的继承
'''
class SchoolMember(object):
members=0
def __init__(self,name,age):
self.name=name
self.age=age
def tell(self):
pass
def enroll(self):
'''注册'''
SchoolMember.members +=1
print('\033[32;1mnew member [%s] is enrolled,now our SchoolMember has [%d] people. \033[0m '%(self.name,SchoolMember.members))
def __del__(self):
"""析构方法"""
SchoolMember.members -= 1
print("\033[31;1mmember [%s] is dead! now our SchoolMember has [%d] people.\033[0m"%(self.name,SchoolMember.members))
class Teacher(SchoolMember):#继承学校类
def __init__(self,name,age,course,salary):
super(Teacher,self).__init__(name,age)
self.course=course
self.salary=salary
self.enroll()
def tell(self):
msg='''hi,my name is [%s], works for [%s] as a [%s] teacher !'''%(self.name,'Oldboy', self.course)
print(msg)
def teaching(self):
print("Teacher [%s] is teaching [%s] for class [%s]" % (self.name, self.course, 's12'))
class Student(SchoolMember):
def __init__(self,name,age,grade,sid):
super(Student,self).__init__(name,age)
self.grade=grade
self.sid=sid
self.enroll()
def tell(self):
msg= '''Hi, my name is [%s], I'm studying [%s] in [%s]!''' %(self.name, self.grade,'Oldboy')
print(msg)
if __name__ == '__main__':
t1 = Teacher("Alex", 22, 'Python', 20000)
t2 = Teacher("TengLan", 29, 'Linux', 3000)
s1 = Student("Qinghua", 24, "Python S12", 1483)
s2 = Student("SanJiang", 26, "Python S12", 1484)
t1.teaching()
t2.teaching()
t1.tell()
| true |
f9c55def95708f250b935d6cf879d046652bef57 | wwilliamcook/PasswordGenerator | /generate.py | 1,391 | 4.125 | 4 | """Main function for password generator.
"""
import argparse
from random_tools import densePassword, memorablePassword
def main(args):
if args.mode is None:
# Find out what mode the user wants
while True:
mode = input('Enter a password mode [dense|memorable] (d/m): ')
# Replace shorthand
if mode in ('d', ''):
mode = 'dense'
elif mode == 'm':
mode = 'memorable'
# Validate input
if mode in ('dense', 'memorable'):
break
else:
print('Invalid mode. Try again.')
else:
mode = args.mode
# Generate and print password
if mode == 'dense':
print('Generating entropy-dense password...')
password = densePassword(16)
elif mode == 'memorable':
print('Generating memorable password...')
password = memorablePassword()
else:
print(f'Error: invalid password mode: {mode}')
input('Press enter to exit.')
exit()
print(f'New password: {password}')
input('Press enter to exit.')
if __name__ == '__main__':
p = argparse.ArgumentParser()
p.add_argument('--mode', '-m', type=str, choices=('dense', 'memorable'),
help='Specify whether to generate a dense or memorable password.')
args = p.parse_args()
main(args)
| true |
d0f2a08ae81bd8cc4c179a0bcc45cea36c0bf69b | TomaszNowak13/python_learning | /Game of threes.py | 700 | 4.28125 | 4 | """Game of Threes. Here's how you play it:
First, you mash in a random large number to start with.
Then, repeatedly do the following:
If the number is divisible by 3, divide it by 3.
If it's not, either add 1 or subtract 1 (to make it divisible by 3),
then divide it by 3.
The game stops when you reach "1"."""
def game_of_threes():
x = int(input("Write a number: "))
while x != 1:
if x % 3 == 0:
x = x / 3
print (x)
elif x % 3 == 1:
x = x - 1
x = x / 3
print (x)
else:
x = x + 1
x = x / 3
print (x)
print ("1")
game_of_threes()
| true |
64ef2a5cbc6725843fdcad0a8741bab777150214 | TomaszNowak13/python_learning | /Rovarspraket.py | 1,943 | 4.21875 | 4 | """Rövarspråket is super-secret language in Sweden.
Here's the rules: you take an ordinary word and replace the consonants with
the consonant doubled and with an "o" in between. So the consonant "b" is
replaced by "bob", "r" is replaced with "ror", "s" is replaced with "sos",
and so on. Vowels are left intact. It's made for Swedish, but it works
just as well in English. Your task today is to write a program that
can encode a string of text into Rövarspråket."""
def rovarspraket():
vowels = ("A", "E", "I", "O", "U", "Y", "Å", "Ä", "Ö")
punctuation_marks = (".", ",", "!", "?", ":", ";", "'")
choice = None
while choice != "0":
print("1 - Encode sentence \n"
"2 - Decode sentence \n"
"0 - Exit")
choice = input("What do you want to do? ")
if choice == "0":
print ("Goodbye")
elif choice == "1":
word = input("Please enter a word: ")
encoded_word = ""
for letter in word:
if letter.lower() and letter.upper() not in vowels and letter.lower() and letter.upper() not in punctuation_marks:
encoded_word = encoded_word + letter + "o" + letter.lower()
else:
encoded_word = encoded_word + letter
print ("Encoded word: ", encoded_word)
elif choice == "2":
x = input("Please enter a word: ")
word = x.split()
decoded_word = ""
i = 0
while i < len(word):
decoded_word += word[i]
if word[i].lower() and word[i].upper() in vowels and word[i].lower() and word[i].upper() in punctuation_marks:
i += 1
else:
i += 3
print ("Decoded word: ", decoded_word)
else:
print ("There's no option")
input("Press Enter to exit")
rovarspraket()
| true |
880e8d942dd7c95c75a72233ebe8aae36c6ce948 | VAR-solutions/Algorithms | /Sorting/pigeonhole/pigeonhole_sorting.py | 992 | 4.1875 | 4 | # Python program to implement Pigeonhole Sorting in python
#Algorithm for the pigeonhole sorting
def pigeonhole_sort(a):
# size of range of values in the list (ie, number of pigeonholes we need)
min_val = min(a) # min()finds the minimum value
max_val = max(a) # max() finds the maximum value
size = max_val - min_val + 1 # size is difference of max and min values plus one
# list of pigeonholes of size equal to the variable size
holes = [0] * size
# Populate the pigeonholes.
for x in a:
assert type(x) is int, "integers only please"
holes[x - min_val] += 1
# Putting the elements back into the array in an order.
i = 0
for count in range(size):
while holes[count] > 0:
holes[count] -= 1
a[i] = count + min_val
i += 1
def main():
a = [8, 3, 2, 7, 4, 6, 8]
print("Sorted order is : ", end = ' ')
pigeonhole_sort(a)
for i in range(0, len(a)):
print(a[i], end = ' ')
if __name__ == '__main__':
main()
| true |
8a85f14869332e422cab4e0f6f30446cb4288e2e | 71200675sabrina/praktikum_alpro | /Video_Praktikum09.py | 1,275 | 4.125 | 4 | #Nama: Sabrina
#Universitas kristen Duta Wacana
#Membuat suatu sistem pendaftaran pekan olimpiade sekolah, agar siswa bisa
#berpartisipasi dalam POS
print (" Pekan Olimpiade Sekolah")
print ("===========================")
username =['budi','andi','putri','diva']
pelajaran = ['matematika','fisika','kimia','biologi']
a=1
while a>=1:
print ("""
1.Pendaftaran
2.Daftar pelajaran
3.Daftar peserta
4.Pembatalan peserta
5.Exit""")
inp = int(input("Masukkan pilihan anda: "))
if inp == 1:
nama = input("Nama: ")
username.append(nama)
kelas = input("Kelas: ")
mapel = input ("Mata pelajaran: ")
print ("Pendaftaran berhasil!")
elif inp == 2:
print ("Mata pelajaran yang diujikan")
pelajaran.sort()
bu = ",".join(pelajaran)
print (bu)
elif inp == 3:
print ("Daftar peserta")
username.sort()
go = "|".join(username)
print (go)
elif inp == 4:
delt = input("Nama: ")
if delt not in username:
print ("Data", delt,"tidak ditemukan")
else:
username.remove(delt)
print ("Data",delt,"berhasil di hapus")
else:
print ("Terimakasih!")
break
| false |
9c437946b845bb50247900130c9bfb060c75e639 | hafeezulkareem/python_scripts | /change_files_extension.py | 779 | 4.40625 | 4 | import os
def change_files_extensions(from_extension, to_extension):
if os.path.exists(path):
for root_path, folders, files in os.walk(path):
for file in files:
file_path = os.path.join(root_path, file)
file_path_without_extension, file_extension = os.path.splitext(file_path)
if from_extension == file_extension:
os.rename(file_path, file_path_without_extension + to_extension)
else:
print(f"'{path}' doesn't exists.")
if __name__ == '__main__':
print('This program will change all the files with [a] to [b] extension.')
path = input('Enter folder path:- ')
from_extension = input('Enter file extension to be changed:- ')
to_extension = input('Enter file extension to be used:- ')
change_files_extensions(path, from_extension, to_extension) | true |
8d706bd75e9af54420f99a2afa40bddb751268f1 | pradeep274/Boot_Camp_day3 | /python_day2/mergesort.py | 750 | 4.25 | 4 |
# merge sort
l1 = [1, 3, 4, 7]
l2 = [0, 2, 5, 6, 8, 9]
def merge_sorted_lists(l1, l2):
"""Merge sort two sorted lists
Arguments:
- `l1`: First sorted list
- `l2`: Second sorted list
"""
sorted_list = []
# Copy both the args to make sure the original lists are not
# modified
l1 = l1[:]
l2 = l2[:]
while (l1 and l2):
if (l1[0] <= l2[0]): # Compare both heads
item = l1.pop(0) # Pop from the head
sorted_list.append(item)
else:
item = l2.pop(0)
sorted_list.append(item)
# Add the remaining of the lists
sorted_list.extend(l1 if l1 else l2)
return sorted_list
if __name__ == '__main__':
print merge_sorted_lists(l1, l2) | true |
3ca068c26428c746ecd1eb65bb1b3d71bed8b11c | Ratna1995/myassignments | /TRAINING/python_programs/day5/map.py | 505 | 4.125 | 4 | items = [1, 2, 3]
if 0:
#map will apply the functionality to each and every item in the list
def sqrt(x):
return x*x
print map(sqrt, items)
if 0:
# lambda is a keyword which creates the functionality on the fly
print map(lambda x:x*2, items)
if 0:
#filters the list based on the functionality
print filter(lambda x:x==1, items)
if 1:
#reduce applyies the functionality and returns a single value
num = input("enter a number:")
L = [x for x in range(1,num+1)]
print reduce(lambda x, y:x*y, L)
| true |
01420625a634859114bbfb2ecd335a857ea5afd7 | Chichri/Data_Visualization | /mpl_squares.py | 769 | 4.28125 | 4 | import matplotlib.pyplot as plt
squares = [1, 4, 9, 16, 25]
plt.plot(squares)
plt.show()
#Python has a lot of tools to display data in diffrent ways
#matplotlib is a very useful module for such activities
#the plot() method here attempts to plot the numbers in a meaningful way
#show() displays the graph, which can then be saved or manipulated as you like
plt.plot(squares, linewidth=5)
"""this is going to label the chart and the axes"""
plt.title('Square Numbers', fontsize = 24)
plt.xlabel('Value', fontsize = 14)
plt.ylabel('Square of Vaule', fontsize = 14)
plt.tick_params(axis='both', labelsize = 14)
plt.show()
#this version of the graph not only has a title, but also labeled axes
#tick_params() in particular can take multiple arguments to adjust things
| true |
a11e7cf2d9b69af78048e9c2e80cbfe9af4f48d6 | mozayed/oop | /18_dunder_add.py | 1,275 | 4.34375 | 4 | # Using the Dunder add __add__ to represent adding two instances together
# Using the Dunder __len__
class Employees:
raise_amount = 1.04
def __init__(self, first, last, pay):
self.first = first #i can use self.anyname but we like to stick to argument name
self.last = last
self.pay = pay
self.email = first + '.' + last + '@mycompany.com'
def fullname(self):
return '{} {}'.format(self.first, self.last)
def apply_raise(self):
self.pay = int(self.pay * self.raise_amount) # we can use Employees.raise_amount
# now when we print the instance we have it represnted that way
def __repr__(self):
return "Employees('{}', '{}', {})".format(self.first, self.last, self.pay)
# now it is using this format when printing the instance
def __str__(self):
return '{} - {}'.format(self.fullname(), self.email)
# self and other are both instances
def __add__(self, other):
return self.pay + other.pay
def __len__(self):
return len(self.fullname())
# actually it is as print('test'.__len__())
emp_1 = Employees('John','Smith',80000)
emp_2 = Employees('Sally','Johnson',45000)
print(emp_1 + emp_2)
print(len(emp_1)) | true |
eb9431780240ea9c1408e7b2c59f2827b9635113 | manojnc/DS-Solved-in-Python | /radix_sort.py | 1,253 | 4.1875 | 4 | '''
radix sort is another index based sorting where the intermediate array is only of size 10.
Unlike count sort, this reduces the space consumed by the algorithm. It works by taking the least/most
significant bits of each element and puts in the intermediate array at the index location that matches
the least significant bit. Once the entire array is parsed, the original array is reorganized according to the
position of the elements in intermediate array. This process is repeated untill there are no more bits remaining
in any of the elements i.e all the bit of the max element in that array is processed.
'''
def radix_sort(A):
n = len(A)
l=[]
max_element = max(A)
max_num_of_digits=len(str(max_element))
bins=[l] * 10
for i in range(max_num_of_digits):
for j in range(n):
sb = int ((A[j]/pow(10,i)) % 10)
if len(bins[sb]) > 0:
bins[sb].append(A[j])
else:
bins[sb] = [A[j]]
k=0
for x in range(10):
if len(bins[x]) > 0:
for y in range(len(bins[x])):
A[k] = bins[x].pop(0)
k = k + 1
A=[3,2,5,100,25,46,54,78,1,987,45,65,-1,0]
print(A)
radix_sort(A)
print(A)
| true |
ca347eaa145fabf59d35b2cd00136257b388ee53 | manojnc/DS-Solved-in-Python | /merge_sort.py | 975 | 4.28125 | 4 | ''' Merge sort uses the technique of breaking down the array into smaller subsets and then merging those subsets
in sorted order to form a final piece of complete sorted array. It uses regression methood to recursively call itself until
the elements are sorted'''
def merge_sort(A,left,right):
if left < right:
mid = (left + right) // 2
merge_sort(A,left,mid)
merge_sort(A,mid+1,right)
merge(A,left,mid,right)
def merge(A,left,mid,right):
i=left
j=mid+1
k=left
B=[0] * (right + 1)
while i <= mid and j <= right:
if A[i] < A[j]:
B[k] = A[i]
i+=1
else:
B[k] = A[j]
j+=1
k+=1
while i <= mid:
B[k] = A[i]
i+=1
k+=1
while j <= right:
B[k] = A[j]
j+=1
k+=1
for x in range(left,right+1):
A[x] = B[x]
A=[1,3,2,5,100,25,46,54,78,987,45,65]
print(A)
merge_sort(A,0,len(A)-1)
print(A)
| true |
bab0ddb6a12727eb99e844a01e55b60fa0a1a18c | lasyavanga/python-for-beginners | /birthday.py | 254 | 4.28125 | 4 | from datetime import datetime
name = input('Enter name: ')
date_of_birth = input('Enter DOB (mm-dd-yyyy): ')
birthday = datetime.strptime(date_of_birth, '%m-%d-%Y')
print(f"{name}, {birthday.month} (month), {birthday.day} (day), {birthday.year} (year)") | false |
aedafe93267db24e7a256fdf87f14cc1eb3cf4c2 | mofei952/leetcode_python | /array/128 Longest Consecutive Sequence.py | 833 | 4.125 | 4 | """
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.
Example:
Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
"""
from typing import List
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
num_set = set(nums)
max_length = 0
for x in num_set:
if x - 1 not in num_set:
y = x + 1
while y in num_set:
y += 1
max_length = max(max_length, y - x)
return max_length
if __name__ == "__main__":
print(Solution().longestConsecutive([100, 4, 200, 1, 3, 2]))
print(Solution().longestConsecutive([1, 2, 0, 1]))
| true |
9ea36ff61ece28ce306a064e3714620d865b6fcf | mofei952/leetcode_python | /dynamic_programming/174 Dungeon Game.py | 2,104 | 4.15625 | 4 | """
The demons had captured the princess and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of m x n rooms laid out in a 2D grid.
Our valiant knight was initially positioned in the top-left room and must fight his way through dungeon to rescue the princess.
The knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately.
Some of the rooms are guarded by demons (represented by negative integers), so the knight loses health upon entering these rooms;
other rooms are either empty (represented as 0) or contain magic orbs that increase the knight's health (represented by positive integers).
To reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step.
Return the knight's minimum initial health so that he can rescue the princess.
Note that any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned.
Example 1:
Input: dungeon = [[-2,-3,3],[-5,-10,1],[10,30,-5]]
Output: 7
Explanation: The initial health of the knight must be at least 7 if he follows the optimal path: RIGHT-> RIGHT -> DOWN -> DOWN.
Example 2:
Input: dungeon = [[0]]
Output: 1
Constraints:
m == dungeon.length
n == dungeon[i].length
1 <= m, n <= 200
-1000 <= dungeon[i][j] <= 1000
"""
from typing import List
import heapq
class Solution:
def calculateMinimumHP(self, dungeon: List[List[int]]) -> int:
m, n = len(dungeon), len(dungeon[0])
dp = [[float('inf')] * (n+1) for i in range(m+1)]
dp[m][n-1] = dp[m-1][n] = 1
for i in range(m-1, -1, -1):
for j in range(n-1, -1, -1):
dp[i][j] = max(1, min(dp[i+1][j], dp[i][j+1])-dungeon[i][j])
return dp[0][0]
if __name__ == '__main__':
print(Solution().calculateMinimumHP([
[-2, -3, 3],
[-5, -10, 1],
[10, 30, -5]
]))
print(Solution().calculateMinimumHP([[0]]))
print(Solution().calculateMinimumHP([[100]]))
| true |
da1cc30a770ec569b6ef2f7facc708b726991bc8 | mofei952/leetcode_python | /str/006 ZigZag Conversion.py | 2,473 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : mofei
# @Time : 2018/10/27 14:23
# @File : 006 ZigZag Conversion.py
# @Software: PyCharm
"""
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this:
(you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string s, int numRows);
Example 1:
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Example 2:
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:
P I N
A L S I G
Y A H R
P I
"""
from collections import defaultdict
import pytest
from commons import func_test
class Solution:
def convert(self, s: str, numRows: int) -> str:
"""z形状列表转换为正常显示, 通过分别统计每行的字母实现"""
if numRows == 0:
return ''
if numRows == 1:
return s
dict_ = {}
row = 1
step = 1
for v in s:
if row not in dict_:
dict_[row] = []
dict_[row].append(v)
row += step
if row == 1 or row == numRows:
step *= -1
result = ''
for i in range(1, numRows + 1):
if i in dict_:
result += ''.join(dict_[i])
return result
def convert2(self, s: str, numRows: int) -> str:
if numRows == 0:
return ''
if numRows == 1:
return s
line = 1
speed = 1
dict_ = defaultdict(list)
for v in s:
dict_[line].append(v)
line += speed
if line == numRows or line == 1:
speed = -speed
res = ''
for i in range(1, numRows + 1):
res += ''.join(dict_[i])
return res
# pytest -vv --durations=10 -q --tb=line "str\006 ZigZag Conversion.py"
@pytest.fixture(scope="module")
def test_data():
params_list = [
('PAYPALISHIRING', 3),
('PAYPALISHIRING', 4),
]
res_list = [
'PAHNAPLSIIGYIR',
'PINALSIGYAHRPI',
]
return params_list, res_list, 100000
def test_06(test_data):
func_test(Solution().convert, *test_data)
def test_06_2(test_data):
func_test(Solution().convert2, *test_data)
| true |
7014441b5d81687219bee7e3d99e4a8c4344acfc | Divyendra-pro/Divyendra | /calc.py | 384 | 4.1875 | 4 | print('Welcome to the simple project of python calculator')
num1=float(input('Enter the first number: '))
op = input('Enter the second number: ')
num2=float(input('Enter the second number: '))
if op == '+':
print(num1+num2)
elif op == '-':
print(num1-num2)
elif op == '*':
print(num1*num1)
elif op == '/':
print(num1/num2)
else:
print('Enter a valid input')
| true |
96f9fe5dbcf43443df5ac50125a7c80638445d3b | yoursamlan/FunWithNumbers | /01 Factoring a number .py | 271 | 4.125 | 4 | #In this program we will enter a number and get its factors as the output in a list format.
num = int(input("Enter number: "))
def factors(n):
flist = []
for i in range(1,n+1):
if n%i == 0:
flist.append(i)
return flist
print(factors(num))
| true |
807dfdde3689558d588f3b95ed66d9791da1f951 | HmAbc/python | /class/method.py | 956 | 4.21875 | 4 | #!/user/bin/env python3
# -*- coding: utf-8 -*-
# 类方法调用类属性
class Myclass():
val1 = '两点水'
@classmethod
def fun1(cls):
print('我是 fun1' + cls.val1)
Myclass.fun1()
# 类方法传参
class ClassA():
val2 = '两点水'
@classmethod
def fun1(cls, age):
print('我是' + cls.val2)
print('年龄:' + str(age))
ClassA.fun1(19)
# 从内部增加和修改类属性
class ClassB:
val1 = '三点水'
@classmethod
def fun1(cls):
print('原来的 val1 值为' + cls.val1)
cls.val1 = input('请输入修改 val1 的值:')
print('修改后 val1 值为' + cls.val1)
cls.val2 = input('新增类属性 val2 ,请为它赋值为:')
print('新增的 val2 值为' + cls.val2)
ClassB.fun1()
ClassB.val1 = input('请输入修改 val1 的值:')
ClassB.fun1()
ClassB.val2 = input('请输入新增类属性 val2 的值:')
print(ClassB.val2) | false |
03225854afebea6378ad5433ff1897e9890379f5 | robbycostales/RSA-cryptography | /main.py | 811 | 4.375 | 4 | print("Starting...")
#
# Author: Robert Costales
# Date: 2017 05 26
# Language: Python 3
# Purpose: Perform encryption and decryption of a piece of text using the RSA
# method.
import crypto
print("Importing crypto...")
# REF
# ord() converts character to corresponding ACII number
# chr() converts number to character
# contains original text
input_file = "inp.txt"
# where encrypted text will go
encrypt_file = "enc.txt"
# where decrypted text will go
decrypt_file = "dyc.txt"
# reads the input_file and encrypts it to the encrypt_file
print("Starting Encryption")
key, maxnum = crypto.encrypt(input_file, encrypt_file, min_prime=500, max_prime=1000)
# reads the encrypt_file and decrypts it to the decrypt file_to_list
print("Starting Decryption")
crypto.decrypt(encrypt_file, decrypt_file, key, maxnum)
| true |
9b512dfbf49aae3ce590c6376b15e6518caa7748 | erauner12/python-for-professionals | /Chapter 15 Comparisons/15_2_Comparison_by__is__vs__==_.py | 1,102 | 4.21875 | 4 |
# A common pitfall is confusing the equality comparison operators is and == .
# a == b compares the value of a and b.
# a is b will compare the identities of a and b.
# To illustrate:
a = 'Python is fun!'
b = 'Python is fun!'
a == b # returns True
a is b # returns False
a = [1, 2, 3, 4, 5]
b = a # b references a
a == b # True
a is b # True
b = a[:] # b now references a copy of a
a == b # True
a is b # False [!!]
# Basically, is can be thought of as shorthand for id(a) == id(b).
# Beyond this, there are quirks of the run-time environment that further complicate things. Short strings and small
# integers will return True when compared with is, due to the Python machine attempting to use less memory for
# identical objects
a = 'short'
b = 'short'
c = 5
d = 5
a is b # True
c is d # True
# But longer strings and larger integers will be stored separately.
a = 'not so short'
b = 'not so short'
c = 1000
d = 1000
a is b # False
c is d # False
myvar = None
# You should use is to test for None:
if myvar is not None:
# not None
pass
if myvar is None:
# None
pass
| true |
a3d1c6bb25a800f7c874edb208382386463d5c87 | erauner12/python-for-professionals | /Chapter 20 List/20_3_Checking_if_list_is_empty.py | 204 | 4.125 | 4 |
# The emptiness of a list is associated to the boolean False, so you don't have to check len(lst) == 0, but just lst
# or not lst
lst = []
if not lst:
print("list is empty")
# Output: list is empty
| true |
f2204259aea255231f8e02564edba80ac30b3a92 | raneyda/games | /games/core.py | 2,061 | 4.125 | 4 | """Module for dice functions of games
"""
#
# Imports
#
import random
from collections import deque
#
# Define Classes
#
def set_number_of_players():
"""Allows input of number of playerss, return a valid number of players
"""
print("Getting number of players")
try:
num_players = int(input("Number of players (default - 2): "))
except ValueError:
print('Invalid number of players. Setting players to 2')
num_players = 2
if (num_players > 8) or (num_players < 0):
print('Invalid number of players. Setting players to 2')
num_players = 2
else:
print('Number of players is: {:1d}'.format(num_players))
return num_players
def player_order(passed_players, setpoint=0):
""" Determines a random order of players based list of players
Returns an list of player instances
"""
total_players = 0
player_list = []
for player in passed_players:
# Determine if a player is inactive (zero bank)
if (setpoint == 0) and (player.bank == 0):
player.active = False
if (setpoint != 0) and (player.point == setpoint) and (player.active):
# List of pushed players
player_list.append(player)
elif player.active:
# List of active players
player_list.append(player)
total_players = len(player_list)
random_start = int(random.uniform(0, total_players))
rotated_list = deque(player_list)
rotated_list.rotate(random_start)
return rotated_list
def getopts(argv):
"""Collect command-line options in a dictionary
borrowed from: https://gist.github.com/dideler/2395703
"""
opts = {} # Empty dictionary to store key-value pairs.
while argv: # While there are arguments left to parse...
if argv[0][0] == '-': # Found a "-name value" pair.
opts[argv[0]] = argv[1] # Add key and value to the dictionary.
argv = argv[1:] # Reduce the argument list by copying it starting from index 1.
return opts
| true |
6cc80dc2c701a39a487e2535e183a697b862a64e | MannyHubGeek/turtle-event-listener | /main.py | 2,390 | 4.125 | 4 | # from turtle import Turtle, Screen
# import random
#
# #manny = Turtle()
# screen = Screen()
#higher order function - passing a fucntion as an input for another function
# screen.listen()
# screen.onkey(key="space", fun=move_forwards)
#example of capturing inputs from the keyboard
#
# def move_forwards():
# manny.forward(10)
#
# def move_backward():
# manny.backward(10)
#
# def move_left():
# manny.left(10)
#
# def move_right():
# manny.right(10)
#
# def move_clear():
# manny.clear()
# manny.penup()
# manny.home()
# manny.pendown()
#
# screen.listen()
# screen.onkey(key="w", fun=move_forwards)
# screen.onkey(key="s", fun=move_backward)
# screen.onkey(key="a", fun=move_left)
# screen.onkey(key="d", fun=move_right)
# screen.onkey(key="c", fun=move_clear)
#creating multiple states of an object
# race = False
# screen.setup(width=1000, height=600)
# #manny = Turtle("turtle")
#
# colors = ("red", "blue", "green", "orange", "yellow", "purple")
#
# user_guess =screen.textinput(title="Welcome to the Turtle GrandPrix!!!", prompt="Who do you think will win the race?")
# speed = [1, 2, 3, 4, 5, 6]
# pos = [-250, -200, -150, -100, -50, 0]
# my_turtles = []
# for obj in range(0, 6):
# manny = Turtle(shape="turtle")
# manny.turtlesize(1.5)
# manny.penup()
# manny.goto(x=-485, y=pos[obj])
# manny.color(colors[obj])
# my_turtles.append(manny)
#
#
# if user_guess:
# race = True
#
# while user_guess:
# for turtle in my_turtles:
# if turtle.xcor() > 420:
# race = False
# winning_color = turtle.pencolor()
# if winning_color == user_guess:
# print(f"Your turtle with {winning_color} won the race")
# else:
# print("you lost")
# rand_distance = random.randint(0, 15)
# turtle.forward(rand_distance)
def greeting(name):
out = name.title()
return f'Hi {out}'
# print(greeting("emmanuel"))
#
# phone_numbers = {"John Smith": "+37682929928", "Marry Simpons": "+423998200919"}
#
# for key, value in phone_numbers.items():
#
# print("%s: %s" % (key, value))
phone_numbers = {"John Smith": "+37682929928", "Marry Simpons": "+423998200919"}
for value in phone_numbers.values():
value.replace("+", "00")
print(f"{value}")
#screen.exitonclick()
a = 0
while a < 5:
a = a + 1
print(a)
| true |
b1d7485e0693f161021ecdeec21c6632de57c6a7 | mentalclear/PythonCrashCourse | /project/chapter8/exercises/exercise8_11.py | 887 | 4.21875 | 4 | def show_magicians(magicians):
"""Print the name of each magician"""
for magician in magicians:
print(magician)
def make_great(magicians):
"""Add the Great to the each name"""
# A new list to add changes magicians names
great_magicians = []
# Adding the Great to each name from the list
while magicians:
magician = magicians.pop()
great_magician = magician + " the Great"
great_magicians.append(great_magician)
# Add the great magicians back into magicians
for great_magician in great_magicians:
magicians.append(great_magician)
return magicians
magicians = ['David Copperfield', 'Doug Henning', 'Lance Burton']
show_magicians(magicians)
print("\nGreat magicians:")
great_magicians = make_great(magicians[:])
show_magicians(great_magicians)
print("\nOriginal list of magicians:")
show_magicians(magicians) | false |
7043219c0ed26a556098fde804080ddbfdb4de51 | mentalclear/PythonCrashCourse | /project/chapter7/exercises/exercise7_6.py | 867 | 4.3125 | 4 | prompt = "\nPlease enter a series of pizza toppings you want"
prompt += "\nEnter 'quit' when you are done"
def using_quit():
while True:
topping = input(prompt)
if topping == 'quit':
break
else:
print("We’ll add " + topping.title() + " topping to your pizza")
def using_flag():
active = True
while active:
topping = input(prompt)
if topping == 'quit':
active = False
else:
print("We’ll add " + topping.title() + " topping to your pizza")
def using_conditional():
index = 1
while index <= 3:
topping = input(prompt + " Maximum 3 toppings allowed")
if topping == 'quit':
break
else:
index += 1
print("We’ll add " + topping.title() + " topping to your pizza")
using_conditional()
| true |
f576c31246e7746c35c7c699e0428730b5cdf10d | yingxumu/CS-Courses | /CS 141/Small functions/print_fourdiv_list.py | 439 | 4.15625 | 4 | A = [1,[2,3,[4,5,6,[7]]]]
for a in A:
if type(a) is int:
print (a)
if type(a) is list:
for b in a:
if type(b) is int:
print (b)
if type(b) is list:
for c in b:
if type(c) is int:
print (c)
if type(c) is list:
for d in c:
print (d)
| false |
43fa185b86bafab237b2436003ae486e7d4a34fa | ebragas/MITX-6.00.1x | /Practice/Week 3 - Structured Types/oddTuples.py | 399 | 4.28125 | 4 |
# oddTuples
# Given a tuple, return another tuple containing the odd (by index) elements of
# the input
def oddTuples(aTup):
'''
aTup: a tuple
returns: tuple, every other element of aTup.
'''
outTup = ()
for i in range(len(aTup)):
if i % 2 == 0:
outTup = outTup + (aTup[i],)
return outTup
print("Name: {}".format(oddTuples(('eric', 'bragas'))))
| true |
335094e970f511e8ad5ec541a0a1c1a041da86b0 | Kurt-Cobai/FATEC-MECATRONICA-1600792021035-KURT | /LTPC1-2020-2/Pratica07/programa02.py | 976 | 4.21875 | 4 | #Guarda a somatoria dos valores informados
somatoria = 0
#Conta a quantidade de valores informados
contador = 0
#Guarda o maior valor rede
maior = 0
#Guarda o menor valor.
menor = 0
#COnstroi a lógica de repetição - enquanto se mantiver verddaeiro, repete o código
continuar = verdadeiro
enquanto continuar == Verdadeiro :
valor = int ( input ( "Valor:" ))
#Adiciona o valor na somatoria
somatoria + = valor #somatoria = somatoria + valor
#Adiciona mais um na contagem
contador + = 1 #contador = contador + 1
#Para verificar se é oprimeiro numero Internet
if contador == 1 :
maior = valor
menor = valor
mais :
se valor > maior :
maior = valor
elif valor < menor :
menor = valor
#Verifica se o usuário deseja continuar
continuar = input ( "Continuar?" ) == 's'
media = somatoria / contador
imprimir ( "Mídia:" , mídia )
print ( "Maior:" , maior )
imprimir ( "Menor:" , menor )
| false |
306482b2f6d2193ffcb1329ae3543c98de939b96 | bleskantje/altan_python | /3.if_else.py | 1,031 | 4.25 | 4 | # Условные операторы(: - синтаксический элемент)
var = 5
# if имеет условие
# выполняет код внутри тела если услоеие истинно
# if var != 0:
# print("var не равно 0")
# if var != 5:
# print("var не равно 0")
# if var < 0:
# print("меньше нуля")
# else:
# print("не меньше нуля")
var = 'A'
if var == 'A':
res = 'lit A'
elif var == 'B':
res = 'lit B'
else:
res = 'var is not A and B'
# print(res)
# Пример термостат
# текущая температура
current_temp = 25
# диапазон температур которые должен поддерживать котел
min_temp = 21
max_temp = 26
# логика термостата
if current_temp < min_temp:
print("Включен нагрев")
elif current_temp > max_temp:
print("Выключен нагрев")
else:
print("Температура оптимальна")
| false |
af5f43307328796d5cd12345995d18c2208c0a79 | timwford/machine-learning | /ML/LinearRegression.py | 1,478 | 4.15625 | 4 | import numpy as np
from math import sqrt
class LinearRegression:
def __init__(self):
self._slope = 0
self._intercept = 0
self._interval = 0
def _get_mean(self, arr):
"""
Calculates the mean of the array given
:param arr: The given array
:return: Mean
"""
return np.mean(arr)
def fit(self, x, y):
"""
Fits a linear model using least squares.
:param x: The list of independent variables
:param y: The list of dependent variables
:return: bool success
"""
if len(x) != len(y):
print("Error: input list sizes must agree.")
raise AttributeError
x_mean = self._get_mean(x)
y_mean = self._get_mean(y)
top = np.dot(x - x_mean, y - y_mean)
bottom = np.sum(((x - x_mean) ** 2))
self._slope = top / bottom
self._intercept = y_mean - (self._slope * x_mean)
y_hat = self._slope * x + self._intercept
err = np.sum((y - y_hat)**2)
deviation = sqrt(1 / (len(y) - 2) * err)
self._interval = 1.96 * deviation
return True
def get_slope(self):
"""
:return: The slope of the fit line
"""
return self._slope
def get_intercept(self):
"""
:return: The intercept of the fit line.
"""
return self._intercept
def get_interval(self):
return self._interval
| true |
555bf1d7b8c05bc9221b32e94c390d17289c56d9 | Rakibul66/Python-Basic-Code | /Python Basic Code/Max_min_setFunc_position.py | 551 | 4.25 | 4 | # Function to find minimum and maximum position in list
def maxminposition(A, n):
# inbuilt function to find the position of minimum
minposition = A.index(min(A))
# inbuilt function to find the position of maximum
maxposition = A.index(max(A))
print ("The maximum is at position::", maxposition + 1)
print ("The minimum is at position::", minposition + 1)
# Driver code
A=list()
n=int(input("Enter the size of the List ::"))
print("Enter the Element ::")
for i in range(int(n)):
k=int(input(""))
A.append(k)
maxminposition(A,n) | true |
2fbe93e7ecc8b0dc3b5deba933d967458849a8c3 | kritikadusad/MITOCW6.00 | /ps2/ps2_hangman.py | 2,838 | 4.15625 | 4 | # 6.00 Problem Set 3
#
# Hangman
#
# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
import random
import string
WORDLIST_FILENAME = "words.txt"
def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print "Loading word list from file..."
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r', 0)
# line: string
line = inFile.readline()
# wordlist: list of strings
wordlist = string.split(line)
print " ", len(wordlist), "words loaded."
return wordlist
wordlist = load_words()
def choose_word(wordlist):
"""
wordlist (list): list of words (strings)
Returns a word from wordlist at random
"""
return random.choice(wordlist)
# end of helper code
# -----------------------------------
def guessed_word(guessed_list, random_word_list):
"""
Takes correct letters guessed so far (in list form) and locates location of these
letters in the random word (list) and gives a list of dashes and correct letters at
the right location
"""
dashed_list = []
for i in range(0, len(random_word_list)):
if random_word_list[i] in guessed_list:
# if random_word_list[i] == guess:
dashed_list.append(random_word_list[i])
else:
dashed_list.append('_')
return dashed_list
# actually load the dictionary of words and point to it with
# the wordlist variable so that it can be accessed from anywhere
# in the program
#Initializing number of guesses that we will start with
random_word = choose_word(wordlist)
print random_word
num_guesses = 8
random_word_list = list(random_word) # twelve
guessed_list = [] # e,a,w,b,t,l,z,v
alphabet = 'abcdefghijklmnopqrstuvwxyz'
print 'Welcome to the game, Hangman! \n I am thinking of a word that is', len(random_word)
print 'letters long.\n You have 8 guesses left. Available letters: abcdefghijklmnopqrstuvwxyz'
# Main body:
while True:
if num_guesses == 0:
print 'Sorry! You lost the game.'
break
elif guessed_word(guessed_list, random_word_list) == random_word_list:
print 'Congratulations, you won!'
break
else:
print 'You have', num_guesses, 'guesses left.'
print 'Available letters:', alphabet
guess = raw_input('Please guess a letter:')
alphabet = alphabet.replace(guess, '')
if guess in random_word:
guessed_list.append(guess)
print 'Good guess:', str(guessed_word(guessed_list, random_word_list))
else:
num_guesses -= 1
print 'Oops! That letter is not in my word:', str(guessed_word(guessed_list, random_word_list))
| true |
d5b71f3010627d28da21162376a85752daf741f7 | ckoch786/pyProgramming | /fileIO/write_it.py | 737 | 4.28125 | 4 | # Write it
# Demonstrates writing to a text file
print "Creating a text file with the write() method"
tf = open("write_it.txt", "w")
tf.write("Line 1\n")
tf.write("This is line 2\n")
tf.write("That makes this line 3\n")
tf.close()
print "\nReading the newly created file"
tf = open("write_it.txt", "r")
print tf.read()
tf.close()
# Note: the writelines() method works with a list of strings
print "\nCreating a text file with the writelines() method"
tf = open("write_it.txt", "w")
lines = ["Line 1\n",
"This is line 2\n",
"That makes this line 3\n"]
tf.writelines(lines)
tf.close()
print "\nReading the newly created file"
tf = open("write_it.txt", "r")
print tf.read()
tf.close()
raw_input("\n\nPress the enter key to exit.")
| true |
adcc193127d6b554513fd357a1efbf45b19cc829 | MattPaul25/PythonReferences | /Loops.py | 699 | 4.15625 | 4 | # example file for working with loops
#only two types of loops, while and for
def main():
x = 0
#showing a while loops
while (x < 5):
print(x)
x = x + 1
def func1():
#showing a for loop
for x in range(5, 10):
print(x)
def func2():
#for over array
days = ['mon', 'tues', 'wed', 'thurs', 'frid', 'sat', 'sun']
for d in days:
print(d)
def func3():
for x in range(5, 10):
if (x == 7): break
print(x)
def func4():
for x in range(5, 10):
if ((x % 2) == 0): continue
print(x)
def func5():
days = ['mon', 'tues', 'wed', 'thurs', 'frid', 'sat', 'sun']
for x, d in enumerate(days):
print(x, d)
if __name__ == '__main__':
main()
func1()
func2()
func3()
func4()
func5()
| false |
5ed056f3aef0c90552c697b4c5035b7645b984cf | batduck27/Advent_of_code | /2021/day01/day01.py | 1,618 | 4.15625 | 4 | '''
Solution for the 1st day of Advent of Code 2021 (https://adventofcode.com/2021/day/1).
'''
# Windows size used for part2.
WINDOW_SIZE = 3
def count_increasing(sweep_report):
''' Count how many times the depth increases from the previous measurement.
:param sweep_report: Array representing the recorded depths.
:return: Number of increasing measurements.
'''
cnt = 0
for i in range(1, len(sweep_report)):
if sweep_report[i] > sweep_report[i - 1]:
cnt += 1
return cnt
def solve_part1(sweep_report):
''' Solve the first part by counting the number of increasing measurements.
:param sweep_report: Array representing the recorded depths.
:return: Number of increasing measurements.
'''
return count_increasing(sweep_report)
def solve_part2(sweep_report):
''' Solve the second part by counting the number of increasing three-measurement window.
:param sweep_report: Array representing the recorded depths.
:return: Number of increasing measurements.
'''
windowed_depths = []
for i in range(len(sweep_report) - WINDOW_SIZE + 1):
windowed_depths.append(sum(sweep_report[i:i + WINDOW_SIZE]))
return count_increasing(windowed_depths)
def main():
''' Parse the input and solve both parts. '''
with open('data.in', 'r', encoding='utf-8') as fhd:
sweep_report = [int(x) for x in fhd.read().splitlines()]
print(f'The solution for part1 is: {solve_part1(sweep_report)}')
print(f'The solution for part2 is: {solve_part2(sweep_report)}')
# Entry point
if __name__ == "__main__":
main()
| true |
56597d5de28a931ad59b198d6afd9e3df0306e0d | sudhirbelagali/PythonCourseMaterials | /hello_you.py | 658 | 4.375 | 4 |
#Ask user for name
name = input("What is yout name?: ")
#print(name)
#print(type(name))
#Ask user for age
age = input("How old are you?: ")
#age = int(age)
#age = raw_input("How old are you?: ")
#print(age)
#print(type(age))
#Ask user for city
city = input("What city do you live in?: ")
#print(city)
#Ask user what they enjoy
love = input("What do you love doing?: ")
#print(love)
#Create output text
string="Your name is {} and you are {} years old. You live in {} and you love {}"
output = string.format(name, age, city, love)
#Print output to screen
print(output)
#playground
A="part"
B=1
print("{}-{}".format(A,B))
print("{1}-{0}".format(A,B))
| false |
e5199f5c29fdb6fa687ad7f419e012dd2b4b7a87 | sudhirbelagali/PythonCourseMaterials | /tuples.py | 440 | 4.375 | 4 | #lists and tuples work the same but the difference is tuple cannot be changed- immutable datatypes
our_tuple=1,2,3,"A","B","C"
print(our_tuple)
print(type(our_tuple))
our_tuple=(1,2,3,"A","B","C")
#tuples are iterable datatypes just like strings and lists
print(our_tuple[0:3])
A=[1,2,3,4]
print(tuple(A))
(A,B,C) = 1,2,3
print(A)
print(B)
print(C)
(D,E,F)=[1,2,3]
print(D)
print(E)
print(F)
(G,H,I)="789"
print(G)
print(H)
print(I)
| true |
5380f3838ddecc66c33015dc810ce440fa1f0c03 | sudhirbelagali/PythonCourseMaterials | /functions/scope.py | 1,120 | 4.25 | 4 | #global scope
#local scope
a = 100
def f1():
print(a)
def f2():
print(a)
f1() #100 prints as 'a' is in global scope
f2() #100 prints as 'a' is in global scope
def f1():
b = 100
print(b)
def f2():
b = 50
print(b)
f1() #100 prints as 'b' is in local scope
f2() #variable b is outside the scope
def f1():
a=100
print(a)
def f2():
a=50
print(a)
f1() #It creates a variable locally instead of modifying global variable
f2()
print(a)
a = 250
def f1():
b=100+a
print(b)
def f2():
b=50+a
print(b)
f1() #It creates a variable locally instead of modifying global variable
f2()
print(a)
def f1():
global a
a = 300
print(a)
def f2():
b=50+a
print(b)
f1() #It creates a variable locally instead of modifying global variable
f2()
print(a)
def f1():
b = 100
print(b)
#def f2():
#print(b)
f1() #100 prints as 'b' is in local scope
#f2() #variable b is outside the scope
print("New update")
a = [1,2,3]
def f1():
a[0]=5
print(a)
def f2():
a=50 #local
print(a)
f1()
f2()
print(a)
| true |
3c55d95338a96feb374fd5c0898993b9c3368447 | ArthurKVasque07/PythonGEEK | /tipo_string.py | 461 | 4.125 | 4 | """
Em python, um dado é considerado um string sempre que:
- Estiver entre aspas simples > 'uma string' '123' 'a'
- Estiver em aspas duplas > "uma string" "123" "a"
- Estiver entre aspas triplas > '''uma string''' '''123''' '''a'''
"""
nome = 'Geek University'
print(nome)
print(type(nome))
nome = 'Geek University'
print(nome[0:4])
print(nome.split()[0])
print(nome.split()[1])
#inverter o nome keeg geek
print(nome[::-1])
print(nome.replace('e', 'i')) | false |
5855fcb0ac861e9190ea860f2c6a83c7525b1914 | tomilashy/using-dictionaries-and-creating-a-playlist | /dictionary.py | 1,199 | 4.125 | 4 |
detail = {"name": "jesutomi", "age": 10} #use of curly braces
details = dict(
name="jesutomi", age=10)
print(details)
print(detail)
print("checking for ", detail["name"])
#keys
for x in detail:
print(x)
for x in detail.keys():
print(x)
#values
for x in detail:
print(detail[x])
#or
for x in detail.values():
print(x)
#item
for x in detail.items():
print(x)
for k, v in detail.items():
print(k, ":", v)
for x in detail.items():
print(x[0], ":", x[1])
x = input("what key are you looking for?")
if x in detail:
print(detail[x])
news = detail.copy();
print (news);
detail.clear();
print (details == news);
#fromkey
new_dict={}.fromkeys(["name","age","address"], "unknown")
print(new_dict.get("name"))
bakery_stock = {
"almond croissant" : 12,
"toffee cookie": 3,
"morning bun": 1,
"chocolate chunk cookie": 9,
"tea cake": 25
}
bakery_stock.pop("toffee cookie"); #remove a paticular item
bakery_stock.popitem(); #removes last item
new_dict.update(bakery_stock); #adds all of bakery_stock to new_dict
detail={key:value*2 for key,value in bakery_stock.items()};
str1 = "ABC";
str2="123";
str_dict={str1[i]:str2[i] for i in range (0,len(str1))}
| true |
00b97a60517c8b630f2031a158fd678e97acebeb | RahulSurana123/40-challenging-program-python | /Factorial-calculator-App.py | 498 | 4.4375 | 4 | import math
print("Welcome to Factorial Calculator App")
def fac(no):
if no == 1:
print(str(no))
return 1
print(str(no) + " *", end=" ")
return no * fac(no - 1)
n = int(input("\nWhat number's factorial would you like to find ?"))
print("\n" + str(n) + "! = ", end=" ")
value = fac(n)
print("\nThe factorial of " + str(n) + " using math lib is : ", end ="")
print(math.factorial(n))
print("\nThe factorial of " + str(n)+" using our calculator is : " + str(value))
| false |
8b69567a615b5e2c4f0057112106acf777b63d57 | RahulSurana123/40-challenging-program-python | /Issue-Polling-App.py | 1,636 | 4.28125 | 4 | print("Welcome to polling App, Your Issue will be solved here.")
issue = input("\nWhat is the yes no issue that we are taking vote for : ")
n = int(input("What is the number of people we are taking vote from :"))
password = input("Enter the password used to see polling data : ")
voters_details = {}
vote_count = {"yes": 0, "no": 0}
for i in range(n):
voter = input("\nEnter Your Full Name voter :").title()
print(f"Here is our issue : {issue}")
if voter in voters_details:
print("\nSorry, it seems someone with the same name has already voted.")
continue
answer = input("What do you think yes or no : ").lower()
voters_details[voter] = answer
if answer.startswith("y"):
vote_count["yes"] += 1
elif answer.startswith("n"):
vote_count["no"] += 1
print(f"\nThank you {voter.title()}! Your vote {answer} has been registered")
print(f"\nThe following {len(voters_details)} people voted :")
for key in voters_details.keys():
print(key)
print(f"\nFor the following issue : {issue}")
if vote_count["yes"] > vote_count["no"]:
print(f"yes wins! {vote_count['yes']} votes to {vote_count['no']}")
elif vote_count["yes"] < vote_count["no"]:
print(f"no wins! {vote_count['no']} votes to {vote_count['yes']}")
else:
print(f"It was a tie! {vote_count['yes']} votes to {vote_count['no']}")
data_display_permission = input("\nTo see the voting result enter the admin password : ") == password
if data_display_permission:
for key, value in voters_details.items():
print(f"Voter: {key}\t Vote: {value}")
print("Thank you for using your Issue Polling App")
| true |
41b00973fdbc33f177de147b89b5e27f4ef1b0e7 | RahulSurana123/40-challenging-program-python | /Vote-Regisration-App.py | 760 | 4.25 | 4 | print("Welcome to Vote Registration App")
name = input("\nEnter your name : ").title()
age = int(input("Enter your age : "))
parties = ["Bjp", "Congress", "Siv Sena", "Aap"]
if age < 18:
print("\nSorry! you are not eligible to vote")
exit()
print(f"\nCongratulation {name}! you are eligible to vote")
print("\nBelow are mentioned name of all the party you can vote any one of them: ")
for party in parties:
print(f"\t- {party.upper()}")
choice = input("What party would you like you to choose : ").title()
if choice == "BJP":
print("Congo you have voted for BJP who is a majority party.")
elif choice.title() in parties:
print(f"You have voted for {choice} who is not a majority party")
else:
print(f"{choice} is not in the election")
| false |
84ae118b426090da45ac739717c1de0e71c9d559 | mikey084/Algorithms_Practice | /Easy_algos/arrays/reverse_array.py | 327 | 4.25 | 4 | def reverse_string(string):
cleaned = string.strip()
split = cleaned.split()
newArray = []
for word in reversed(split):
newArray.append(word)
return newArray
string1 = "hello I am here to bang"
string2 = "hello john asdf "
print(reverse_string(string1))
print(reverse_string(string2))
| true |
08ec36aa9a4986c1e4907d4d75335a2df7f97c23 | mikey084/Algorithms_Practice | /Data_Structures/Queue.py | 691 | 4.1875 | 4 | '''
implement a Queue data structure
'''
class Queue:
def __init__(self):
self.queue = []
def isEmpty(self):
return self.queue == []
def enqueue(self, data):
self.queue.append(data)
def dequeue(self):
data = self.queue[0]
del self.queue[0]
return data
def peek(self):
return self.queue[0]
def sizeQueue(self):
return len(self.queue)
def getValues(self):
return self.queue
q = Queue()
q.enqueue(10)
q.enqueue(20)
q.enqueue(30)
q.enqueue(40)
print(q.sizeQueue())
print("dequeue: " + str(q.dequeue()))
print("dequeue: " + str(q.dequeue()))
print(q.sizeQueue())
print(q.getValues())
| false |
9c30917bbc2eed29a3136edd3a53e885529c0100 | KWolf484/PythonProject | /String List (Palindrome)/String List (Palindrome)/String_List__Palindrome_.py | 382 | 4.3125 | 4 | word = input('Enter a word to check if it is a palindrome: ').upper()
def pal_check(word):
newWord = []
for char in list(word[::-1]):
newWord += char
newWord = ''.join(newWord)
if newWord == word:
print ('%s is a palindrome' % word)
else:
print ('%s backwards is %s.\nSo %s is not a palindrome' % (word, newWord, word,))
pal_check(word)
| false |
ae3cb99af93f5ef556723ce6125d4a515c272a12 | umutcaltinsoy/Data-Structures | /Dictionary/Dictionary_Methods/update.py | 739 | 4.65625 | 5 | # update() method
# This method updates the dictionary with the elements from the another
# dictionary object or from an iterable of key/value pairs
# Syntax : dict.update([other])
# Parameters : key-value pairs
# Example: Update with another dictionary
Dictionary1 = {'A': 'Umut', 'B' : 'Cagri'}
Dictionary2 = {'B' : 'Umut'}
# Dictionary before Update
print("Original Dictionary : ", Dictionary1)
# Update the value of key 'B'
Dictionary1.update(Dictionary2)
print("Dictionary after update : ", Dictionary1)
# Example 2 : Update with an iterable
Dictionary1 = {'A' : 'Umut'}
print("Original : ", Dictionary1)
# Update with iterable
Dictionary1.update(B = 'Cagri', C = 'Altinsoy')
print("Dictionary after update : ", Dictionary1)
| true |
701cc0a2771bd964223d0ac3a8a708aa420b165f | umutcaltinsoy/Data-Structures | /Dictionary/Dictionary_Methods/keys.py | 1,145 | 4.875 | 5 | # keys()
# This method returns a view object that displays a list of all the keys
# in the dictionary in order of insertion.
# Syntax : dict.keys()
# Example :
Dictionary1 = {'A': 'Umut', 'B' : 'Cagri', 'C' : 'Altinsoy'}
print(Dictionary1.keys())
# Creating empty dictionary
empty_Dict1 = {}
print(empty_Dict1)
# Example :
# To show how updation works
Dictionary1 = {'A' : 'Umut', 'B' : 'Cagri'}
print("Keys before dictionary updation : ")
keys = Dictionary1.keys()
print(keys)
# adding an element to the dict.
Dictionary1.update({'C' : 'Altinsoy'})
print('\nAfter dictionary is updated : ', keys)
# Here, when the dictionary is updated, keys are also
# automatically updated to show the changes.
# The keys() can be used to access the elements
# of the dict as we can do for the list
# Example :
test_dict = {'Umut' : 1, 'Cagri' : 2, 'Zed' : 3}
# accessing 2nd element using loop
j = 0
for i in test_dict:
if (j == 1):
print('2nd key using loop : ' + i)
j = j + 1
# accessing 2nd element using keys()
# print('2nd key using keys() : ' + test_dict.keys()[1])
# wouldn't work because python3 doesn't support indexing
| true |
6199791e2f5c0c9814d8863a63730030266d0df6 | TiahWeiJun/PythonDataStructures | /Sort Algorithms/BubbleSort.py | 608 | 4.1875 | 4 | #Compare the element with the element beside and swap until the largest element is pushed to the right
#Time complexity is O(n^2) in worse case scenario and O(n) in best case scenario due to double for loop
#Space complexity is O(1) as it is sorting in place
#Stable Sorting Algorithm
def bubbleSort(arr):
for i in range(len(arr)):
swap = 0
for j in range(len(arr)-i-1):
if arr[j] > arr[j+1]:
arr[j],arr[j+1] = arr[j+1],arr[j]
swap+=1
if swap == 0:
break
print(arr)
unsortedArr = [6,5,4,3,2,1]
bubbleSort(unsortedArr) | true |
ec4a405d067aae71398dc2b0f1ee2f3223e62c0e | TiahWeiJun/PythonDataStructures | /Sort Algorithms/SelectionSort.py | 698 | 4.1875 | 4 | #Iterate over array to find minimum value and put it to the front of the array
#Time complexity is O(n^2) in worse case scenario as well as best case scenario due to double for loop
#Space complexity is O(1) as it is sorting in place
#Not a stable algorithm. elements with same value might end up swapping their positions in the array
def selectionSort(arr):
for i in range(len(arr)-1):
minindex = i
minvalue = arr[i]
for j in range(i+1,len(arr)):
if arr[j] < minvalue:
minindex = j
minvalue = arr[j]
arr[i],arr[minindex] = arr[minindex],arr[i]
return arr
unsortedArr = [3,6,1,4,2,5]
selectionSort(unsortedArr) | true |
b9f95581b3fb46c73013b09a201138c129997a77 | amisolanki/assignments | /assignment1/pro9.py | 308 | 4.40625 | 4 | print("Program that converts the string into lowercase")
string1="HelLo MoNTy PyThOn"
print(string1)
print("@@@@@@@@@@@@@@@@@@@@@^^^^^^^^^^^^^^^^^^^^^^@@@@@@@@@@@@@@@@")
print("String after converting into the lowercase")
print("@@@@@@@@@@@@@@@@@@@@@^^^^^^^^^^^^^^^^^^^^^^@@@@@@@@@@@@@@@@")
print(string1.lower())
| true |
c67c436d6f6c9c2655e8ae26d7141462a8b9dcbb | sunank200/DSA-nanodegree | /P0/Task1.py | 914 | 4.125 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open("texts.csv", "r") as f:
reader = csv.reader(f)
texts = list(reader)
with open("calls.csv", "r") as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 1:
How many different telephone numbers are there in the records?
Print a message:
"There are <count> different telephone numbers in the records."
"""
def differentPhoneNumbers():
set_of_phone_numbers = set()
for each_text in texts:
set_of_phone_numbers.add(each_text[0])
set_of_phone_numbers.add(each_text[1])
for each_call in calls:
set_of_phone_numbers.add(each_call[0])
set_of_phone_numbers.add(each_call[1])
print(
"There are {} different telephone numbers in the records.".format(
len(set_of_phone_numbers)
)
)
differentPhoneNumbers()
| true |
0f474774b937799bfe9d4814de18f968fca25a9b | Nomillions/OOP | /CarClass.py | 1,879 | 4.125 | 4 | # Class HW Assignment
# MIS 4322 - MW 1:00 - 2:15
# Noah Miller
class Car:
def __init__(self, year_model,make,speed):
self.__year_model = year_model
self.__make = make
self.__speed = speed
def accelerate(self,speed_change_accelerate):
self.__speed += speed_change_accelerate
def brake(self,speed_change_brake):
self.__speed -= speed_change_brake
def get_speed(self):
return self.__speed
################################################################
#Use the class
import CarClass as cc
def main():
car_info()
def car_info():
print("Hello! Please input your vehicle's information below.")
year_model = input("What is your vehicle's YEAR and MODEL? (Format: 'YYYY, MODEL') ")
make = input("What is your vehicle's MAKE? ")
speed = 0
car_info = cc.Car(year_model,make,speed)
car_speed_montoring(year_model, make, speed, car_info)
def car_speed_montoring(year_model, make, speed, car_info):
accumulator = 5
speed_change_accelerate = 5
speed_change_brake = 5
print("")
print("Now we will find your vehicle's acceleration!")
print("---------------------------------------------")
for increase_change in range(accumulator):
car_info.accelerate(speed_change_accelerate)
print("Your ",year_model,make, " is currently traveling ",
car_info.get_speed(), " miles per hour!", sep=''
)
print()
print()
print("Now we will find your vehicle's decceleration!")
print("---------------------------------------------")
for decrease_change in range(accumulator):
car_info.brake(speed_change_brake)
print("Your ",year_model,make, " is currently traveling ",
car_info.get_speed(), " miles per hour!", sep=''
)
print()
main() | false |
ff1cd5ca261b8162bef485baf7a55f691cc71fdf | LizaKoliechkina/python-workshop-082021 | /DAY-1-FunctionalProgramming/closure.py | 799 | 4.125 | 4 | # Design Pattern - FACTORY
# CLOSURE - func object that allows access to variables outside local scope
def power_n(n):
def inner(x):
return x ** n
return inner
power_2 = power_n(2)
power_3 = power_n(3)
print(power_2(10))
print(power_3(10))
def sentence(name):
age = 32 # not used in inner function
def inner(city): # closure
return f'My name is {name} and live in {city}'
return inner
print(sentence('Ala')('Wroclaw'))
full_sentence = sentence('Ala') # - global scope
print(full_sentence.__closure__)
print(full_sentence.__closure__[0].cell_contents)
print(full_sentence('Krakow')) # - object inner !!!
# PERSISTENCE: GENERATORS, CLASSES, GLOBAL VARIABLES
# GLOBAL VARIABLES ARE IN GLOBAL EXECUTION SCOPE, ARE CLEANED ONLY AFTER PROGRAM EXECUTION
| true |
c4a839e2eabe092831d690dba88dc7beb1d1def1 | isiguta/hackerrank_problems | /Interview Preparation Kit/WarmUp/clouds_jump.py | 1,634 | 4.25 | 4 | # Emma is playing a new mobile game that starts with consecutively numbered clouds. Some of the clouds are thunderheads and others are cumulus. She can jump on any cumulus cloud having a number that is equal to the number of the current cloud plus or . She must avoid the thunderheads. Determine the minimum number of jumps it will take Emma to jump from her starting postion to the last cloud. It is always possible to win the game.
# For each game, Emma will get an array of clouds numbered if they are safe or if they must be avoided. For example, indexed from . The number on each cloud is its index in the list so she must avoid the clouds at indexes and . She could follow the following two paths: or . The first path takes jumps while the second takes .
# Function Description
# Complete the jumpingOnClouds function in the editor below. It should return the minimum number of jumps required, as an integer.
# jumpingOnClouds has the following parameter(s):
# c: an array of binary integers
# Input Format
# The first line contains an integer , the total number of clouds. The second line contains space-separated binary integers describing clouds where .
# Constraints
#
#
#
# Output Format
# Print the minimum number of jumps needed to win the game.
# Sample Input 0
# 7
# 0 0 1 0 0 1 0
# Sample Output 0
# 4
def jumping_on_clouds(c):
steps = 0
index = 0
end = len(c) - 2
while index <= end:
if index + 2 <= len(c) - 1:
if c[index + 2] == 0:
index += 2
steps += 1
continue
index += 1
steps += 1
return steps
| true |
c8a4d90661c4a8ace8679a2d32f4bbb4065b23b4 | Yanushanus/coloc | /44.py | 471 | 4.25 | 4 | '''
Перетин даху має форму півкола з радіусом R м. Сформувати таблицю,
яка містить довжини опор, які встановлюються через кожні R / 5 м.
'''
from math import sqrt
radius = int(input('radius: '))
delta = radius / 5
x = 0
i = 0
while x < 2 * radius - delta:
x = x + delta
i += 1
h = sqrt(x * (2 * radius - x))
print(f'Height of {i} prop:', h) | false |
509ecf55ca491e9c9666fec1b83ba73a60b807c6 | puspita-sahoo/basic_ds_algo | /my_folder/singly_linked_list/3_add.py | 1,516 | 4.125 | 4 | #add operation ===> at beginning, at end
#==> at given pos(before given node, after node)
class Node:
def __init__(self, data= None, next = None):
self.data = data
self.next = next
class Linked_List:
def _init__(self):
self.head = None
def traverse(self):
n = self.head
while n:
print(n.data, "->", end='')
n = n.next
def addstart(self, data): #===> at beginning
self.head = Node(data=data, next= self.head)
def addend(self, data): #===> at end
new_node = Node(data= data)
if (self.head == None):
self.head = new_node
else:
n = self.head
while n.next:
n = n.next
n.next = new_node
def add_after(self, data, x): #====> after given node
n = self.head
while n is not None:
if x == n.data:
break
n = n.next
if n is None:
print("node is not present in ll")
else:
new_node = Node(data)
new_node.next = n.next
n.next = new_node
def add_before(self, data, x): # ===> before given node
if self.head is None:
print("Linked list is empty")
return
if self.head.data == x:
new_node = Node(data)
new_node.next = self.head
self.head = new_node
return
n = self.head
while n.next
| false |
cf741496d982523b4911628c2247b3c580a54795 | Jingwei4CMU/Leetcode | /617. Merge Two Binary Trees.py | 2,005 | 4.25 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def mergeTrees(self, t1, t2):
"""
:type t1: TreeNode
:type t2: TreeNode
:rtype: TreeNode
"""
# Runtime: 96 ms, faster than 83.11% of Python3 online submissions for Merge Two Binary Trees.
if t1 or t2:
nt = TreeNode(None)
return self.merge(nt, t1, t2)
else:
return None
def merge(self, nt, t1, t2):
# merge root
if t1 or t2:
val1 = t1.val if t1 else 0
val2 = t2.val if t2 else 0
nt.val = val1 + val2
else:
return nt
# merge left
templeftnode1 = t1.left if t1 else None
templeftnode2 = t2.left if t2 else None
if templeftnode1 or templeftnode2:
tempnode = TreeNode(None)
nt.left = self.merge(tempnode, templeftnode1, templeftnode2)
# merge right
temprightnode1 = t1.right if t1 else None
temprightnode2 = t2.right if t2 else None
if temprightnode1 or temprightnode2:
tempnode = TreeNode(None)
nt.right = self.merge(tempnode, temprightnode1, temprightnode2)
return nt
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def mergeTrees(self, t1, t2):
"""
:type t1: TreeNode
:type t2: TreeNode
:rtype: TreeNode
"""
# Runtime: 80 ms, faster than 100.00% of Python3 online submissions for Merge Two Binary Trees.
if t1 and t2:
t1.val = t1.val + t2.val
else:
return t1 or t2
t1.left = self.mergeTrees(t1.left, t2.left)
t1.right = self.mergeTrees(t1.right, t2.right)
return t1
| false |
7d2d1a20723e1af434f709914dcbe8ce70e3352a | eljam3239/CarDatabase | /FileHandle.py | 2,010 | 4.46875 | 4 | from csv import reader
#I tried a painful amount of ways of working with csv file without the csv library, but I ultimately stopped being stubborn and read the links commented in this program to learn how to use the csv module so I could work with reading and writing the csv file easier
"""
This module contains the method that stores the csv file into a list of lists that is easier to work with and the module which writes output to the text file if the user chooses to view it that way
Written by Eli James, 20177630
Last Edited on July 20th, 2020
"""
#learned how to make list of lists from a csv file from: https://thispointer.com/python-read-csv-into-a-list-of-lists-or-tuples-or-dictionaries-import-csv-to-list/
#turns the csv file from onq into a list of lists
def readFromDatabase():
with open('C:\\Users\\Eli\\Desktop\\python\\assignment2elijames\\database1.csv', 'r') as read_obj:
#makes a reader object
csv_reader = reader(read_obj)
#get a list of lists
carDatabase = list(csv_reader)
return carDatabase
#tried to implement the text writing file from assignment 1, had some troubles
#instead I am using inspiration from a user on stackoverflow: https://stackoverflow.com/questions/899103/writing-a-list-to-a-file-with-python
#writes a list to a text file that the user can use as an alternative to the console to view the car information
def writeToOuputFile(alist):
outputFile = open("C:\\Users\\Eli\\Desktop\\python\\assignment2elijames\\outputFile.txt", "w")
for item in alist:
outputFile.write('%s' % item + " ")
outputFile.close
#used this for testing like once
def displayInventory(inventory):
for i in range(len(inventory)):
print(inventory[i])
#for testing
if __name__ == "__main__":
inventory = readFromDatabase()
displayInventory(inventory)
writeToOuputFile('C:\\Users\\Eli\\Desktop\\python\\assignment2elijames\\outputFile.txt', [1, 2, 3, 4])
| true |
0a8bef43135eb67fb9b974274ff2e7aac44c9df4 | kuljotbiring/Udacity-DS-Algorithms | /binarysearch.py | 1,487 | 4.25 | 4 | """You're going to write a binary search function.
You should use an iterative approach - meaning
using loops.
Your function should take two inputs:
a Python list to search through, and the value
you're searching for.
Assume the list only has distinct elements,
meaning there are no repeated values, and
elements are in a strictly increasing order.
Return the index of value, or a -1 if the value
doesn't exist in the list."""
def binary_search(input_array, value):
"""Your code goes here."""
# set the start and end variables for where to look in
start = 0
end = len(input_array) - 1
# while in range of two end points
while start <= end:
# get the middle of end points. use floor division to round down
mid = (start + end) // 2
# if the middle index value is the value, then return it
if input_array[mid] == value:
return mid
# if the value is less than current value of the middle
elif value < input_array[mid]:
# shift the end of search range to be 1 less the mid value
end = mid - 1
# otherwise value is more than current value of the middle
else:
# then move start of search to 1 more than mid value
start = mid + 1
# returning -1 means value was not found
return -1
test_list = [1,3,9,11,15,19,29]
test_val1 = 25
test_val2 = 15
print(binary_search(test_list, test_val1))
print(binary_search(test_list, test_val2))
| true |
a1d5376ced3f236460527e8e710e6170e8114084 | GTPB/PPB17 | /extra/1-TabularData/d3_tabulardata_data_scripts/transpose_table.py | 361 | 4.21875 | 4 | '''
Tabular Data - Exercise
The script reads the input table into a Python table,
transposes the table and writes the transposed table to
a file.
'''
T = open("table-1.txt")
table = []
for line in T:
table.append(line.split())
# Transpose table. It generates a transposed table.
columns = zip(*table)
for elem in columns:
print '\t'.join(elem)
| true |
d96a20a677951a2ea57f2b2151dacbc365ebcc95 | KevTiv/delivery_management_system_wgu_C950 | /chaining.py | 2,745 | 4.15625 | 4 | # Name : Kevin Tivert
# Student ID: 001372496
# Use of hashtable to store necessary data
# O(n)
class Chaining(object):
# Constructor
# Constructor with predefine storage capacity
# Assigns all buckets with an empty list.
# O(1)
def __init__(self, inital_storage=10):
# initialize the hash table with empty bucket list entries.
self.table = []
for i in range(inital_storage):
self.table.append([])
# Assign a new item
# Function will first determine the length of the current list then
# assign the new object at the end of the existing bucket list or
# create a new bucket list.
# O(1)
def insert(self, item):
bucket = hash(item) % len(self.table)
bucket_list = self.table[bucket]
# Assign the item to the end of the bucket list.
bucket_list.append(item)
# Searches for item with same key in the hash table and return result
# Similar as the insert () function this function will first determine
# the size of the list and using a loop, the function will go through the
# list and compare every single object until one matches our search object
# or will return none
# O(n)
def search(self, key):
bucket = hash(key) % len(self.table)
bucket_list = self.table[bucket]
# search key in the bucket list
if key in bucket_list:
# find the item's index and return the item that is in the bucket list.
item_index = bucket_list.index(key)
return bucket_list[item_index]
else:
# No key found
print("No Result")
return None
# Remove an item with same key from the hash table.
# The function will first determine the size of the list, go through the list
# using a loop and compare object in the list with the given object (key) the
# function has to remove. If the key is found in the list, it will be removed
# but if it is not found the function will go through the list and end.
# O(n)
def remove(self, key):
bucket = hash(key) % len(self.table)
bucket_list = self.table[bucket]
# remove the item from the bucket list if it is found
if key in bucket_list:
bucket_list.remove(key)
# Overloaded string conversion method to create a strings that represent the hashtable
# bucket in the hastable is shown as a pointer to a list object.
# O(1)
def __str__(self):
index = 0
wrd = " -----\n"
for bucket in self.table:
wrd += "%2d:| ---|-->%s\n" % (index, bucket)
index += 1
wrd += " -----"
return wrd | true |
6ebac9a46b641c759ae1e0b697bf2652accfa830 | atticdweller/pythonthehardway | /ex42.py | 1,293 | 4.3125 | 4 | ## animal is-a object
class Animal(object):
pass
##?? dog is annoying
class Dog(animal):
def __init))(self, name):
## bow bow, dog has a name
self.name = name
## ?? cat is an animal
class Cat(Animal):
def __init__(self, name):
# cats have names
self.name = name
## really animal, but fine, i'll take object
class Person(object):
def __init__(self, name):
## just call a human an object with name?
self.name = name
# and we own pets!
self.pet = None # only animals I own are edible.
## employee is object of class person?
class Employee(Person):
def __init__(self, name, salary):
## ?? what is this magic?
super(Employee,self).__init__(name)
##??
self.salary = salary
## Fish is a class of object
class Fish(object):
pass
## salmon is a class of fish
class Salmon(Fish):
pass
##?? Halibut is a class of fish
class Halibut(Fish):
pass
## rover isa dog
rover = Dog("Rover")
## satan is a cat
satan = Cat("Satan")
##mary is a person
mary = Person("Mary")
## mary has a pet, satan
mary.pet = satan
## frank is an employee and has a salary of 12000
frank = Employee("Frank",120000)
## frank has a pet rover
frank.pet = rover
## flipper is a fish
flipper = Fish()
## crouse is a salmon
crouse = Salmon()
## harry is a halibut()
harry = Halibut()
| true |
559b16837bff4325ef7a3b999a9f97901174b524 | ishantk/PythonEdurekaDec14 | /venv/Session3A.py | 1,422 | 4.375 | 4 | # Dictionary of Dictionaries
customers = { 1001: {"name":"John", "phone":"+91 99999 88888"}, 2001: {"name":"Jennie", "phone":"+91 77777 88888"} }
print(customers[1001])
print(customers[2001])
# get is built in function to again get the data on the basis of key
print(customers.get(1001))
print(customers.get(2001))
# item is a tuple of key value pair
# items is a list of tuples of key value pairs
items = customers.items()
print(items)
print(type(items))
keys = customers.keys()
values = customers.values()
print(keys)
print(type(keys))
print(values)
print(type(values))
print("====Copying customers to newCustomers===")
newCustomers = customers.copy()
print(newCustomers)
print(type(newCustomers))
print(hex(id(customers)))
print(hex(id(newCustomers)))
customers.clear()
print(customers)
# ****************
employees = { 111:"John", 21:"Jennie", 45:"Jim", 33:"Jack", 65:"Joe" }
# Fetch the keys and convert them into list
keys = list(employees.keys()) # to convert data into list
print(keys)
sortedKeys = sorted(keys)
print(sortedKeys)
# iterating in Sorted Keys
for key in sortedKeys:
print(key," ",employees[key])
"""
Combinations
-> List of Tuples
-> List of Sets
-> List of Dictionaries
-> List of Strings
-> List of Any Type
-> Tuple of Any Type
-> Set of Any Type
-> Dictionary of Any Type
Strings are Just collection of characters !!
"""
| true |
e0ae1cdfc8ca594d28c2f6d4e5f07b1af83ea7e4 | ishantk/PythonEdurekaDec14 | /venv/Session8H.py | 1,952 | 4.4375 | 4 | # In Python our scripts are Interpreted and not compiled !!
# What ever error shall occur will be an error at run time
# Errors which occurs at Run Time they simply crash our program
# Execution of Program shall be disrupted i.e. abnormal termination of program
"""
print("Welcome")
num1 = int(input("Enter Number 1 "))
num2 = int(input("Enter Number 2 "))
num3 = num1/num2
print("Result is", num3)
print("Thank You !! B.Byee !!")
"""
# If everything is running fine, our program i.e. main thread shall run from top to bottom !!
# All the statements will execute and program shall terminate normally !!
# If error occurs at Run Time we call it Exception !!
# We got techniques to handle exceptions with try catch and finally blocks
print("Welcome")
# Exception Handling : With this we make our apps robust !!
try:
num1 = int(input("Enter Number 1 "))
num2 = int(input("Enter Number 2 "))
num3 = num1/num2
# except ZeroDivisionError:
# print("OOPS!! num2 cannot be 0")
# except ValueError:
# print("OOPS!! Number in a text format isn't allowed")
except Exception as e:
print("Some Error Occurred !!", e)
else:
print("Result is", num3)
finally:
print("--Finally--")
print("Thank You !! B.Byee !!")
"""
try is a block where we keep statement in which error may occur
except is a block which catches the errors and we shall print some message to the user
else, if exception will not come use else block to perform the task
finally is a block which is executed at last regardless of exception occurring or not
Q. How shall we remember exception classes or how will we come to know about them ?
A. When you will get error you will learn about it or refer documentation about how many errors are thr
But of all the errors Exception class is Parent to them !!
"""
"""
User Defined Exceptions
class MyException(Exception):
pass
class YourException(ZeroDivisionError):
pass
""" | true |
02eca9e1934667f996f41a63a7d02679dd19f968 | FPTensorFlow/jim-emacs-fun-py | /python_lambda_multiline.py | 1,017 | 4.125 | 4 | #!/usr/bin/python
#-*-coding:utf-8 -*-
aaa = lambda a,b: (
a*b
)
#print aaa(5,2) #=> 10
# 这里面不能用等号赋值表达式==>
aaa1 = lambda a,b: (
a,
b,
a+b,
a*b,
a-b
)
# 输出是一个列表来着:
#print aaa1(222,110) #=> (222, 110, 332, 24420, 112)
aaa2 = lambda a,b: (
a,
b,
a+b,
a*b,
a-b
)[-1]
# [-1] 是输出最后一个答案的意思
# print aaa2(222,110) #=> 112
# 在lambda中运行这三个运算: 只能变成数组去 pop 取出, append 加入来运算了 # 因为不能进行赋值操作(SyntaxError: can't assign to lambda)
# a = a + b
# b = b * c;
# return a + b + c;
aaa3 = lambda a,b,c: (
a.append(a.pop() + b[-1]),
b.append(b.pop() * c),
a[-1] + b[-1] + c
)
# print aaa3([1],[2],1) #=> (None, None, 6)
# print aaa3([1],[2],1)[-1] #=> 6
#aaa4 = lambda a,b,c: a+b+c,a #=> NameError: name 'a' is not defined
#aaa4 = lambda a,b,c: (a+b+c,a) #=> ok
#aaa4 = lambda a,b,c: a+b+c;a #=> NameError: name 'a' is not defined
| false |
67c556af4b8fda2f624791bb64b3c717029fa024 | tianceshi-python/practice_pro | /meeting_ptactice/Decorator_dir/str_spit8str.py | 824 | 4.25 | 4 | # encoding:utf-8
'''
题目描述
•连续输入字符串,请按长度为8拆分每个字符串后输出到新的字符串数组;
•长度不是8整数倍的字符串请在后面补数字0,空字符串不处理。
输入描述:
连续输入字符串(输入2次,每个字符串长度小于100)
输出描述:
输出到长度为8的新字符串数组
'''
def printStr(string):
if len(string) > 8:
while (len(string) > 8):
str1 = string[:8]
print(str1)
string = string[8:]
str1 = string + '0' * (8 - len(string))
print(str1)
else:
for i in range(len(string),8):
string = string + '0'
print(string)
string1 = input('请输入string1:\n')
string2 = input('请输入string2:\n')
printStr(string1)
printStr(string2)
| false |
3a312ed52863a0e4f600bfd3b2d0c7ec8906da17 | dm-drogeriemarkt/nesbi | /nesbi/core/helpers/__init__.py | 335 | 4.1875 | 4 | def deepupdate(original, update):
"""
Recursively update a dict.
Subdict's won't be overwritten but also updated.
"""
for key, value in original.items():
if key not in update:
update[key] = value
elif isinstance(value, dict):
deepupdate(value, update[key])
return update
| true |
5de9caacfee4e439c90dbe60146a070eaad75091 | Juju4ka/Learn-Python-The-Hard-Way | /ex15.py | 889 | 4.21875 | 4 | # Imports argument variable from sys module
from sys import argv
# Assigns data from command line arguments to variables
script, filename = argv
# Opens a file with specified filename
# txt is a variable holding a file object
txt = open(filename)
# Prints the name of the file
print "Here's your file %r:" % filename
# Reads all data of the file and prints it
# print txt.read()
print txt.readline()
print "The name of the file is %s" % txt.name
# Close the file
txt.close()
# Prints the text specified in quotes
print "Type the filename again:"
# Reads a string from the input and
# assigns it to a variable
file_again = raw_input("> ")
# Opens a file with specified filename and
# assigns file object to a variable txt_again
txt_again = open(file_again)
# Reads all data of the file until EOF reached
# and prints it
print txt_again.read()
# Close the file
txt_again.close() | true |
d5d1862218159be2fea30ef0fd5da23e18b1db48 | Juju4ka/Learn-Python-The-Hard-Way | /ex3.py | 2,031 | 4.4375 | 4 | # Prints text specified in quotes on the screen
print "I will now count my chickens:"
# Calculates and prints the number of Hens
# 30 is divided by 6 and then the result is added to 25
print "Hens", 25 + 30 / 6
# Calculates and prints the number of Roosters
# Calculation of 100 - 25 * 3 % 4 is permormed as following:
# 1) 25 * 3 = 75
# 2) 75 % 4 = 3 (3 is the remainder of 75 divided by 4)
# 3) 100 - 3 = 97
print "Roosters", 100 - 25 * 3 % 4
# Prints text "Now I will count the eggs:"
print "Now I will count the eggs:"
# Calculates the number of eggs and prints this number on the screen
# Calculation of 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6 is performed as following:
# 1) 4 % 2 = 0
# 2) 1 / 4 = 0.25 (but it will only use integer part, i.e. 0)
# 3) 3 + 2 + 1 - 5 + 0 - 0 + 6 = 1 + 6 = 7
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
# Calculates the number of eggs and prints this number on the screen
# Uses floating numbers
print 3 + 2 + 1 - 5 + 4 % 2 - 1.0 / 4.0 + 6.0
# Prints text specified in quotes on the screen
print "Is it true that 3 + 2 < 5 - 7?"
# Calculates left and right part, compares and
# Prints result of comparison of 5 < -2
print 3 + 2 < 5 - 7
# Prints text specified in quotes on the screen
# Along with he result of calculation of 3 + 2, i.e. 5
print "What is 3 + 2?", 3 + 2
# Prints text specified in quotes on the screen
# Along with he result of calculation of 5 - 7, i.e. -2
print "What is 5 - 7?", 5 - 7
# Prints text specified in quotes on the screen
print "Oh, that's why it's False."
# Prints text specified in quotes on the screen
print "How about some more."
# Prints text specified in quotes on the screen
# Along with the result of comparison 5 > -2 , i.e. True
print "Is it greater?", 5 > -2
# Prints text specified in quotes on the screen
# Along with the result of comparison 5 >= -2 , i.e. True
print "Is it greater or equal?", 5 >= -2
# Prints text specified in quotes on the screen
# Along with the result of comparison 5 <= -2 , i.e. False
print "Is it less or equal?", 5 <= -2 | true |
0fa17731d3a091d92b4961627b6437596480f2b8 | jiteshjitsun/hackerrank | /mergethetools.py | 1,490 | 4.21875 | 4 | '''
Consider the following:
A string, , of length where .
An integer, , where is a factor of .
We can split into subsegments where each subsegment, , consists of a contiguous block of characters in . Then, use each to create string such that:
The characters in are a subsequence of the characters in .
Any repeat occurrence of a character is removed from the string such that each character in occurs exactly once. In other words, if the character at some index in occurs at a previous index in , then do not include the character in string .
Given and , print lines where each line denotes string .
Input Format
The first line contains a single string denoting .
The second line contains an integer, , denoting the length of each subsegment.
Constraints
, where is the length of
It is guaranteed that is a multiple of .
Output Format
Print lines where each line contains string .
Sample Input
AABCAAADA
3
Sample Output
AB
CA
AD
Explanation
String is split into equal parts of length . We convert each to by removing any subsequent occurrences non-distinct characters in :
We then print each on a new line.
'''
#code begins here
def merge_the_tools(string, k):
# your code goes here
l=int(len(string)/k)
for i in range(l):
t=string[i*k:(i+1)*k]
u=""
for c in t:
if c not in u:
u+=c
print(u)
if __name__ == '__main__':
string, k = input(), int(input())
merge_the_tools(string, k)
| true |
7920840d707cebbcbd1a4526bfd18903ca8184be | aaronl647/python-programming | /unit-1/lists.py | 2,100 | 4.15625 | 4 | #declare an empty list
classmates = []
#add items to list
classmates.append('Sue')
classmates.append('Shad')
classmates.append('Mayank')
classmates.append('Gus')
classmates.append('Chin')
classmates.append('Eva')
classmates.append('Jeremy')
classmates.append('Dan')
classmates.append('Julian')
classmates.append('Aaron')
'''
print(classmates)
#access an item at a specific position
#print(classmates[2]) #third element
#get the size of the list
#print(len(classmates))
#remove an item from end of list
classmates.pop()
print(classmates)
#insert at specific position
classmates.insert(0, 'Dan')
print(classmates)
#removing an item from the list
classmates.remove('Gus')
print(classmates)
#edit an item in the list
classmates[1] = 'Sue Work'
print(classmates)
'''
#iterate over a list
'''
for classmate in classmates:
if(classmate == 'Gus'):
print("Great, Gus is in the class!")
'''
'''
#edit elements while iterating
for index, classmate in enumerate(classmates):
#classmates[index] = classmate.upper()
classmates[index] = classmates[index].upper()
print(classmates)
'''
#Create a list of all the Marvel movies from Iron Man to End Game
#Go through the list, and create a second list with all the titles that have 'The' in their names
marvel_movies = ['Iron Man',
'The Incredible Hulk',
'Iron Man II',
'Thor',
'Captain America: The First Avenger',
'The Avengers',
'Iron Man III',
'Thor: The Dark World',
'Captain America: The Winter Soldier',
'Guardians of the Galaxy',
'Avengers: Age of Ultron',
'Ant-Man',
'Captain America: Civil War',
'Doctor Strange',
'Guardians Of The Galaxy Vol. 2',
'Spiderman: Homecoming',
'Thor: Ragnarok',
'Black Panther',
'Avengers: Infinity War',
'Ant-Man and the Wasp',
'Captain Marvel',
'Avengers: Endgame'
]
movies_with_the = []
'''
for index, movie in enumerate(marvel_movies):
if "the " in movie.lower():
movies_with_the.append(movie)
print(movies_with_the)
'''
for index in range(len(marvel_movies)):
print(index)
| true |
c5237d03ee5ed34784bb910040e82b655ed79919 | jessapp/coding-challenges | /daily_temps.py | 917 | 4.25 | 4 | """
Given a list of daily temperatures T, return a list such that,
for each day in the input, tells you how many days you would have
to wait until a warmer temperature. If there is no future day for
which this is possible, put 0 instead.
For example, given the list of temperatures
T = [73, 74, 75, 71, 69, 72, 76, 73],
your output should be [1, 1, 4, 2, 1, 1, 0, 0].
"""
def daily_temps(nums):
# Initialize an empty list
ret = [0] * len(nums)
# Initialize a stack
stack = []
for i, v in enumerate(nums):
# if there is a stack, we want to see which value is
# lower - the current value or the last value in the
# stack.
while stack and stack[-1][1] < v:
index, value = stack.pop()
ret[index] = i - index
# Append to the stack no matter what - this is what fills
# it out
stack.append(i, v)
return ret | true |
d7d4067735f92bbac93c171588e98d0d510cfe24 | jessapp/coding-challenges | /mode.py | 873 | 4.25 | 4 | """Find the most frequent num(s) in nums.
Return the set of nums that are the mode::
>>> find_mode([1]) == {1}
True
>>> find_mode([1, 2, 2, 2]) == {2}
True
If there is a tie, return all::
>>> find_mode([1, 1, 2, 2]) == {1, 2}
True
"""
def find_mode(nums):
"""Find the most frequent num(s) in nums."""
counts = {}
for num in nums:
counts[num] = counts.get(num, 0) + 1
highest_frequency = 0
for frequency in counts.values():
if frequency >= highest_frequency:
highest_frequency = frequency
most_frequent = set()
for num, count in counts.items():
if count == highest_frequency:
most_frequent.add(num)
return most_frequent
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print "\n*** ALL TESTS PASSED. HOORAY!\n"
| true |
87cb6dd8213c17b47e759932eaa34cf4bc4f7426 | jessapp/coding-challenges | /exponentialsquaring.py | 767 | 4.375 | 4 | # calculate x to the power of n in less than O(n) time
# Also known as Exponential Squaring
def pow_recurisve(x, n):
# Base case: if n is 1, return x
if n == 1:
return x
# If n is even, recurse where x is x ^ 2 and n is halved
if n % 2 == 0:
return pow_recurisve(x * x, n / 2)
# Otherwise, recurse given the following parameters
else:
return x * pow_recurisve(x * x, (n-1) / 2)
def pow_iterative(x, n):
r = 1
while n:
print "n", n
if n % 2 == 1:
r *= x
print "r", r
n -= 1
print "new n", n
x *= x
print "x", x
n /= 2
print "new n again", n
return r
print pow_iterative(5, 5)
print pow_recurisve(5, 5) | false |
86462b3c5ed8554af236e3871719d39ba4556a54 | jessapp/coding-challenges | /bst_notes.py | 2,437 | 4.125 | 4 | # DFS traversals:
# In order: Left, root, right
# - Traverse the left subtree
# - Visit the root
# - Traverse the right subtree
# - Used for: In the case of BSTs, gets the nodes in non-decreasing order
# Preorder: Root, left, right
# - Visit the root
# - Traverse the left subtree
# - Traverse the right subtree
# - Used for: creating a copy of the tree
# Postorder: Left, right, root
# - Traverse the left subtree
# - Traverse the right subtree
# - Visit the root
# - Used for: deleting the tree.
class Node:
def __init__(self, value):
self.left = None
self.right = None
self.value = value
def print_in_order(root):
if root:
print_in_order(root.left)
print(root.val)
print_in_order(root.right)
def print_pre_order(root):
if root:
print(root.val)
print_pre_order(root.left)
print_pre_order(root.right)
def print_post_order(root):
if root:
print_post_order(root.left)
print_post_order(root.right)
print(root.val)
# Check if two binary trees are identical
def check_equal(root1, root2):
if not root1 and not root2:
return True
if root1.data == root2.data:
return check_equal(root1.left, root2.left) and check_equal(root1. right, root2.right)
return False
# Calculate the height of a binary tree. The height is defined as the longest
# path from the root to a leaf.
# Interesting adjustment - if you don't want to count the root node, return -1 instead of 0
def calculate_depth(root):
if not root:
return 0
return max(calculate_depth(root.left), calculate_depth.root.right) + 1
# Search a binary search tree for a given value
def search(root, key):
if not root or root.value == key:
return root
if key < root.value:
return search(root.left, key)
elif key > root.value:
return search(root.right, key)
# Insert a new key into a binary tree
def insert(root, new_node):
if root is None:
root = new_node
else:
if root.val < node.val:
if root.right is None:
root.right = node
else:
insert(root.right, node)
else:
if root.left is None:
root.left = node
else:
insnert(root.left, node)
# Delete a node from a binary search tree
# If the node is a leaf, it just needs to be deleted.
| true |
6f2b1db1581ecd4d12a87ba36824e63ab115f6b7 | jessapp/coding-challenges | /max_increase_to_skyline.py | 2,600 | 4.28125 | 4 | """
In a 2 dimensional array grid, each value grid[i][j] represents the height of a building located there. We are allowed to increase the height of any number of buildings, by any amount (the amounts can be different for different buildings). Height 0 is considered to be a building as well.
At the end, the "skyline" when viewed from all four directions of the grid, i.e. top, bottom, left, and right, must be the same as the skyline of the original grid. A city's skyline is the outer contour of the rectangles formed by all the buildings when viewed from a distance. See the following example.
What is the maximum total sum that the height of the buildings can be increased?
Example:
Input: grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]
Output: 35
Explanation:
The grid is:
[ [3, 0, 8, 4],
[2, 4, 5, 7],
[9, 2, 6, 3],
[0, 3, 1, 0] ]
The skyline viewed from top or bottom is: [9, 4, 8, 7]
The skyline viewed from left or right is: [8, 7, 9, 3]
The grid after increasing the height of buildings without affecting skylines is:
gridNew = [ [8, 4, 8, 7],
[7, 4, 7, 7],
[9, 4, 8, 7],
[3, 3, 3, 3] ]
"""
def maxIncreaseKeepingSkyline(grid):
num_rows = len(grid)
new_grid = []
top_bottom_skyline = []
left_right_skyline = []
for horizontal_line in grid:
current_max = 0
max_index = 0
for index, num in enumerate(horizontal_line):
if num > current_max:
current_max = num
max_index = index
left_right_skyline.append(current_max)
for i in range(num_rows):
top_bottom_current_max = 0
top_bottom_max_index = 0
for index, horizontal_line in enumerate(grid):
num = horizontal_line[i]
if num > top_bottom_current_max:
top_bottom_current_max = num
top_bottom_max_index = index
top_bottom_skyline.append(top_bottom_current_max)
for i in range(num_rows):
new_row = []
for j in range(num_rows):
i_constraint = left_right_skyline[i]
j_constraint = top_bottom_skyline[j]
new_value = min(i_constraint, j_constraint)
new_row.append(new_value)
new_grid.append(new_row)
total = 0
for i in range(num_rows):
for j in range(num_rows):
old_val = grid[i][j]
new_val = new_grid[i][j]
increase = new_val - old_val
total += increase
return total
print(total) | true |
4a42123ac60b0f3b667ca645b1c585a154c3f183 | grigor-stoyanov/PythonOOP | /introduction/book.py | 776 | 4.1875 | 4 | class Book:
# dunder methods are called "magicaly" by something else eg. symbol
# self is the name of the variable and is self-asigned
def __init__(self, name, author, pages, private):
# on the current row attach the values to the variable
self.name = name
self.author = author
self.pages = pages
# using __ to an atribute privates it for use only within the class
self.__private = private
# the init is called by "()" creating an instance of the object
book = Book('MyBook', 'Me', 200, 'something private')
# equivalent book = book.__init__('MyBook','Me',200)
print(book.pages)
print(book.name)
print(book.author)
# print(book.private)
# a different object allocated in memory
my_book = Book('MyBook', 'Me', 200)
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.