blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
88044fba92673eae63292c65aa63c804fc4fb041 | ridersw/Karumanchi---Algorithms | /selectionSort.py | 448 | 4.125 | 4 | def selectionSort(arr):
size = len(elements)
for swi in range(len(elements)-1):
minIndex = swi
for swj in range(minIndex+1, size):
if elements[swj] < elements[minIndex]:
minIndex = swj
if swi != minIndex:
elements[swi], elements[minIndex] = elements[minIndex], elements[swi]
if __name__ == "__main__":
elements = [78, 12, 15, 8, 61, 53, 23, 27]
selectionSort(elements)
print("Sorted Array: ", elements) | true |
cd5b89dda0ce27d88438439d7e58b3c89128384d | ianhom/Python-Noob | /Note_1/list.py | 566 | 4.28125 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
list = [ 'abcd', 123, 1.23, 'Ian' ]
smalllist = [ 123, 'Jane' ]
print list # print all elements
print list[0] # print the first element
print list[1:3] # print the second one to the third one
print list[2:] # print the third and following elements
print smalllist * 2 # print small list twice
print list + smalllist # print both list
# result
"""
['abcd', 123, 1.23, 'Ian']
abcd
[123, 1.23]
[1.23, 'Ian']
[123, 'Jane', 123, 'Jane']
['abcd', 123, 1.23, 'Ian', 123, 'Jane']
"""
| false |
c00a4cbed2ed5edb26bbcb8741d12f2e6bc3bf1b | ianhom/Python-Noob | /Note_2/class1.py | 981 | 4.15625 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
class dog:
'This is a dog class' #函数提示
dogcnt = 1;
def __init__(self, name, age): #构造函数
self.name = name
self.age = age
dog.dogcnt += 1
def ShowCnt(self):
print "The count of dog is %d" % dog.dogcnt
def ShowDog(self):
print "Name : ", self.name, ", Age : ", self.age
dog1 = dog("Mike",4)
dog2 = dog("John",5)
dog1.ShowCnt()
dog2.ShowDog()
print dog.dogcnt
print "dog.__doc__:", dog.__doc__
print "dog.__name__:", dog.__name__
print "dog.__module__:", dog.__module__
print "dog.__bases__:", dog.__bases__
print "dog.__dict__:", dog.__dict__
# result
"""
The count of dog is 3
Name : John , Age : 5
3
dog.__doc__: This is a dog class
dog.__name__: dog
dog.__module__: __main__
dog.__bases__: ()
dog.__dict__: {'__module__': '__main__', 'ShowCnt': , 'dogcnt': 3, 'ShowDog': , '__doc__': 'This is a dog class', '__init__': }
"""
| false |
4d4f0c00d086198d3899bce833ed3463c30a5599 | sam-79/Assignment_Submission | /Day1_Assignment.py | 370 | 4.1875 | 4 |
#List sorting in descending order
int_list = [74,4,2,7,55,76,47478,4,21,124,42,4,4,36,6,8,0,95,6]
int_list.sort(reverse=True)
print(int_list)
alpha_list=['t','o','i','q','z','m','v','p','r']
alpha_list.sort(reverse=True)
print(alpha_list)
#User input list sorting
input_list= input("Enter list elements: ").split()
input_list.sort(reverse=True)
print(input_list)
| false |
b68e7cd455c23630cae9c80094108316a5f3683d | agmontserrat/Ejercicios_Python_UNSAM | /Clase07/documentacion.py | 1,155 | 4.125 | 4 | #Para cada una de las siguientes funciones:
#Pensá cuál es el contrato de la función.
#Agregale la documentación adecuada.
#Comentá el código si te parece que aporta.
#Detectá si hay invariantes de ciclo y comentalo al final de la función
def valor_absoluto(num):
'''Devuelve el valor absoluto de un número entero '''
if num >= 0:
return num
else:
return -num
def suma_pares(lista):
'''Devuelve la suma de todos los elementos pares de una lista de números'''
resultado = 0
for elemento in lista:
if elemento % 2 ==0:
resultado += elemento
else:
resultado += 0
return resultado
def veces(a, b):
''' Recibe dos numeros enteros.
Devuelve la suma del numero a tantas veces como el numero b. '''
resultado = 0
contador = b
while contador != 0:
resultado += a
contador -= 1
return resultado
def collatz(n):
resultado = 1
while n!=1:
if n % 2 == 0:
n = n//2
else:
n = 3 * n + 1
resultado += 1
return resultado
| false |
e60d1d29e10422a69b0b867be7f849f4030e51fa | baishuai/leetcode | /algorithms/p151/151.py | 300 | 4.125 | 4 | # Given an input string, reverse the string word by word.
# For example,
# Given s = "the sky is blue",
# return "blue is sky the".
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
return ' '.join(reversed(s.split()))
| true |
17fd1c22103dd367ed6e6488eff4330f2928d0e7 | xieguoyong/shiyanlou | /cases/python_captcha/sort_test.py | 772 | 4.3125 | 4 | dic = {'a': 31, 'bc': 5, 'c': 3, 'asd': 4, 'aa': 74, 'd': 0}
print("打印出字典的键和值的列表:", dic.items())
# sorted 方法中 key指定按什么排序
# 这里的 lambda x: x[1] 即指定以列表的x[1] 即value来排序,x[0]则是以key排序
print("指定以value来排序:", sorted(dic.items(), key=lambda x: x[1]))
# sorted 默认从小到大排序,加上reverse=True 参数则翻转为从大到小排序
print("指定从大到小排序:", sorted(dic.items(), key=lambda x: x[1], reverse=True))
# 打印列表前几个值
print("指定打印出前3个值:", sorted(dic.items(), key=lambda x: x[1], reverse=True)[:3])
# 分别打印出key 和 value
for i, j in sorted(dic.items(), key=lambda x: x[1], reverse=True)[:3]:
print(i, j)
| false |
181f19fec56913372b5aa480dfea3e5d3c4c91b8 | senseiakhanye/pythontraining | /section5/ifelseif.py | 246 | 4.21875 | 4 | isFound = True
if (isFound):
print("Is found")
else:
print("Is not found")
#else if for python is different
num = 2
if (num == 1):
print("Number is one")
elif (num == 2):
print("Number if two")
else:
print("Number is three") | true |
baca925b539e5fcc04be482c5fc8b27a6ff355eb | johnstinson99/introduction_to_python | /course materials/b05_matplotlib/d_sankey/sankey_example_1_defaults.py | 1,070 | 4.34375 | 4 | """Demonstrate the Sankey class by producing three basic diagrams.
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.sankey import Sankey
# Example 1 -- Mostly defaults
# This demonstrates how to create a simple diagram by implicitly calling the
# Sankey.add() method and by appending finish() to the call to the class.
# flows:
# positive flow goes into the main stream.
# negative flow comes out of the main stream.
# orientations:
# 0 = horizontal
# 1 = vertical upwards
# -1 = vertical downwards
Sankey(flows=[0.25, 0.15, 0.60, -0.20, -0.15, -0.05, -0.50, -0.10],
labels=['1st', '2nd', '3rd', '4th', '5th', '6th', '7th', '8th'],
orientations=[-1, 1, 0, 1, 1, 1, 0, -1]).finish()
plt.title("The default settings produce a diagram like this.")
# Notice:
# 1. Axes weren't provided when Sankey() was instantiated, so they were
# created automatically.
# 2. The scale argument wasn't necessary since the data was already
# normalized.
# 3. By default, the lengths of the paths are justified.
plt.show() | true |
1fc9ba256d1201e878b76e6d9419d162d0e9cd59 | anuragpatilc/anu | /TAsk9_Rouletle_wheel_colors.py | 992 | 4.375 | 4 | # Program to decides the colour of the roulette wheel colour
# Ask the user to select the packet between 0 to 36
packet = int(input('Enter the packet to tell the colour of that packet: '))
if packet < 0 or packet > 36:
print('Please enter the number between 0 to 36')
else:
if packet == 0:
print('Your selected packet GREEN')
elif packet < 11:
if packet % 2 == 0:
print('Your selected packet BLACK')
else:
print('Your selected packet RED')
elif packet < 19:
if packet % 2 == 0:
print('Your selected packet RED')
else:
print('Your selected packet BLACK')
elif packet < 29:
if packet % 2 == 0:
print('Your selected packet BLACK')
else:
print('Your selected packet RED')
else:
if packet % 2 == 0:
print('Your selected packet RED')
else:
print('Your selected packet BLACK')
| true |
83ccf65950e90bd1cf095c29e5b1c61b1d7a75d9 | zeus911/sre | /leetcode/Search-for-a-Range.py | 1,062 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'liuhui'
'''
Given an array of integers sorted in ascending order, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].
'''
class Solution:
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
temp, l = 0, -1
for i in range(len(nums)):
if nums[i] == target and temp == 0:
temp = 1
l = i
elif nums[i] == target and temp != 0:
temp += 1
else:
pass
if l != -1:
return [l, l+temp-1]
else:
return [-1, -1]
if __name__ == '__main__':
nums = [5, 7, 7, 8, 8, 10]
solut = Solution()
res = solut.searchRange(nums, 8)
print(res)
| true |
1dfd1b6ceeaaa4e18804ebdf96697fff2e494a25 | mimichen226/GirlsWhoCode_SIP2018 | /Python/Libraries/DONE_rock_paper_scissors.py | 562 | 4.1875 | 4 | ########### Code for Rock Paper Scissors ############
import random
gestures = ["scissors", "rock", "paper"]
computer = random.choice(gestures)
human = input("Rock, paper, scissors, SHOOT: ")
human = human.lower().lstrip().rstrip()
print("Computer chooses {}".format(computer.upper()))
if computer == human:
print("TIE")
elif (computer == "scissors" and human == "paper") or (computer == "paper" and human == "rock") or (computer == "rock" and human == "scissors"):
print("You lost. Go computers. ")
else:
print("You win! Down with computers. ")
| true |
bff09661d3f94c924370978ec58eba596f184bcc | penelopy/interview_prep | /Basic_Algorithms/reverse_string.py | 389 | 4.3125 | 4 | """ Reverse a string"""
def reverse_string(stringy):
reversed_list = [] #strings are immutable, must convert to list and reverse
reversed_list.extend(stringy)
for i in range(len(reversed_list)/2):
reversed_list[i], reversed_list[-1 - i] = reversed_list[-1 -i], reversed_list[i]
print "".join(reversed_list)
string1 = "cat in the hat"
reverse_string(string1)
| true |
6507cb3071727a87c6c7309f92e7530b74fcc5a2 | penelopy/interview_prep | /Trees_and_Graphs/tree_practice_file.py | 1,262 | 4.25 | 4 | """NOTES AND PRACTICE FILE
Ex. Binary Tree
1
/ \
2 3
Ex. Binary Search Tree
2
/ \
1 3
A binary search is performed on sorted data. With binary trees you use them to quickly look up numbers and compare them. They have quick insertion and lookup.
"""
class BinarySearchTree:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def get_right(self):
return self.right
def set_right(self, node):
self.right = node
def get_left(self):
return self.left
def set_left(self, node):
self.left = node
def set_value(self, number):
self.value = number
def depth_first_traversal(self, node):
""" DFT, recursive"""
print node.value,
if node.left:
depth_first_traversal(node.left)
if node.right:
depth_first_traversal(node.right)
def breath_first_traversal(self, node):
if not node:
return None
else:
queue = [node]
while len(queue) > 0:
current = queue.pop(0)
print current.value,
if current.left:
queue.append(current.left)
if current.right:
queue.append(current.right)
| true |
a6cfcadcba5fb1aba6dc49e653b2ac9625f18de2 | chieinviolet/oop_project2 | /user_name.py | 929 | 4.15625 | 4 | """
※雰囲気コード
データ型宣言: UserName <<python ではクラス型と呼ばれる。
属性:
実際のユーザー名
ルール:
・ユーザー名は4文字以上20文字以下である
できること
・ユーザー名を大文字に変換する
"""
class UserName:
def __init__(self, name):
if not (4 <= len(name) <= 20):
raise ValueError(f'{name}は文字数違反やで!')
self.name = name
def screen_name(self):
return self.name.upper()
# UserNameクラスのインスタンス化
hibiki = UserName(name='Hibiki')
# print (hibiki)
# print(type (hibiki))<<<<<type がUserNameになる!?
# print(hibiki.name)
# <<<<UserNameクラスのインスタンス化
# sho = UserName(name = 'Sho')
# print(sho.name)
# こんなんあったらうれしい!から入る。option + enter で実装。
print(hibiki.screen_name())
| false |
29b81abb43d6167f5ead8d625e705a9675831b8d | bavipanda/Bavithra | /check the given is alphabets or digits.py | 207 | 4.25 | 4 | ch = input()
if((ch >= 'a' and ch <= 'z') or (ch >= 'A' and ch <= 'Z')):
print("is an Alphabet")
elif(ch >= '0' and ch <= '9'):
print("is a Digit")
else:
print("is Not an Alphabet or a Digit")
| false |
2bec8e896b556bc8077e14e4ee64cec5957a6ef8 | ak14249/Python | /dictionary.py | 578 | 4.25 | 4 | myDict={"Class" : "Engineer", "Name" : "Ayush", "Age" : "25"}
print(myDict)
print(myDict["Class"])
print(myDict.get("Name"))
print(myDict.values())
for val in myDict:
print(myDict[val])
for x,y in myDict.items():
print(x,y)
myDict["Name"]="Prateek"
print(myDict)
myDict["Designation"]="Linux Admin"
print(myDict)
myDict.pop("Designation") #It will remove Designation from dictionary
print(myDict)
myDict.popitem() #It will remove last entry
print(myDict)
del myDict["Class"]
print(myDict)
myDict.clear() #It will clrear all dictionary
print(myDict)
| false |
2ee39e37dec9a9c5df1f70683a5a01d2a6935f09 | ak14249/Python | /map_function.py | 2,336 | 4.40625 | 4 | print("Que: Write a map function that adds plus 5 to each item in the list.\n")
lst1=[10, 20, 30, 40, 50, 60]
lst2=list(map(lambda x:x+5,lst1))
print(lst2)
print("\n=========================================================\n")
print("Que: Write a map function that returns the squares of the items in the list.\n")
lst1=[10, 20, 30, 40, 50, 60]
lst2=list(map(lambda x:x*x,lst1))
print(lst2)
print("\n=========================================================\n")
print("Que: Write a map function that adds Hello, in front of each item in the list.\n")
lst1=["Jane", "Lee", "Will", "Brie"]
lst2=list(map(lambda x:"Hello, "+x,lst1))
print(lst2)
print("\n=========================================================\n")
print("Que: Using map() function and len() function create a list that's consisted of lengths of each element in the first list.\n")
lst1=["Alpine", "Avalanche", "Powder", "Snowflake", "Summit"]
lst2=list(map(lambda x:len(x),lst1))
print(lst2)
print("\n=========================================================\n")
print("Que: Using map() function and lambda add each elements of two lists together. Use a lambda with two arguments.\n")
lst1=[100, 200, 300, 400, 500]
lst2=[1,10,100,1000,10000]
lst3=list(map(lambda x,y:x+y,lst1,lst2))
print(lst3)
print("\n=========================================================\n")
print("Que: Using map() function and lambda and count() function create a list which consists of the number of occurence of letter: a.\n")
lst1=["Alaska", "Alabama", "Arizona", "Arkansas", "Colorado", "Montana", "Nevada"]
lst2=list(map(lambda x:x.count("a"),lst1))
print(lst2)
print("\n=========================================================\n")
print("Que: Using map() function and lambda and count() function create a list consisted of the number of occurence of both letters: A and a.\n")
lst1=["Alaska", "Alabama", "Arizona", "Arkansas", "Colorado", "Montana", "Nevada"]
lst2=list(map(lambda x:x.lower().count("a"),lst1))
print(lst2)
print("\n=========================================================\n")
print("Que: Using map() function, first return a new list with absolute values of existing list. Then for ans_1, find the total sum of the new list's elements.\n")
lst=[99.3890,-3.5, 5, -0.7123, -9, -0.003]
new_lst=list(map(abs,lst))
ans_1=sum(new_lst)
print(ans_1)
| true |
6098028a07d94854e273ca763d3ff1f566ea6c4d | karthikrk1/python_utils | /primeSieve.py | 1,330 | 4.34375 | 4 | #!/bin/python3
'''
This is an implementation of the sieve of eratosthenes. It is created for n=10^6 (Default Value).
To use this in the program, please import this program as import primeSieve and call the default buildSieve method
Author: Karthik Ramakrishnan
'''
def buildSieve(N=1000000):
'''
This function is an implementation of the sieve of eratosthenes. The function creates a boolean array of size N and marks the
prime numbers as True. This is an utility function that creates a boolean array for the sieve and sets up the prime numbers.
Args:
N - The upper bound until which we need to set up the sieve.
Return:
isPrime - The boolean array with all the prime numbers set as True. The remaining values are made False.
'''
N+=1 # This is to make sure we have the N inclusive in the array and not getting it lost due to 0-based indexing of Python lists
isPrime = [True] * N # Initializing the isPrime list with all True values.
isPrime[0] = isPrime[1] = False # Since 0 and 1 are considered Neither Prime nor composite. So we make them False.
for (ind, num) in enumerate(isPrime):
if num:
for no in range(ind*ind, N, ind): # This is used to mark the factors as not Prime.
isPrime[no] = False
return isPrime
| true |
af8e0ab5c3cabbda9b75721c81492e285345c9d3 | brianhoang7/6a | /find_median.py | 940 | 4.28125 | 4 | # Author: Brian Hoang
# Date: 11/06/2019
# Description: function that takes list as parameter and finds the median of that list
#function takes list as parameter
def find_median(my_list):
#sorts list from least to greatest
my_list.sort()
#distinguishes even number of items in list
if len(my_list) % 2 == 0:
#finding the smallest number of the second half of the list
num1 = my_list[int(len(my_list)/2)]
#finding the largest number of the first half of the list
num2 = my_list[int(len(my_list)/2 - 1)]
#adding the two numbers up and dividing by 2 to return the median
sum1 = num1 + num2
return sum1/2
#finds the number in the center of the list to return as the median for lists with odd number of objects
elif len(my_list) % 2 != 0:
num1 = my_list[round(len(my_list)/2)]
return num1
#my_list = [4,5,3,7,8,3,1,12,13]
#print(find_median(my_list)) | true |
bbacdc29ca3d75eeaee34e1d9800e57b390bd83c | pastcyber/Tuplesweek4 | /main.py | 917 | 4.1875 | 4 | value = (5, 4, 2000, 2.51, 8, 9, 151)
def menu():
global value
option = ''
while(option != 6):
print('*** Tuple example ***')
print('1. Print Tuple ***')
print('2. Loop over tuple')
print('3. Copy Tuple')
print('4. Convert to list')
print('5. Sort Tuple')
print('6. Exit ***')
option = int(input('Please enter option: '))
if(option == 1):
print(value)
elif(option == 2):
continue
elif(option == 3):
start = int(input('Enter start of range: '))
end = int(input('Enter start of range: '))
newtuple = value[start:end]
print(newtuple)
elif(option == 4):
templist = list(value)
templist.append(100)
value = tuple(templist)
print(value)
elif(option == 5):
templist = list(value)
templist = sorted(value)# reverse = True (descending)
value = tuple(templist)
print(value)
| true |
70f84fb61188d4a12f42bc5ab4e90f190dde764b | YOOY/leetcode_notes | /problem/check_if_number_is_a_sum_of_powers_of_three.py | 292 | 4.15625 | 4 | # check if n can be formed by 3**0 + 3**1 + ... + 3**n
# if any r equals to 2 it means we need 2 * (3 ** n) which should be false
def checkPowersOfThree(n):
while n > 1:
n, r = divmod(n, 3)
if r == 2:
return False
return True
print(checkPowersOfThree(21)) | true |
07815b759c627172f59ac80c7bc403f6b9b48a90 | Aditi-Billore/leetcode_may_challenge | /Week2/trie.py | 2,258 | 4.1875 | 4 | # Implementation of trie, prefix tree that stores string keys in tree. It is used for information retrieval.
#
class TrieNode:
def __init__(self):
self.children = [None] *26
self.isEndOfWord = False
class Trie:
def __init__(self):
self.root = self.getNode()
def getNode(self):
return TrieNode()
def _charToIndex(self, letter):
# return index value of character to be assigned in array
return ord(letter) - ord('a')
def insert(self, key):
pCrawl = self.root
length = len(key)
for level in range(length):
index = self._charToIndex(key[level])
# if current character is not present
if not pCrawl.children[index]:
pCrawl.children[index] = self.getNode()
pCrawl = pCrawl.children[index]
# mark last node as leaf
pCrawl.isEndOfWord = True
def search(self, key):
pCrawl = self.root
length = len(key)
for level in range(length):
index = self._charToIndex(key[level])
if not pCrawl.children[index]:
return False
pCrawl = pCrawl.children[index]
return pCrawl != None and pCrawl.isEndOfWord
def startsWith(self, key):
pCrawl = self.root
length = len(key)
for level in range(length):
index = self._charToIndex(key[level])
if not pCrawl.children[index]:
return False
pCrawl = pCrawl.children[index]
return pCrawl != None
def main():
keys = ["the","a","there","anaswe","any","by","their"]
output = ["Not present in trie","Present in trie"]
# Trie object
t = Trie()
# Construct trie
for key in keys:
t.insert(key)
# Search for different keys
print("{} --{}-- {}".format("the","search",output[t.search("the")]))
print("{} --{}-- {}".format("these","search",output[t.search("these")]))
print("{} --{}-- {}".format("their","search",output[t.search("their")]))
print("{} --{}-- {}".format("thaw","startsWith",output[t.startsWith("th")]))
print("{} --{}-- {}".format("anyw","startsWith",output[t.startsWith("anyw")]))
if __name__ == "__main__":
main()
| true |
7b9424dc3a0cf43e35df9557d8739d48587ad0a1 | jcarlosbatista/pacote-desafios-pythonicos | /07_front_back.py | 2,802 | 4.125 | 4 | """
07. front_back
Considere dividir uma string em duas metades.
Caso o comprimento seja par, a metade da frente e de trás tem o mesmo tamanho.
Caso o comprimento seja impar, o caracter extra fica na metade da frente.
Exemplo: 'abcde', a metade da frente é 'abc' e a de trás é 'de'.
Finalmente, dadas duas strings a e b, retorne uma string na forma:
a-frente + b-frente + a-trás + b-trás
"""
import math
def front_back(a, b):
size_a = len(a)
size_b = len(b)
if size_a % 2 == 0 and size_b % 2 == 0:
size_a, size_b = size_a // 2, size_b // 2
front_a = a[:size_a]
back_a = a[size_a:]
front_b = b[:size_b]
back_b = b[size_b:]
return front_a + front_b + back_a + back_b
elif size_a % 2 == 1 and size_b % 2 == 1:
size_a, size_b = (size_a // 2) + 1, (size_b // 2) + 1
front_a = a[:size_a]
back_a = a[size_a:]
front_b = b[:size_b]
back_b = b[size_b:]
return front_a + front_b + back_a + back_b
elif size_a % 2 == 1 and size_b % 2 == 0:
size_a, size_b = (size_a // 2) + 1, (size_b // 2)
front_a = a[:size_a]
back_a = a[size_a:]
front_b = b[:size_b]
back_b = b[size_b:]
return front_a + front_b + back_a + back_b
elif size_a % 2 == 0 and size_b % 2 == 1:
size_a, size_b = (size_a // 2), (size_b // 2) + 1
front_a = a[:size_a]
back_a = a[size_a:]
front_b = b[:size_b]
back_b = b[size_b:]
return front_a + front_b + back_a + back_b
def front_back(a, b):
size_a = len(a)
size_b = len(b)
front_a = a[:math.ceil(size_a/2)]
back_a = a[math.ceil(size_a / 2):]
front_b = b[:math.ceil(size_b / 2)]
back_b = b[math.ceil(size_b / 2):]
return ''.join([front_a, front_b, back_a, back_b])
def front_back(a, b):
idx_a = math.ceil(len(a) / 2)
idx_b = math.ceil(len(b) / 2)
return ''.join((a[:idx_a], b[:idx_b], a[idx_a:], b[idx_b:]))
# --- Daqui para baixo são apenas códigos auxiliáries de teste. ---
def test(f, in_, expected):
"""
Executa a função f com o parâmetro in_ e compara o resultado com expected.
:return: Exibe uma mensagem indicando se a função f está correta ou não.
"""
out = f(*in_)
if out == expected:
sign = '✅'
info = ''
else:
sign = '❌'
info = f'e o correto é {expected!r}'
print(f'{sign} {f.__name__}{in_!r} retornou {out!r} {info}')
if __name__ == '__main__':
# Testes que verificam o resultado do seu código em alguns cenários.
test(front_back, ('abcd', 'xy'), 'abxcdy')
test(front_back, ('abcde', 'xyz'), 'abcxydez')
test(front_back, ('Kitten', 'Donut'), 'KitDontenut')
test(front_back, ('Donut', 'Kitten'), 'DonKitutten')
| false |
b591729dcfbbb565158ad7a7541b8bfaa0378cda | Tu7ex/Python_Programming | /Clase1.py | 2,565 | 4.21875 | 4 | '''Comentario'''
#adsasd
var = 1
print(type(var)) #Muestra el tipo de variable que es.
print("")
# Cadena de caracteres
cadena1="Clase n° 1"
cadena2='Curzo de Python'
print(type(cadena1))
# Boolean (True -> V, False -> F)
encendido= True
print(type(encendido))
print("")
# Operadores aritméticos
# Suma
x=20
y=5
res = x-y
print(res)
# Suma
res=x+y
print(res)
#Mult
res=x*y
print(res)
# Exponente **
res = x**2
print(res)
print("")
# Division entera //
res= x//3
# Modulo %. Divide el operando de la izquierda por el operador de
# la derecha y devuelve el resto.
res=7%2
print(res)
print("")
# Operaciones con cadena
print(cadena1+" "+cadena2)
print(cadena1*2)
print("")
# Operaciones logicas con retorno Boolean
print(x==20) # True
print(x==2) # False
print(x!=20) # Negación que afirma que es verdad
print(x!=2) # Negación que afirma que es falso
print("")
# Listas = Arrays
personas=[]
personas=["Juan","Ana","Marcelo"]
numeros=[1, 2, 3, 10]
print(personas[0])
print("")
varios1=[True, -5, "hola mundo", [1, 10]]
varios1[3]= "Inicio de la clase"
print(varios1[3]) # Muestra lista dentro de lista
print("")
# Append -> Agrega un elemento al final
numeros.append(100)
print(numeros)
print("")
#Insert -> Inserta un elemento en una ubicacion especifica
numeros.insert(0, -20)
print(numeros)
print("")
#Eliminar elemento
del personas[2]
print(personas)
print("")
# Tuplas -> Inmutables. No se pueden modificar
var_t=(10, 20, 6)
print(var_t[0])
print("")
var_t_unica=(10,) # Crearcion tupla con un solo valor
print(var_t_unica[0])
print("")
var1=[10, 20, 30]
var2=[40, 50]
print(var1+var2)
print("")
# Diccionarios -> Clave: Valor
cliente={"Nombre": "Juan", "Edad":25, "Direccion":"25 de Mayo 1000"}
print("")
# None (is) -> Boolean
n=None
print(n is None)
print("")
# Operaciones logicas
#Conjuncion -> Retorna True siempre que ambos lados de la operacion sean verdaderas
print(True and True)
print(False and True)
print("")
# Disyuncion -> Reterona True siempre que alguno de los operandos sea True
print(True or True)
print(False or True)
print(False or False)
print("")
# Negacion -> not
print(not True)
print("")
#Condicionales
'''
edad=int(input("ingrese edad: "))
if(edad>18):
print("Mayor de edad")
else:
print("Menor de edad")
'''
#for
lista=[10, 20, 30, 40]
for lis in lista:
print(lis)
for i in range(1, 21):
print("Curso python")
print("")
personas=["Juan","Ana","Marcelo", "Matias"]
for i in range(len(lista)):
nombre=personas[i]
print(nombre,i)
print("")
#Enumerate
for i, nombre in enumerate(personas):
print(i, nombre) | false |
239d29e78ee6f68d72bcda0a08f25d62ee223b7d | ellezv/data_structures | /src/trie_tree.py | 2,588 | 4.1875 | 4 | """Implementation of a Trie tree."""
class TrieTree(object):
"""."""
def __init__(self):
"""Instantiate a Trie tree."""
self._root = {}
self._size = 0
def insert(self, iter):
"""Insert a string in the trie tree."""
if type(iter) is str:
if not self.contains(iter):
self._size += 1
start = self._root
for letter in iter:
start.setdefault(letter, {})
start = start[letter]
start["$"] = {}
return
raise TypeError("Please enter a string.")
def contains(self, value):
"""Will return True if the string is in the trie, False if not."""
if type(value) is str:
start = self._root
for letter in value:
try:
start = start[letter]
except KeyError:
return False
if "$" in start.keys():
return True
return False
def size(self):
"""Return the size of the Trie tree. O if empty."""
return self._size
def remove(self, value):
"""Will remove the given string from the trie."""
if type(value) is str:
current_letter = self._root
for letter in value:
try:
current_letter = current_letter[letter]
except KeyError:
break
if "$" in current_letter.keys():
del(current_letter['$'])
if len(current_letter.keys()):
return
for letter in value[::-1]:
current_letter = letter
if current_letter is {}:
del current_letter
else:
break
raise KeyError("Cannot remove a word that is not in the Trie.")
def traversal(self, string):
"""Depth first traversal."""
if type(string) is str:
dict_cur = self._root
for letter in string:
try:
dict_cur = dict_cur[letter]
except KeyError:
break
for letter in dict_cur.keys():
if letter != '$':
yield letter
for item in self.traversal(string + letter):
yield item
if __name__ == '__main__':
tt = TrieTree()
words = ['otter', 'other', 'apple', 'apps', 'tea', 'teabag', 'teapot']
for i in words:
tt.insert(i)
| true |
64f36d53d21666be487100bd9d919afd18ece35c | ginchando/SimplePython | /CheckLeapYear/check.py | 731 | 4.1875 | 4 | year = int(input("Enter a year: "))
month = int(input("Enter a month: "))
isLeapYear = False
if year % 400 == 0:
isLeapYear = True
elif year % 4 == 0 and year % 100 != 0:
isLeapYear = True
result = "is" if isLeapYear else "is not"
print(f"{year} {result} a leap year")
month_name = {
1: "January",
2: "February",
3: "March",
4: "April",
5: "May",
6: "June",
7: "July",
8: "August",
9: "September",
10: "October",
11: "November",
12: "December"
}
name = month_name.get(month)
month_days = {
1: 31, 3: 31, 4: 30, 5: 31, 6: 30,
7: 31, 8: 31, 9: 30, 10: 31, 11: 30,
12: 31, 2: 29 if isLeapYear else 28
}
days = month_days.get(month)
print(f"{name} has {days} days") | false |
20e60f62e4865b7a1beb1cdd67330159ebbba35c | LesterZ819/PythonProTips | /PythonBasics/Lists/CreatingLists.py | 534 | 4.15625 | 4 | #You can create a list of values by putting them in [brackets] and assigning them a variable.
#For example:
varialble = [item1, item2, item3, item4]
#lists can contain any time of value, or multiple value types
#Example list containing floats or real numbers.
float = [1.25, 15.99, 21.33]
#Example of a list containing int or integer numbers.
int = [1, 2, 3, 4]
#Example of a list containing str or strings.
str = ["a", "b", "c"]
#Example of a list containing bool or boolean values.
bool = [True, False, True, True]
| true |
9f13a8c2f6f5d0f9095da83f175c15a51108096c | LukeBecker15/learn-arcade-work | /Lab 06 - Text Adventure/lab_06.py | 2,656 | 4.15625 | 4 | class Room:
def __init__(self, description, north, south, east, west):
self.description = description
self.north = north
self.south = south
self.east = east
self.west = west
def main():
room_list = []
room = Room("You are in the entrance to the Clue house.\nThe path leads north.", 2, None, None, None)
room_list.append(room)
room = Room("You are in the billiard room.\nThe path leads north and east.", 4, None, 2, None)
room_list.append(room)
room = Room("You are in the ballroom.\nThe path leads north, south, east, and west.", 5, 0, 3, 1)
room_list.append(room)
room = Room("You are in the kitchen.\nThe path leads north and west.", 6, None, None, 2)
room_list.append(room)
room = Room("You are in the library.\nThe path leads south and east.", None, 1, 5, None)
room_list.append(room)
room = Room("You are in the study.\nThe path leads south, east, and west.", None, 2, 6, 4)
room_list.append(room)
room = Room("You are in the dining room.\nThe path leads south and west.", None, 3, None, 5)
room_list.append(room)
current_room = 0
done = False
while done == False:
print()
print(room_list[current_room].description)
next_room = input("What direction do you want to move? ")
if next_room.title() == "N" or next_room.title() == "North":
next_room = room_list[current_room].north
if next_room == None:
print()
print("You can't go this way.")
else:
current_room = next_room
elif next_room.title() == "S" or next_room.title() == "South":
next_room = room_list[current_room].south
if next_room == None:
print()
print("You can't go this way.")
else:
current_room = next_room
elif next_room.title() == "E" or next_room.title() == "East":
next_room = room_list[current_room].east
if next_room == None:
print()
print("You can't go this way.")
else:
current_room = next_room
elif next_room.title() == "W" or next_room.title() == "West":
next_room = room_list[current_room].west
if next_room == None:
print()
print("You can't go this way.")
else:
current_room = next_room
elif next_room.title() == "Q" or next_room.title() == "Quit":
done = True
print()
print("The game is over.")
main()
| true |
183d3360519f1935140cefd8830662d0f168e6ae | DhirajAmbure/MachineLearningProjects | /PythonPracticePrograms/factorialOfNumber.py | 1,225 | 4.28125 | 4 | import math as m
def findfact(number):
if number == 1:
return number
elif number != 0:
return number * findfact(number - 1)
number = int(input("Enter number to find Factorial: "))
if number < 0:
print("factorial can not be found for negative numbers")
elif number ==0:
print("Factorial of 0 is 1")
else:
print("Factorial of {} is {}".format(number,findfact(number)))
print("Factorial of {} using function from math package is {}".format(number,m.factorial(number)))
# def findFact(number):
# if(number==0 | number==1):
# return 1
# elif (number > 1):
# return number * findFact(number-1)
#
# varFact = int(input("Please Enter the number to find Factorial"))
# fact = 0
# if(varFact < 0):
# print("Please enter +ve number to find factorial")
# else:
# print("factorial of {} is {}".format(varFact,findFact(varFact)))
#
"""Using while loop"""
def factUsingWhile(number):
"""To find the factorial of given parameter"""
factr = 1
while(number>0):
factr *= number
number -= 1
return factr
factr_vari = int(input("Enter the number: "))
print(factUsingWhile(factr_vari)) | true |
4318daad6d05bf2528b5025bab4974939267bf07 | Ladydiana/LearnPython | /CompoundDataStructures.py | 1,229 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
COMPOUND DATA STRUCTURES
"""
elements = {"hydrogen": {"number": 1,
"weight": 1.00794,
"symbol": "H"},
"helium": {"number": 2,
"weight": 4.002602,
"symbol": "He"}}
helium = elements["helium"] # get the helium dictionary
hydrogen_weight = elements["hydrogen"]["weight"] # get hydrogen's weight
oxygen = {"number":8,"weight":15.999,"symbol":"O"} # create a new oxygen dictionary
elements["oxygen"] = oxygen # assign 'oxygen' as a key to the elements dictionary
print('elements = ', elements)
# todo: Add an 'is_noble_gas' entry to the hydrogen and helium dictionaries
# hint: helium is a noble gas, hydrogen isn't
hydrogen = {"number": 1,
"weight": 1.00794,
"symbol": "H",
"is_noble_gas": False
}
helium = {"number": 2,
"weight": 4.002602,
"symbol": "He",
"is_noble_gas": True
}
elements["hydrogen"] = hydrogen
elements["helium"] = helium
print(elements)
#or
#elements['hydrogen']['is_noble_gas'] = False
#elements['helium']['is_noble_gas'] = True
| false |
18a845aa39833a9b137bd19759c543a8a77054b6 | Ladydiana/LearnPython | /ListComprehensions.py | 959 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
LIST COMPREHENSIONS
"""
#capitalized_cities = [city.title() for city in cities]
squares = [x**2 for x in range(9) if x % 2 == 0]
print(squares)
#If you would like to add else, you have to move the conditionals to the beginning of the listcomp
squares = [x**2 if x % 2 == 0 else x + 3 for x in range(9)]
print(squares)
"""
QUIZ - Extract First Names
"""
names = ["Rick Sanchez", "Morty Smith", "Summer Smith", "Jerry Smith", "Beth Smith"]
first_names = [name.split()[0].lower() for name in names]
print(first_names)
"""
QUIZ - Multiples of Three
"""
count = 0
multiples_3 = [x * 3 for x in range(1, 21)]
print(multiples_3)
"""
QUIZ - Filter Names by Scores
"""
scores = {
"Rick Sanchez": 70,
"Morty Smith": 35,
"Summer Smith": 82,
"Jerry Smith": 23,
"Beth Smith": 98
}
passed = passed = [name for name, score in scores.items() if score >= 65]
print(passed) | true |
1a4584feb95da66abab5d2b0cb40664f2eab59dc | Ladydiana/LearnPython | /LambdaExpressions.py | 872 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
LAMBDA EXPRESSIONS
---You can use lambda expressions to create anonymous functions.
"""
multiply = lambda x, y: x * y
print(multiply(4, 7))
"""
QuUIZ - Lambda with Map
"""
numbers = [
[34, 63, 88, 71, 29],
[90, 78, 51, 27, 45],
[63, 37, 85, 46, 22],
[51, 22, 34, 11, 18]
]
###def mean(num_list):
### return sum(num_list) / len(num_list)
averages = list(map(lambda num_list: sum(num_list)/len(num_list) , numbers))
print(averages)
"""
QUIZ - Lambda with Filter
"""
cities = ["New York City", "Los Angeles", "Chicago", "Mountain View", "Denver", "Boston"]
#def is_short(name):
# return len(name) < 10
#short_cities = list(filter(is_short, cities))
short_cities = list(filter(lambda name: len(name)<10, cities))
print(short_cities) | false |
e5f63dd75eadec1499cb15037c3b4623ace06b76 | abhi472/Pluralsight | /Chapter5/classes.py | 1,035 | 4.1875 | 4 | students = []
class Student:
school_name = "Sumermal Jain Public School" # this is similar to a static variable but unlike java we do not need to have a static class for static variables we
# can have a class instance just like school_name for static call of it
def __init__(self, name, student_id = 112):
self.name = name # self is an equivalent of this
self.student_id = student_id # both self.name and self.student are member variables known as instance variables in python
students.append(self)
def __str__(self): # overriding
return "student : " + self.name
def get_school_name(self):
return self.school_name
# mark = Student("mark")
# print(mark)
#
# print(Student.school_name)
#
# Student.school_name = "wowo"
#
# print(Student.school_name)
#
# print(mark.get_school_name()) # as expected the school_name will have the same value across all class objects
| true |
62eadc4c3eb829a71a0a2fd24282da4a2c8f3232 | abhi472/Pluralsight | /Chapter3/rangeLoop.py | 444 | 4.375 | 4 | x = 0
for index in range(10): # here range creates a list of size 10(argument that has been passed)
x += 10
print("The value of X is {0}".format(x))
for index in range(5, 10): # two args mean list start from 5 and goes till 9
x += 10
print("The value of X is {0}".format(x))
for index in range(5, 10, 2): # three args mean list start from 5 and increments two till 9
x += 10
print("The value of X is {0}".format(x)) | true |
c5f3a449b0a84d29787adc5ecbd2438fe616aed2 | lampubolep/HackerRank30days | /day3.py | 458 | 4.3125 | 4 | # receiving input integer
n = int(input())
# if n is odd, print Weird
if (n % 2) != 0:
print("Weird")
# if n is even and in the inclusive range of 2 to 5, print Not Weird
elif (n%2 == 0 and n>=2 and n<=5):
print("Not Weird")
#if n is even and in the inclusive range of 6 to 20 print Weird
elif (n%2 == 0 and n>=6 and n<=20):
print("Weird")
#if n is even and greater than 20, print Not Weird
elif (n%2 == 0 and n>20 and n<=100):
print("Not Weird")
| false |
80b8be8ba4fabddfcffaf7d8a69039c83679938f | JubindraKc/python_assignment_dec15 | /#4_firstname_lastname_split.py | 503 | 4.28125 | 4 | def full_name():
print("your first name is ", first_name)
print("your last name is ", last_name)
choice = input("will you include your middle name? y/n\n")
name = input("please enter your full name separated with whitespace\n")
if choice == 'y':
first_name, last_name, middle_name = name.split(" ")
full_name()
print('your middle name is ', middle_name)
elif choice == 'n':
first_name, last_name = name.split(" ")
full_name()
else:
print("error")
| true |
48d8c9acfbbe437a075f8850b40559cc5a7d52d7 | simonechen/PythonStartUp | /ex1.py | 407 | 4.1875 | 4 | # print("Hello World!")
# print("Hello Again")
# print("I like typing this.")
# print("This is fun.")
# print("Yay! Pringting.")
# print("I'd much rather you 'not'.")
print('I "said" do not touch this.') # ' "" '
print("I'm back.") # Terminate
print("-how to make my script print only one of the lines?")
print("-one way is to put a `#` character at the beginning of every line not supposed to be printed")
| true |
48bcb4c1c7e29d4185555c559d565c949e9c4617 | queeniekwan/mis3640 | /session05/mypolygon.py | 1,526 | 4.28125 | 4 | import turtle
import math
# print(andrew)
# draw a square
# for i in range(4):
# andrew.fd(100)
# andrew.lt(90)
def square(t, length):
for i in range(4):
t.fd(length)
t.lt(90)
def polyline(t, n, length, angle):
"""
Draws n line segments with given length and angle (in degrees) between them.
t is a turtle.
"""
for i in range(n):
t.fd(length)
t.lt(angle)
def polygon(t, length, n):
"""
Draws a n-sided polygon with given length
t is a turtle
"""
angle = 360 / n
polyline(t, n, length, angle)
# def circle(t, r):
# c = 2 * math.pi * r
# length = c / 60
# polygon(t,length,60)
# circle(andrew,100)
def arc(t, r, angle):
"""
Draws an arc with radius r and angle
t is a turtle
"""
arc_length = 2 * math.pi * r * angle / 360
n = int(arc_length/3) + 1
step_length = arc_length / n
step_angle = angle / n
polyline(t, n, step_length, step_angle)
def circle(t, r):
"""
Draws a circle with radius r
t is a turtle
"""
arc(t, r, 360)
def move(t, x, y):
"""
Moves Turtle (t) forward (x,y) units without leaving a trail
"""
t.pu()
t.setpos(x, y)
t.pd()
def main():
andrew = turtle.Turtle()
# square(andrew,200)
# polyline(andrew, n = 4, length = 50, angle = 60)
# polygon(andrew, length = 50, n = 6)
# arc(andrew, r = 100, angle = 360)
# circle(andrew, n = 100)
turtle.mainloop()
if __name__ == "__main__":
main()
| false |
57629ce5b3adbfeb89b532c2b2af3b4977815c26 | queeniekwan/mis3640 | /session13/set_demo.py | 540 | 4.3125 | 4 | def unique_letters(word):
unique_letters = []
for letter in word:
if letter not in unique_letters:
unique_letters.append(letter)
return unique_letters
print(unique_letters('bookkeeper'))
# set is a function and type that returns unique elements in an item
word = 'bookkeeper'
s = set(word)
print(s, type(s))
s.add('a')
print(s)
# intersection between two sets
s1 = {1, 2, 3}
s2 = {2, 3, 4}
print(s1 & s2) #intersection
print(s1 | s2) #union
print(s1.difference(s2)) #what's in s1 that s2 doesn't have
| true |
ce7990693175eab9465ba280d06b8ec38e7c22a0 | queeniekwan/mis3640 | /session05/ex_05.py | 1,732 | 4.125 | 4 | import turtle
import math
from turtle_shape import circle, arc, polygon, move
def circle_flower (t, r):
"""
Draws a circle flower, t is a turtle, r is the radius of the circle
"""
for _ in range(6):
arc(t,r,60)
t.lt(60)
arc(t,r,120)
t.lt(60)
def yinyang (t):
"""
Draws a yinyang symbol, t is a turtle
"""
# draws the outter circle
circle(t,100)
# draws the two arcr
for _ in range(2):
move(t,0,100)
arc(t,50,180)
# draws the two small circle
move(t,0,35)
circle(t,15)
move(t,0,135)
circle(t,15)
def circle_triangle (t, r):
"""
Draws a pattern of circles within triangles within circle,
t is a turtle, r is the radius of the outter circle
"""
# draws the big circle
circle(t,r)
# draws the four triangles
move(t,0,r)
t.lt(60)
for _ in range(4):
t.lt(90)
polygon(t,r,3)
# calculations for small circles
degree30 = math.radians(30)
degree60 = math.radians(60)
r_s = r / 2 / math.tan(degree60)
height = r * math.cos(degree30)
# draws the bottom small circle
y1 = 100 - height
move(t,0,y1)
t.rt(60)
circle(t,r_s)
# draws the top small circle
y2 = 100 + height
move(t,0,y2)
t.lt(180)
circle(t,r_s)
#draws the left small circle
x1 = -height
move(t, x1, r)
t.lt(90)
circle(t,r_s)
# draws the right small circle
x2 = height
move(t,x2,r)
t.lt(180)
circle(t,r_s)
def main():
t = turtle.Turtle()
t.speed(0)
circle_flower(t,100)
# yinyang(t)
# circle_triangle(t, 100)
turtle.Screen().mainloop()
if __name__ == "__main__":
main() | false |
4babb313798da7167ba3ffbf63c6ce25ee2528c5 | sayaliupasani1/Learning_Python | /basic_codes/list1.py | 899 | 4.15625 | 4 | fruits = ["Mango", "Apple", "Banana", "Chickoo", "Custard Apple", "Strawberry"]
vegetables = ["Carrots", "Spinach", "Onion", "Kale", "Potato", "Capsicum", "Lettuce"]
print (type(fruits))
print(fruits)
#fruits.extend(vegetables)
#print(fruits)
#fruits.extend(vegetables[1])
print (fruits)
fruits.extend(vegetables[1:3])
print (fruits)
fruits.append("Garlic")
print (fruits)
fruits.insert(1,"Baby Spinach")
print (fruits)
fruits.remove("Baby Spinach")
print(fruits)
fruits.clear()
print(fruits)
vegetables.append("Onion")
print(vegetables)
vegetables.remove("Onion")
print(vegetables)
vegetables.remove("Onion")
print(vegetables)
vegetables.pop()
print(vegetables.index("Kale"))
print(vegetables.count("kale"))
lucky_nums=[8,5,9,0,3,2,6]
print(lucky_nums)
lucky_nums.sort()
print(lucky_nums)
lucky_nums.reverse()
print(lucky_nums)
lucky_nums2= lucky_nums.copy()
print(lucky_nums)
print(lucky_nums2) | true |
acf185f967bab8d3111bc6960294ea116d48cb1a | elkin5/curso-python-azulschool | /src/examples/ejericiosE2cadenas.py | 656 | 4.21875 | 4 | '''1.- Dada la cadena “El veloz murciélago hindú comía feliz cardillo y kiwi”, imprimir su variante justificada a la derecha rellenando con ‘>’, a la izquierda rellenando con ‘<‘ y centrada en 60 caracteres con asteriscos utilizando métodos de cadenas.'''
string = "El veloz murciélago hindú comía feliz cardillo y kiwi";
print(string.ljust(100, '>'));
print(string.rjust(60, '<'));
print(string.center(60, '*'));
# 5. Utilizando métodos de cadenas, crear una variable con una lista de números pares del 2 al 10 como cadenas e imprimir sus valores separados por un guión medio.
pares = ['2','4','6','8','10']
print('-'.join(pares)) | false |
7693ec8848f94f4375fa79e2d216744c71d4f56f | michaelpeng/anagramsgalore | /anagramlist.py | 1,251 | 4.3125 | 4 | """
Given a list of strings, tell which items are anagrams in the list, which ones are not
["scare", "sharp", "acres", "cares", "ho", "bob", "shoes", "harps", "oh"]
return list of lists, each list grouping anagrams together
"""
"""
Function to check two strings are anagrams of each other
'scare'
'acres'
True
"""
def anagrammer(string1, string2):
this_dict = {}
for letter in string1:
if letter not in this_dict:
this_dict[letter] = 1
else:
this_dict[letter] += 1
for letter in string2:
if letter not in this_dict:
return False
else:
this_dict[letter] -= 1
for key, value in this_dict.iteritems():
if value != 0:
return False
return True
def anagramlist(this_list):
anagram_dict = {}
while len(this_list) != 0:
item = this_list[0]
if item not in anagram_dict:
anagram_dict[item] = [this_list.pop(this_list.index(item))]
for word in list(this_list):
if anagrammer(item, word):
anagram_dict[item].append(this_list.pop(this_list.index(word)))
else:
this_list.remove(item)
return_list = []
for key, value in anagram_dict.iteritems():
return_list.append(value)
print return_list
this_list = ["scare", "sharp", "acres", "cares", "ho", "bob", "shoes", "harps", "oh"]
anagramlist(this_list) | true |
097e582da15e74f03d068917779f50f5560b845e | JoaoGabrielDamasceno/Estudo_Python | /Iteradores e Geradores/iterator_iterable.py | 358 | 4.375 | 4 | """
Iterator -> Objeto que dá para ser iterável e retorna um dado.
-> Se consegue usar a função next()
Iterable -> Função que retorna um iterável
-> Retornará um objeto quando a função iter() for chamada
lista = [1,2,3]
- O pyhton pega essa lista e faz iter(lista) num laço de repetição
- A cada passo do laço faz next()
""" | false |
9d6eaa66b5e3e24818e50cadbbbba75e76a5ca73 | ramlingamahesh/python_programs | /conditionsandloops/Sumof_NaturalNumbers.py | 615 | 4.21875 | 4 | num = int(input("Enter a number: "))
if num < 0:
print("Enter a positive number")
else:
sum = 0
# use while loop to iterate un till zero
while (num > 0):
sum += num
num -= 1
print("The sum is", sum)
# 2 Python Program - Find Sum of Natural Numbers
print("Enter '0' for exit.");
num = int(input("Upto which number ? "));
if num == 0:
exit();
elif num < 1:
print("Kindly try to enter a positive number..exiting..");
else:
sum = 0;
while num > 0:
sum += num;
num -= 1;
print("Sum = ", sum); | true |
24a599fb4fa7dcf2a5fe305b6a0905429dc2d195 | ramlingamahesh/python_programs | /conditionsandloops/GCDorHCF.py | 779 | 4.125 | 4 | '''n1 = 48
n2 = 36
# find smaller
if (n1 > n2):
smaller = n2
else:
smaller = n1
# getting hcf
i = 1
while (i <= smaller):
if (n1 % i == 0 and n2 % i == 0):
hcf = i
i = i + 1
print("hcf = ", hcf)'''
# Method 2: Using Recursion
'''
def find_hcf(n1, n2):
if (n2 == 0):
return n1
else:
return find_hcf(n2, n1 % n2)
n1 = 48
n2 = 36
hcf = find_hcf(n1, n2)
print("highest common factor = ", hcf) '''
# Method 3: Using math.gcd()
'''
import math
n1 = 48
n2 = 36
hcf = math.gcd(n1,n2)
print("Highest Common Factor = ", hcf) '''
# method 4
# implementing Euclidean algo
def get_gcd(x, y):
while (y):
x, y = y, x % y
return x
n1 = 48
n2 = 36
hcf = get_gcd(n1, n2)
print("Highest Common Factor = ", hcf)
| false |
ec5b56efd27c6d6c232e3c21f80bdccba626b68b | ramlingamahesh/python_programs | /conditionsandloops/FindNumbers_Divisible by Number.py | 646 | 4.15625 | 4 | # Python Program - Find Numbers divisible by another number
print("Enter 'x' for exit.");
print("Enter any five numbers: ");
num1 = input();
if num1 == 'x':
exit();
else:
num2 = input();
num3 = input();
num4 = input();
num5 = input();
number1 = int(num1);
number2 = int(num2);
number3 = int(num3);
number4 = int(num4);
number5 = int(num5);
numbers_list = [number1, number2, number3, number4, number5,];
check_num = int(input("Enter a number to check divisibility test: "));
res = list(filter(lambda x: (x % check_num == 0), numbers_list));
print("Number divisible by",check_num,"are",res); | true |
5209c52949500091bda483d0b6b7fba199098637 | shohanurhossainsourav/python-learn | /program28.py | 341 | 4.375 | 4 | matrix = [
[1, 2, 3],
[4, 5, 6],
]
print(matrix[0][2])
# print matrix value using nested loop
matrix = [
[1, 2, 3],
[4, 5, 6],
]
for row in matrix:
for col in row:
print(col)
matrix1 = [
[1, 2, 3],
[4, 5, 6],
]
# 0 row 2nd coloumn/3rd index value changed to 10
matrix1[0][2] = 10
print(matrix1[0][2])
| true |
ff6a9327111545c69ad4f59c5b5f2878def92431 | ikki2530/holbertonschool-machine_learning | /math/0x02-calculus/10-matisse.py | 740 | 4.53125 | 5 | #!/usr/bin/env python3
"""Derivative of a polynomial"""
def poly_derivative(poly):
"""
-Description: calculates the derivative of a polynomial.
the index of the list represents the power of x that the
coefficient belongs to.
-poly: is a list of coefficients representing a polynomial
- Returns: new list of coefficients representing the derivative
of the polynomial
"""
if poly and type(poly) == list:
new_coef = []
lg = len(poly)
if lg == 1:
new_coef.append(0)
for i in range(lg):
if i != 0:
coef = poly[i]
grade = i
new_coef.append(coef * grade)
else:
return None
return new_coef
| true |
d82167ca61a739e2d8c6919137e144a987ee22a3 | ikki2530/holbertonschool-machine_learning | /math/0x00-linear_algebra/8-ridin_bareback.py | 1,123 | 4.3125 | 4 | #!/usr/bin/env python3
"""multiply 2 matrices"""
def matrix_shape(matrix):
"""
matrix: matrix to calcuted the shape
Return: A list with the matrix shape [n, m],
n is the number of rows and m number of columns
"""
lista = []
if type(matrix) == list:
dm = len(matrix)
lista.append(dm)
lista = lista + matrix_shape(matrix[0])
return lista
else:
return lista
def mat_mul(mat1, mat2):
"""
Description: performs matrix multiplication, 2D matrices
Returns: a new matrix with the results of the multiplication
if it is possible, None otherwise
"""
shape1 = matrix_shape(mat1)
shape2 = matrix_shape(mat2)
suma = 0
resultado = []
temp = []
if shape1[1] == shape2[0]:
for k in range(len(mat1)):
for i in range(len(mat2[0])):
for j in range(len(mat1[0])):
suma += mat1[k][j] * mat2[j][i]
temp.append(suma)
suma = 0
resultado.append(temp)
temp = []
return resultado
else:
return None
| true |
181117260d2bcdc404dcd55a6f51966afa880e83 | ikki2530/holbertonschool-machine_learning | /supervised_learning/0x07-cnn/0-conv_forward.py | 2,649 | 4.53125 | 5 | #!/usr/bin/env python3
"""
performs forward propagation over a convolutional layer of a neural network
"""
import numpy as np
def conv_forward(A_prev, W, b, activation, padding="same", stride=(1, 1)):
"""
- Performs forward propagation over a convolutional layer of a
neural network.
- A_prev is a numpy.ndarray of shape (m, h_prev, w_prev, c_prev) containing
the output of the previous layer, m is the number of examples,
h_prev is the height of the previous layer,
w_prev is the width of the previous layer and c_prev is the number
of channels in the previous layer.
- W is a numpy.ndarray of shape (kh, kw, c_prev, c_new) containing
the kernels for the convolution, kh is the filter height,
kw is the filter width, c_prev is the number of channels in
the previous layer and c_new is the number of channels in the output.
- b is a numpy.ndarray of shape (1, 1, 1, c_new) containing the biases
applied to the convolution.
- activation is an activation function applied to the convolution.
- padding is a string that is either same or valid, indicating the
type of padding used.
- stride is a tuple of (sh, sw) containing the strides for the convolution,
sh is the stride for the height, sw is the stride for the width.
Returns: the output of the convolutional layer.
"""
m, h_prev, w_prev, c_prev = A_prev.shape
kh, kw, c_prev, c_new = W.shape
sh, sw = stride
if padding == "same":
ph = int(((h_prev - 1)*sh + kh - h_prev) / 2)
pw = int(((w_prev - 1)*sw + kw - w_prev) / 2)
if padding == "valid":
ph = 0
pw = 0
# Add zero padding to the input image
A_padded = np.pad(A_prev, ((0, 0), (ph, ph), (pw, pw), (0, 0)))
zh = int(((h_prev + (2*ph) - kh) / sh) + 1)
zw = int(((w_prev + (2*pw) - kw) / sw) + 1)
Z = np.zeros((m, zh, zw, c_new))
for y in range(zh):
for x in range(zw):
for k in range(c_new):
vert_start = y * sh
vert_end = (y * sh) + kh
horiz_start = x * sw
horiz_end = (x * sw) + kw
a_slice_prev = A_padded[:, vert_start:vert_end,
horiz_start:horiz_end, :]
# Element-wise product between a_slice and W.
# Do not add the bias yet.
prev_s = a_slice_prev * W[:, :, :, k]
# Sum over all entries of the volume prev_s.
sum_z = np.sum(prev_s, axis=(1, 2, 3))
z1 = sum_z + b[:, :, :, k]
Z[:, y, x, k] = activation(z1)
return Z
| true |
d5435c2f2cca0098f13f5d2ca37100b58eed8515 | David-Papworth/qa-assessment-example-2 | /assessment-examples.py | 2,639 | 4.1875 | 4 | # <QUESTION 1>
# Given a word and a string of characters, return the word with all of the given characters
# replaced with underscores
# This should be case sensitive
# <EXAMPLES>
# one("hello world", "aeiou") → "h_ll_ w_rld"
# one("didgeridoo", "do") → "_i_geri___"
# one("punctation, or something?", " ,?") → "punctuation__or_something_"
def one(word, chars):
for char in chars:
word = word.replace(char, '_')
return word
# <QUESTION 2>
# Given an integer - representing total seconds - return a tuple of integers (of length 4) representing
# days, hours, minutes, and seconds
# <EXAMPLES>
# two(270) → (0, 0, 4, 30)
# two(3600) → (0, 1, 0, 0)
# two(86400) → (1, 0, 0, 0)
# <HINT>
# There are 86,400 seconds in a day, and 3600 seconds in an hour
def two(total_seconds):
days = total_seconds // 86400
total_seconds %= 86400
hours = total_seconds // 3600
total_seconds %= 3600
minutes = total_seconds // 60
total_seconds %= 60
return (days, hours, minutes, total_seconds)
print(two(86400))
# <QUESTION 3>
# Given a dictionary mapping keys to values, return a new dictionary mapping the values
# to their corresponding keys
# <EXAMPLES>
# three({'hello':'hola', 'thank you':'gracias'}) → {'hola':'hello', 'gracis':'thank you'}
# three({101:'Optimisation', 102:'Partial ODEs'}) → {'Optimisation':101, 'Partial ODEs':102}
# <HINT>
# Dictionaries have methods that can be used to get their keys, values, or items
def three(dictionary):
new_dict = {}
for key, value in dictionary.items():
new_dict[value] = key
return new_dict
# <QUESTION 4>
# Given an integer, return the largest of the numbers this integer is divisible by
# excluding itself
# This should also work for negative numbers
# <EXAMPLES>
# four(10) → 5
# four(24) → 12
# four(7) → 1
# four(-10) → 5
def four(number):
last_possible = 1
if number < 0:
number = number * -1
for x in range(2, number//2 + 1):
if number % x == 0:
last_possible = x
return last_possible
print(four(-10))
# <QUESTION 5>
# Given an string of characters, return the character with the lowest ASCII value
# <EXAMPLES>
# five('abcdef') → 'a'
# four('LoremIpsum') → 'I'
# four('hello world!') → ' '
def five(chars):
asc=1000000000
for char in chars:
asc1 = ord(char)
if asc1 < asc:
asc = asc1
return chr(asc)
print(five('LoremIpsum')) | true |
0875700b5375f46ffcb44da81fff916e10808e6d | siddarthjha/Python-Programs | /06_inheritance.py | 1,338 | 4.28125 | 4 | """
Concept of Inheritance.
"""
print('I am created to make understand the concept of inheritance ')
class Upes:
def __init__(self, i, n):
print('I am a constructor of Upes ')
self.i = i
self.n = n
print('Ok i am done bye....')
def fun(self):
print('I am a function of Upes class')
print('Function of Upes exited....')
class Cse:
def __init__(self, i, n, s):
print('I am a constructor of Cse')
self.i = i
self.n = n
self.s = s
print('Ok i am done bye.....')
def func(self):
print('I am a function of Cse class')
print('Function of Cse class exited....')
class Cit(Upes, Cse):
__c = 10
def __init__(self, i, n):
self.i = i
self.n = n
print('I am a constructor of CseOg class')
print('Ok i am done')
print('The Abstraction variable is this and its value is %d' % Cit.__c)
def func(self):
print('I am function of class CseOg(Overrided method of Cse Class)')
print('Function of CseOg class is exited....')
obj = Cit(40, 'Sid')
obj.fun()
# obj.funct()
obj.func()
print(issubclass(Cit, Cse))
print(isinstance(obj, Cit))
# print(Cit.__c) # The __c is hidden to the class
| true |
b9f0b7f7699c8834a9c3a7b287f7f68b09b100ee | GabrielByte/Programming_logic | /Python_Exersice/ex018.py | 289 | 4.34375 | 4 | '''
Make a program that calculates sine, cosine and tangent
'''
from math import sin, cos, tan, radians
angle = radians(float(input("Enter an angle: ")))
print(f"This is the result; Sine: {sin(angle):.2f}")
print(f"Cosine: {cos(angle):.2f}")
print(f"and Tangent: {tan(angle):.2f}")
| true |
45e8158ac5e78c5deea43e77bebb2773c3aee215 | GabrielByte/Programming_logic | /Python_Exersice/ex017.py | 230 | 4.1875 | 4 | '''
Make a program that calculates Hypotenouse
'''
from math import pow,sqrt
x = float(input("Enter a number: "))
y = float(input("Enter another one: "))
h = sqrt(pow(x,2) + (pow(y,2)))
print(f"This is the result {h:.2}")
| true |
38b524a20fa88a549e0926230a63571a113c6249 | tabssum/Python-Basic-Programming | /rename_files.py | 997 | 4.21875 | 4 | #!/usr/bin/python
import os
import argparse
def rename_files():
parser=argparse.ArgumentParser()
parser.add_argument('-fp','--folderpath',help="Specify path of folder to rename files")
args=parser.parse_args()
#Check for valid folderpath
if args.folderpath :
#Get files in particular folder
file_list=os.listdir(args.folderpath)
print(file_list)
os.chdir(args.folderpath)
if len(file_list) > 0:
for file_name in file_list:
#string fun translate removes second parameter ele from string
new_name=file_name.translate(None,"0123456789")
#Finally to rename files in folder os.rename
os.rename(file_name,new_name)
else:
print("Folder is empty")
else :
print("Specify Folder Name in cmd")
rename_files()
#Exception Conditione
#1.renaming file that does not exist
#2.renaming a file name to name that already exist in folder.
| true |
dbccaa5b83a7764eb172b0e1653f7f086dd7b95e | smakireddy/python-playground | /ArraysAndStrings/PrisonCellAfterNDays.py | 2,265 | 4.21875 | 4 | """"
There are 8 prison cells in a row, and each cell is either occupied or vacant.
Each day, whether the cell is occupied or vacant changes according to the following rules:
If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied.
Otherwise, it becomes vacant.
(Note that because the prison is a row, the first and the last cells in the row can't have two adjacent neighbors.)
We describe the current state of the prison in the following way: cells[i] == 1 if the i-th cell is occupied, else cells[i] == 0.
Given the initial state of the prison, return the state of the prison after N days (and N such changes described above.)
Example 1:
Output: [0,0,1,1,0,0,0,0]
Explanation:
The following table summarizes the state of the prison on each day:
Day 0: [0, 1, 0, 1, 1, 0, 0, 1]
Day 1: [0, 1, 1, 0, 0, 0, 0, 0]
Day 2: [0, 0, 0, 0, 1, 1, 1, 0]
Day 3: [0, 1, 1, 0, 0, 1, 0, 0]
Day 4: [0, 0, 0, 0, 0, 1, 0, 0]
Day 5: [0, 1, 1, 1, 0, 1, 0, 0]
Day 6: [0, 0, 1, 0, 1, 1, 0, 0]
Day 7: [0, 0, 1, 1, 0, 0, 0, 0]
Example 2:
Input: cells = [1,0,0,1,0,0,1,0], N = 1000000000
Output: [0,0,1,1,1,1,1,0]
Note:
cells.length == 8
cells[i] is in {0, 1}
1 <= N <= 10^9
"""
from typing import List
# [0,1,0,1,1,0,0,1], N = 7
# 1[0,1,1,0,0,0,0,0]
# 2[0,0,0,0,1,1,1,0]
# 3[0,1,1,0,0,1,0,0]
# 4[0,0,0,0,0,1,0,0]
# 5[0,1,1,1,0,1,0,0]
# 6[0,0,1,0,1,1,0,0]
# 7[0,0,1,1,0,0,0,0]
# output [0,0,1,1,0,0,0,0]
class PrisonCellAfterNDays:
@staticmethod
def prisonAfterNDays(cells: List[int], N: int) -> List[int]:
length = len(cells)
cells_copy = cells.copy()
for i in range(N):
# print("i ->{} ".format(i))
for i in range(1, length - 1):
if cells[i - 1] == cells[i + 1]:
cells_copy[i] = 1
else:
cells_copy[i] = 0
cells_copy[0] = 0
cells_copy[length - 1] = 0
cells = cells_copy.copy()
# print("cell_copy ->{} ".format(cells_copy))
return cells_copy
if __name__ == "__main__":
# obj = PrisonCellAfterNDays()
cells = [0, 1, 0, 1, 1, 0, 0, 1]
N = 7
res = PrisonCellAfterNDays.prisonAfterNDays(cells, N)
print(res)
| true |
7d543273ad847de56beaae7761f9280640cfe012 | smakireddy/python-playground | /ArraysAndStrings/hackerrank_binary.py | 1,396 | 4.15625 | 4 | """
Objective
Today, we're working with binary numbers. Check out the Tutorial tab for learning materials and an instructional video!
Task
Given a base- integer, , convert it to binary (base-). Then find and print the base- integer denoting the maximum number of consecutive 's in 's binary representation. When working with different bases, it is common to show the base as a subscript.
Example
The binary representation of is . In base , there are and consecutive ones in two groups. Print the maximum, .
Input Format
A single integer, .
Constraints
Output Format
Print a single base- integer that denotes the maximum number of consecutive 's in the binary representation of .
Sample Input 1
5
Sample Output 1
1
Sample Input 2
13
Sample Output 2
2
"""
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input())
result = ""
cnt, max = 0, 0
while n > 0:
remainder = 0 if n % 2 == 0 else 1
flag = True
n = math.floor(n / 2)
print("remainder ->", remainder)
result = str(remainder) + result
if remainder == 1 and flag:
cnt += 1
flag = True
else:
flag = False
if n != 0:
cnt = 0
if max < cnt:
max = cnt
print("Binary -> ", result)
print("Count of consecutive 1's -> ", max)
| true |
29bf475491bbb765a9e739822fe09e7e383a1fef | aototo/python_learn | /week2/week2 bisection.py | 878 | 4.15625 | 4 | print("Please think of a number between 0 and 100!")
high = 100
low = 0
nowCorrect = int(( high + low ) / 2)
print('Is your secret number '+ str(nowCorrect) + '?')
while True:
input_value = input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.")
if input_value =='l':
low = nowCorrect
nowCorrect = int((high + low)/2)
print('Is your secret number '+ str(nowCorrect) + ' ?')
elif input_value =='h':
high = nowCorrect
nowCorrect = int((high+low)/2)
print('Is your secret number '+ str(nowCorrect) + ' ?')
elif input_value =='c':
print('Game over. Your secret number was: '+str(nowCorrect))
break
else:
print('Sorry, I did not understand your input.')
print('Is your secret number '+ str(nowCorrect) + ' ?')
| true |
7bbe2bf4078108379bff6f1b4edcf1d61dad66fd | Jeremiah-David/codingchallenges | /python-cc.py | 1,363 | 4.15625 | 4 | # Write a function called repeatStr which repeats the given string
# string exactly n times.
# My Solution:
def repeat_str(repeat, string):
result = ""
for line in range(repeat):
result = result + string
return (result)
# Sample tests:
# import codewars_test as test
# from solution import repeat_str
# @test.describe('Fixed tests')
# def basic_tests():
# @test.it('Basic Test Cases')
# def basic_test_cases():
# test.assert_equals(repeat_str(4, 'a'), 'aaaa')
# test.assert_equals(repeat_str(3, 'hello '), 'hello hello hello ')
# test.assert_equals(repeat_str(2, 'abc'), 'abcabc')
# Evens times last
# Given a sequence of integers, return the sum of all the integers that have an even index, multiplied by the integer at the last index.
# If the sequence is empty, you should return 0.
def even_last(numbers):
print("input is", numbers)
count = 0
answer = []
if numbers == []:
return 0
for number in numbers:
if count%2 == 0:
answer.append(number)
print("Array before sums together", answer)
count = count + 1
findsum = sum(answer)
print("The sum of array", findsum)
x = findsum * numbers[-1]
print('should be final', x)
return x
| true |
55e74e7fa646c954cefac68cd885b63a639191a3 | attaullahshafiq10/My-Python-Programs | /Conditions and loops/4-To Check Prime Number.py | 646 | 4.1875 | 4 | # A prime number is a natural number greater than 1 and having no positive divisor other than 1 and itself.
# For example: 3, 7, 11 etc are prime numbers
# Other natural numbers that are not prime numbers are called composite numbers.
# For example: 4, 6, 9 etc. are composite numbers
# Code
num = int(input("Enter a number: "))
if num > 1:
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,"is a prime number")
else:
print(num,"is not a prime number") | true |
bb69af4b9a1f55be425c9dbd16d19768cef3345d | winkitee/coding-interview-problems | /11-20/15_find_pythagorean_triplets.py | 911 | 4.28125 | 4 | """
Hi, here's your problem today. This problem was recently asked by Uber:
Given a list of numbers, find if there exists a pythagorean triplet in that list.
A pythagorean triplet is 3 variables a, b, c where a2 + b2 = c2
Example:
Input: [3, 5, 12, 5, 13]
Output: True
Here, 5^2 + 12^2 = 13^2.
"""
def findPythagoreanTriplets(nums):
# -> You always have to find exactly position in the range.
for i in range(1, len(nums) - 1):
front = nums[i - 1]
back = nums[i]
front_pow = pow(front, 2)
back_pow = pow(back, 2)
result_index = i + 1
while result_index < len(nums):
result = nums[result_index]
if pow(result, 2) == (front_pow + back_pow):
return True
result_index += 1
return False
print(findPythagoreanTriplets([3, 12, 5, 13]))
print(findPythagoreanTriplets([3, 5, 6, 11, 12, 5, 13]))
| true |
5c1c1b11dc666990e8344bf2cd5cc8e2a663d46f | winkitee/coding-interview-problems | /71-80/80_make_the_largest_number.py | 586 | 4.15625 | 4 | """
Hi, here's your problem today. This problem was recently asked by Uber:
Given a number of integers, combine them so it would create the largest number.
Example:
Input: [17, 7, 2, 45, 72]
Output: 77245217
def largestNum(nums):
# Fill this in.
print(largestNum([17, 7, 2, 45, 72]))
# 77245217
"""
class largestNumKey(str):
def __lt__(x, y):
return x + y > y + x
def largestNum(nums):
largest_num = "".join(sorted(map(str, nums), key=largestNumKey))
return '0' if largest_num[0] == '0' else largest_num
print(largestNum([17, 7, 2, 45, 72]))
# 77245217
| true |
dd07fe905d62c6de15dd052c2b54ff82de8ced23 | winkitee/coding-interview-problems | /31-40/34_contiguous_subarray_with_maximum_sum.py | 876 | 4.21875 | 4 | """
Hi, here's your problem today. This problem was recently asked by Twitter:
You are given an array of integers. Find the maximum sum of all possible
contiguous subarrays of the array.
Example:
[34, -50, 42, 14, -5, 86]
Given this input array, the output should be 137. The contiguous subarray with
the largest sum is [42, 14, -5, 86].
Your solution should run in linear time.
"""
#def max_subarray_sum(arr):
# pass
def max_subarray_sum(arr):
max_sum = float('-inf')
current_sum = max_sum
for num in arr:
if num > current_sum:
current_sum = max(num, current_sum + num)
else:
current_sum += num
max_sum = max(current_sum, max_sum)
return max_sum
print(max_subarray_sum([34, -50, 42, 14, -5, 86]))
# 137
print(max_subarray_sum([1, 1, 1, 2, 3]))
# 8
print(max_subarray_sum([-1, 1, -1, 2, -3]))
# 2
| true |
3a65bf1e00e3897174298a3dc7162b4c75c90742 | GabuTheGreat/GabuTheGreat.github.io | /challange/recursion_1.py | 467 | 4.1875 | 4 | n= int(input("Enter number the first number: "))
def isPrime(num):
"""Returns True if num is prime."""
if (num == 1) or (num % 2 == 0) or (num % 3 == 0) :
return False
if (num == 2) or (num == 3) :
return True
check_var= 5
set_var = 2
while check_var * check_var <= num:
if num % check_var == 0:
return False
check_var += set_var
set_var = 6 - set_var
return True
print(isPrime(n)) | true |
7ddb79a6c8b6d3cd0778e7e12eeb27af72598c35 | Poyx15/Tutorials | /Codecademy Practice/VisualizeData/DataFrame/ColumnOperation.py | 287 | 4.1875 | 4 | # import codecademylib
# from string import lower
import pandas as pd
df = pd.DataFrame([
['JOHN SMITH', 'john.smith@gmail.com'],
['Jane Doe', 'jdoe@yahoo.com'],
['joe schmo', 'joeschmo@hotmail.com']
],
columns=['Name', 'Email']
)
# Add columns here
df['Lowercase Name'] = df['Name'].str.lower()
print(df) | false |
0f036e9d59a6b7e4d12401f3e453dd2f8cb6fcdb | toufiq007/Python-Tutorial-For-Beginners | /chapter nine/list_comprehension.py | 1,044 | 4.25 | 4 |
# list comprehension
# print a list to square number of 1-10
# traditional way
num = list(range(1,11))
num_list = [i for i in range(1,11)]
print(num)
# def square_number(x):
# square_list = []
# for i in x:
# square_list.append(i**2)
# return square_list
# print(square_number(num))
square_list = []
for i in range(1,11):
square_list.append(i**2)
# print(square_list)
# list comprehension way
square_list = [i**2 for i in range(1,11)]
print(square_list)
# square_list2 = [i**2 for i in range(1,11)]
# print(square_list2)
negative_number = [-i for i in range(1,11)]
# print(negative_number)
negative_number = [-i for i in range(1,11)]
print(negative_number)
negative_number = []
for i in range(1,11):
negative_number.append(-i)
# print(negative_number)
names = ['limon','Mostafiz','toufiq']
new_list = []
# new_list_two = [i for i in names]
# print(new_list_two)
for i in names:
new_list.append(i[0])
# print(new_list)
# another_list = [i[0] for i in names ]
# print(another_list)
| false |
fbb50bc38f14354555cef3e2bf8cd66e2a3f9270 | toufiq007/Python-Tutorial-For-Beginners | /chapter three/while_loop.py | 412 | 4.21875 | 4 |
#loop
#while loop
# steps
# first declare a variable
# second write the while loop block
# in while loop block you must declare a condition
# find the odd and even number by using while number between 0-100
i = 0;
while i<=100:
print(f'odd number {i}')
i+=2
# find the even and even number by using while number between 0-100
i = 1;
while i<=100:
print(f'even number {i}')
i+=2
| true |
74bee5049a2462c78824fdee03bc35c9bcd6759e | toufiq007/Python-Tutorial-For-Beginners | /chapter twelve/lambda_expresion_intro.py | 512 | 4.25 | 4 |
# lambda expression --> anonymous function
# it means when a function has no name then we called it anonymous function
# syntex
# 1: first write lambda keyword
# 2: second give the parameters
# 3: then give : and give the operator tha'ts it
def add(x,y):
return x+y
print(add(10,5))
add = lambda a,b : a+b
print(add(10,12))
# add1 = lambda x,y : x+y
# print(add1(10,10))
# print(add)
# print(add1)
# multiply = lambda a,b : a*b
# print(multiply(5,2))
# print(multiply)
| true |
4024a43132422ded8732257256bfb91b98cf3582 | toufiq007/Python-Tutorial-For-Beginners | /chapter thirteen/iterator_iterable.py | 515 | 4.21875 | 4 |
# iterator vs iterables
numbers = [1,2,3,4,5] # , tuple and string alls are iterables
# new_number = iter(numbers)
# print(next(new_number))
# print(next(new_number))
# print(next(new_number))
# print(next(new_number))
# print(next(new_number))
square_numbers = map(lambda x:x**2,numbers)
# map , filter this all build functions are iterators
# print(next(square_numbers))
# print(next(square_numbers))
# print(next(square_numbers))
# print(next(square_numbers))
# print(next(square_numbers))
| true |
e7557d739edf11756cbec9759a5e7afaefa7955e | toufiq007/Python-Tutorial-For-Beginners | /chapter two/exercise3.py | 975 | 4.125 | 4 |
# user_name,user_char = input('enter your name and a single characte ==>').split(',')
name,character = input('please enter a name and character ').split(',')
#another times
# print(f'the lenght of your name is = {len(name)}')
# print(f'character is = {(name.lower()).count((character.lower()))}')
# (name.lower()).count((character.lower()))
# print(user_name)
# print(f'the lenth of the username is = {len(user_name)}')
# char = user_name.count(user_char)
# print(f'the character in this username is = {char}')
# print(f'character count is = {user_name.count(user_char)}')
# make case insensitive method
# print(f'character count is = {user_name.upper().count(user_char.upper())}')
#remove space problem
# name => name.strip() => name.strip().lower()
# character => character.strip() => character.strip().lower()
print(f'the length of you name is {name.strip()}')
print(f'character is = {name.strip().lower().count(character.strip().lower())}')
| true |
bd809f3954aded9bef550a88b32eb1a958b7b1b5 | toufiq007/Python-Tutorial-For-Beginners | /chapter thirteen/zip_part2.py | 978 | 4.1875 | 4 |
l1= [1,2,3,4,5,6]
l2 = [10,20,30,40,50,60]
# find the max number of those list coupe item and store them into a new list
def find_max(l1,l2):
new_array = []
for pair in zip(l1,l2):
new_array.append(max(pair))
return new_array
print(find_max(l1,l2))
# find the smallest numbers and stored them into a new list
# another_list = []
# for pair in zip(l1,l2):
# another_list.append(min(pair))
# print(another_list)
# l = zip(l1,l2)
# # print(list(l))
# print(dict(l))
# you have a list like
# [(1,2),(3,4),(5,6)]
couple = [(1,2),(3,4),(5,6)]
# you should convert this tuple into different list
l1,l2 = zip(*couple)
print(l1)
print(l2)
# l1,l2 = zip(*couple)
# print(l1)
# print(l2)
# zip_item = tuple(zip(l1,l2))
# print(zip_item)
# unpack_file,file = zip(*zip_item)
# print(unpack_file)
# print(file)
# new_list = []
# for pair in zip(l1,l2):
# new_list.append(max(pair))
# print(new_list)
| true |
41097f82056b1013fefd43169ac216060394710e | toufiq007/Python-Tutorial-For-Beginners | /chapter seven/add_delete_data.py | 1,547 | 4.28125 | 4 |
# add and delete data form dictionaries
user_info = {
'name' : 'Mostafiz',
'age' : 20,
'favourite_movie' : ['coco','terminator','matrix'],
'favourite_songs' : ['forgive me','ei obelay'],
'nickname' : ('lebu','manik','baba')
}
user_info['others'] = ['textile engnieering student at ptec']
# print(user_info)
# popped_item = user_info.popitem()
# print(popped_item)
# print(type(popped_item))
popped_item = user_info.pop('age')
print(popped_item)
print(type(popped_item))
# user_info['lang'] = ['javascript','python','html','css']
# print(user_info)
# pop_items = user_info.pop('age')
# print(pop_items)
# print(type(pop_items))
# print(user_info)
# popped_item = user_info.pop('name')
# print(popped_item)
# print(type(popped_item))
popped_item = user_info.popitem()
# print(popped_item)
# print(type(popped_item))
# how to add data in dictionaries
user_info['fav_sports'] = ['football','cricket','badminton']
# print(user_info)
# for i in user_info.items():
# print(i)
# how to remove data by using pop method
# pop_items = user_info.pop('favourite_movie')
# print(user_info)
# print(pop_items)
# print(type(pop_items))
# print(user_info)
# user_info.pop('age')
# print(user_info)
# remove data by using pop items method
# popitem method randomly removes a data form the dictionaries with keyvalues
# popitems returns the removes value in a tuples
# print(user_info)
popped_item = user_info.popitem()
# print(user_info)
# print(popped_item)
# print(type(popped_item))
| false |
60b9af30be744aec3de24fd4f422c688570644f3 | toufiq007/Python-Tutorial-For-Beginners | /chapter eleven/args_as_arguement.py | 452 | 4.28125 | 4 |
# Args as arguements
def multiply_nums(*args):
print(args)
print(type(args)) # [1,2,3,4,5]
mutiply = 1
for i in args:
mutiply *= i
return mutiply
# when you pass a list or tuple by arguemnts in your function then you must give * argument after give your list or tuple name
number = [1,2,3,4,5]
print(multiply_nums(*number)) # when you pass the * arguements then the items of the list will unpack.
| true |
21647313d550a72c49db44ddb740922b2199c2e1 | toufiq007/Python-Tutorial-For-Beginners | /chapter eight/set_intro.py | 984 | 4.375 | 4 | # set data type
# unordered collection of unique items
# i a set data type you can't store one data in multipying times it should be use in onetime
# set removes which data are in mulple times
# the main use of set is to make a unique collection of data it means every data should be onetimes in a set
# s = {1,2,3,42,42,22,23,2,3}
# print(s)
# s2 = [1,2,3,5,4,65,4,2,3,8,9,10,21,20,10,1,3,8,9]
# s2 = set(s2)
# print(s2)
# you can change a list by using set and change a set to list by using list method
# set_list = list(set(s2))
# print(set_list)
# set methods
s = {1,2,3,4,5}
# s.add(4)
# s.remove(6)
# s.discard(3)
# s2 = s.copy()
# s.clear()
# print(s)
# print(s2)
# in a set you can'nt store list, tuple and dictionary
# you only store number like integer,floating number and also you store string
s = {1,2.2,1.1,'string','hello'}
# there is no matter which is printing before and after because set is a unordered collection of data
print(s)
| true |
0bb687e8e8af5de27e6a4d7fb3c64d32e902fe42 | toufiq007/Python-Tutorial-For-Beginners | /chapter seven/exercise1.py | 1,024 | 4.1875 | 4 |
# def cube_func(x):
# cube_dic = dict()
# for i in x:
# num = i**3
# number_dic = {
# i : num
# }
# cube_dic.update(number_dic)
# return cube_dic
# number = list(range(1,10))
# print(cube_func(number))
# make a function that function take a single number and convet it to cube number and returns it into a dictionary
# like {1:1, 2:8, 3:27}
# def cube_func(x):
# cube_dict = dict()
# for i in x:
# cube_number = i**3
# another_cube_dict = { i : cube_number }
# cube_dict.update(another_cube_dict)
# return cube_dict
# number = list(range(1,10))
# print(cube_func(number))
def cube_dict(x):
cube_list = {}
for i in x:
cube_list[i] = i**3
return cube_list
number = list(range(1,10))
print(cube_dict(number))
# another way
# def cube_finder(x):
# cubes = {}
# for i in range(1,x+1):
# cubes[i] = i**3
# return cubes
# print(cube_finder(10))
| false |
e624a05600178ddc779ed8f0c552380ad76b6d7e | toufiq007/Python-Tutorial-For-Beginners | /chapter thirteen/enumerate_func.py | 584 | 4.34375 | 4 |
# we use emumerate function with for loop to tract the position of our item
# item in iterable
# how we can use without enumerate function
# names = ['limon','toufiq','mostafiz','salman','tamim']
# pos = 0
# for i in names:
# # print(f' {pos} --> {i} ')
# pos += 1
# show the output on below
# 0--> limon
# 1--> toufiq
# 2--> mostafiz
names = ['limon','toufiq','mostafiz']
for pos, name in enumerate(names):
print(f' {pos} --> {name} ')
# with enumerate function
# for pos, name in enumerate(names):
# print(f' {pos} --> {name} ')
| false |
4dc27bfcc459e5a66e85c8cd84027676b72d82cf | toufiq007/Python-Tutorial-For-Beginners | /chapter five/exercise3.py | 733 | 4.21875 | 4 |
names = ['abc','def','ghi']
# make the reverse in every list item
def reverse_list(x):
reverse_item = []
for i in range(len(names)):
pop_items = names.pop()
reverse_item.append(pop_items)
return reverse_item
print(reverse_list(names))
words = ['abc','def','ghi']
def reverse_words(x):
reverse_word_list = []
for i in x:
reverse_word_list.append(i[-1::-1])
return reverse_word_list
# print(reverse_words(words))
# makes the reverse in every each item of the list
# def reverse_elements(x):
# reverse = []
# for i in x:
# reverse.append(i[-1::-1])
# return reverse
# print(reverse_elements(words))
| false |
080bf5bb5c575a0dfc6b1d805c252097b2fe6389 | joannarivero215/i3--Lesson-2 | /Lesson3.py | 1,577 | 4.15625 | 4 | #to comment
#when naming file, do not add spaces
#age_of_dog = 3, meaningful variable name instead of using x
names = ["corey", "philip", "rose","daniel"] #assigning variables values to varibale name in a list(need braket)
print names #without quotation to print value
print names[1] #says second name
print '\n'
for x in range(0,len(names)): #len is length of vaules, begins with 0. x signifies the integer assigned to the name
print names[x] #indent is to inculde in for loop
print '\n'
for current_names in names: #does the same as previous example only treats names as an individual string
print current_names
print type(current_names)
print '\n'
name=raw_input("Type your name here: ") #user inputs varibale name, raw input is used to take in answer as a string (better to not have hackers)
print "Your name is", name
print '\n'
if 1>2: #add collon for loop, only prints if true
print "Hello"
elif 1<2: #acts like another if, another condition. Goodbye is said because its true
print "Goodbye"
else:
print "I have nothing to say"
hello=23!=34 #!= is not equal to
print hello
#age of dog problem
print'\n'
age_of_dog=input("How old is your dog? ")
output=22+(age_of_dog -2)*5
if age_of_dog<=0:
print "Hold on! Say whaaaaaaat"
elif age_of_dog==1: #== is equal too
print "about 14 human years"
elif age_of_dog==2:
print "about 22 human years"
elif age_of_dog>2: #not using else because it would fall under every other answer not previously stated (including less then 2)
print "human years: ", output #comma to print both
| true |
095615f1bac4635998d783a8c1e6aad0f17c1930 | hmedina24/Python2021 | /Practice/basic_python_practice/practice04.py | 431 | 4.3125 | 4 | #Create a program that asks the user for a number and then prints out a list of all the divisors that number.
#(If you don't know what a divisor is, it is a number that divides evely into another number.) For example, 13 is a divisor of 26 /13 has no remainder.)
def main():
num = int(input("Enter a number"))
divisor = [i for i in range(1,num+1) if num % i == 0]
print(divisor)
if __name__ == "__main__":
main() | true |
077dd6078669f3ff73df753fa86ace4b7c38ccae | hmedina24/Python2021 | /Sort_Algorithms /insertionSort.py | 582 | 4.15625 | 4 | def insertionSort(arr):
#traverse through 1 to len(arr)
for i in range(1, len(arr)):
key = arr[i]
#move elements of arr[0..i-1], that greater
#than key, to one position ahead
#of their current position
j = i-1
while(j >= 0 and key < arr[j]):
arr[j+1] = arr[j]
j-= 1
arr[j + 1] = key
for i in range(len(arr)):
print("%d" %arr[i])
def main():
#lets create an array
nums = [9,3,6,2,7,1,5,4]
insertionSort(nums)
if __name__ == "__main__":
main()
| true |
a87d462cc9760c43b2e75cfffcada78a0d1f3a92 | NikitaTipule/PPL_Lab | /Assignment6/shapes.py | 1,286 | 4.21875 | 4 | import turtle
s = turtle.getscreen()
t = turtle.Turtle()
class shape:
def __init__(self, sides = 0, length = 0):
self.sides = sides
self.length = length
class polygon(shape):
def info(self):
print("In geometry , a polygon can be defined as a flat or plane , two dimentional with straight sides")
class square(polygon):
def show(self):
for i in range(4):
t.fd(self.length)
t.rt(90)
class pentagon(polygon):
def show(self):
for i in range(5):
t.forward(self.length)
t.right(72)
class hexagon(polygon):
def show(self):
for i in range(6):
t.forward(self.length)
t.right(60)
class octagon(polygon):
def show(self):
for i in range(8):
t.forward(self.length)
t.right(45)
class triangle(polygon):
def show(self):
t.forward(self.length)
t.left(120)
t.forward(self.length)
t.left(120)
t.forward(self.length)
t.circle(100)
hex1 = hexagon(6, 100)
hex1.info()
hex1.show()
octa = octagon(12,100)
octa.info()
octa.show()
squ = square(4,100)
squ.info()
squ.show()
tri = triangle(3,100)
tri.info()
tri.show()
penta = pentagon(5,100)
penta.info()
penta.show()
| false |
4f39c91b7ed484576a00a3a0fca619e5d79c7a75 | mulyesmita15/Birthday-Remaining-Python | /birthday Remaining.py | 799 | 4.15625 | 4 | from datetime import datetime
import time
def get_user_birthday():
date_str = input("Enter your birth date in DD/MM/YYYY: ")
try:
birthday = datetime.strptime(date_str, "%d/%m/%Y")
except TypeError:
birthday = datetime.datetime(*(time.strptime(date_str, "%d/%m/%Y")[0:6]))
return birthday
def days_remaining(birth_date):
now = datetime.now()
current_year = datetime(now.year, birth_date.month, birth_date.day)
days = (current_year - now).days
if days < 0:
next_year = datetime(now.year + 1, birth_date.month, birth_date.day)
days = (next_year - now).days
return days
birthday = get_user_birthday()
next_birthday = days_remaining(birthday)
print("Your birthday is coming in: ", next_birthday, " days") | false |
280316ead847ed3f6aaf806b316926ab74102f92 | titotamaro/List_Spinner | /List_Spinner/List_Spinner.py | 1,198 | 4.1875 | 4 | list_awal = [[1, 2, 3],[4, 5, 6],[7, 8, 9]] #akan diubah menjadi[3,6,9][2,5,8][1,4,7]
#[3,6,9] ==> setiap kolom selisih 3 angka
#[2,5,8]
#[1,4,7]
def counterClockwise (list_x): # fungsi counterClockwise untuk list_x
hasil = [] # storage untuk penghitungan
for i in range(1,len(list_x)+1): # jumlah baris
for j in range(i,10,3): # isi kolom
hasil.append(j) # saat di run hasil masih terbalik [3,6,9] posisinya ada di bawah
hasil = f" {hasil[-3:]} '\n' {hasil[3:6]} '\n' {hasil[0:3]}" # saya coba balik dengan slicing
return hasil
#Kalau yang diatas masih belum memuaskan saya coba bikin pakai lambda (semoga menambah nilai):
# def counterClockwise(list_x): # fungsi counterClockwise untuk list_x
# a = map(lambda x: x*3 ,list_x[0]) # mengambil list pertama dan dikali 3 menggunakan map dan lambda
# b = map(lambda x: x-1 , a) # mengambil list a dan dikurangi 1
# c = map(lambda x: x-1, b) # mengambil list b dan dikurangi 1
# return f" {[a]} \n {[b]} \n {[c]}" #return value sesuai output yg diinginkan soal
print(counterClockwise(list_awal)) # pemanggilan fungsi sesuai soal
#Created by Tito Tamaro | false |
257f16e47cff4e8ac9c09a2c612c26514a144272 | eternalAbyss/Python_codes | /Data_Structures/zip.py | 585 | 4.34375 | 4 | # Returns an iterator that combines multiple iterables into one sequence of tuples. Each tuple contains the elements in
# that position from all the iterables.
items = ['bananas', 'mattresses', 'dog kennels', 'machine', 'cheeses']
weights = [15, 34, 42, 120, 5]
print(list(zip(items, weights)))
item_list = list(zip(items, weights))
# print(dict(zip(items, weights)))
# print(list(zip(*item_list)))
for i, item in enumerate(items):
print(i,item)
# Transpose trick
data = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11))
data_transpose = tuple(zip(*data))
print(data_transpose) | true |
5f5deaa62dde074fe526e3b079565fa5a25c51ab | konstantin2508/geekbrains_lessons | /Lesson2_Циклы_Рекурсия_Функции/les2_2_Рекурсия.py | 396 | 4.15625 | 4 | # Рекурсия
# Даны 2 числа: необходимо вывести все числа от A до B,
# в порядке возрастания (A<B) или убывания (A>B)
def func(a, b):
if a == b:
return f'{a}'
elif a > b:
return f'{a}, {func(a - 1, b)}'
elif a < b:
return f'{a}, {func(a + 1, b)}'
print(func(3, 25))
print(func(20, 2)) | false |
c24e68e1d77ba3e532987225382ae2f325424426 | muha-abdulaziz/langs-tests | /python-tests/sqrt.py | 419 | 4.3125 | 4 | """
This program finds the square root.
"""
x = int(input('Enter an integer: '))
def sqrt(x):
'''
This program finds the square root.
'''
x = x
ans = 0
while ans ** 2 < abs(x):
ans = ans + 1
if ans ** 2 != abs(x):
print(x, "is not a perfect square.")
else:
if x < 0:
ans = -ans
print('Square root of ' + str(x) + ' is ' + str(ans)) | true |
4e77c72219eec3043169f21e5ea39683d274d768 | vssousa/hacker-rank-solutions | /data_structures/linked_lists/merge_two_sorted_linked_lists.py | 982 | 4.34375 | 4 | """
Merge two linked lists
head could be None as well for empty list
Node is defined as
class Node(object):
def __init__(self, data=None, next_node=None):
self.data = data
self.next = next_node
return back the head of the linked list in the below method.
"""
def MergeLists(headA, headB):
merge_head = None
current_node = None
while headA or headB:
# evaluate data in the linked lists
if not headB or (headA and headB and headA.data <= headB.data):
current_head = Node(data=headA.data)
headA = headA.next
else:
current_head = Node(data=headB.data)
headB = headB.next
# update the head in the merge list
if not merge_head:
merge_head = current_head
# create links on the merge list
if current_node:
current_node.next = current_head
current_node = current_head
return merge_head | true |
866d69100bf11fa6508f0831af38d793fcbc1203 | CapstoneProject18/Twitter-sentiment-analysis | /s3.py | 711 | 4.34375 | 4 | #function to generate list of duplicate values in the list
def remove_Duplicate(list):
final_list = []
for letter in list: #empty final list to store duplicate values in list
if letter not in final_list: #if letter is not in the list it appends that letter to final list
final_list.append(letter)
return final_list #it returns finalist
list = ["a","v","q","d","a","w","v","m","q","v"]
print(remove_Duplicate(list))
| true |
6a95042055f70c57d1b7f162d425999f4ea0b9ef | rhaeguard/algorithms-and-interview-questions-python | /string-questions/reverse_string_recursion.py | 368 | 4.28125 | 4 | """
Reverse the string using recursion
"""
def reverse_recurse(string, st, end):
if st > end:
return ''.join(string)
else:
tmp_char = string[st]
string[st] = string[end]
string[end] = tmp_char
return reverse_recurse(string, st+1, end-1)
def reverse(string):
return reverse_recurse(list(string), 0, len(string)-1) | true |
29780713ccfde18c564112343872fc00415e994b | rhaeguard/algorithms-and-interview-questions-python | /problem_solving/triple_step.py | 449 | 4.4375 | 4 | """
Triple Step: A child is running up a staircase with n steps and can hop either 1 step, 2 steps, or 3
steps at a time. Implement a method to count how many possible ways the child can run up the
stairs.
"""
def triple_steps(step_size):
if step_size == 1 or step_size == 0:
return 1
elif step_size == 2:
return 2
else:
return triple_steps(step_size-1) + triple_steps(step_size-2) + triple_steps(step_size-3)
| true |
4a5ff8792e2f2106205376b2e4ac135045abf3d9 | akashgkrishnan/HackerRank_Solutions | /language_proficiency/symmetric_difference.py | 741 | 4.34375 | 4 | # Given sets of integers, and , print their symmetric difference in ascending order. The term symmetric difference indicates those values that exist in either or but do not exist in both.
# Input Format
# The first line of input contains an integer, .
# The second line contains space-separated integers.
# The third line contains an integer, .
# The fourth line contains space-separated integers.
# Output Format
# Output the symmetric difference integers in ascending order, one per line.
# Sample Input
# 4
# 2 4 5 9
# 4
# 2 4 11 12
# Sample Output
# 5
# 9
# 11
# 12
input()
a = set(map(int, input().split()))
input()
b = set(map(int, input().split()))
A = list(a.symmetric_difference(b))
for i in sorted(A):
print(i)
| true |
c4b02fa604cfbaeda727970e16450d9caceb3cd0 | namanm97/sl1 | /7a.py | 744 | 4.375 | 4 | # 7A
# Write a python program to define a student class that includes name,
# usn and marks of 3 subjects. Write functions calculate() - to calculate the
# sum of the marks print() to print the student details.
class student:
usn = " "
name = " "
marks1 = 0
marks2 = 0
marks3 = 0
def __init__(self,usn,name,marks1,marks2,marks3): #Constructor
self.usn = usn
self.name = name
self.marks1 = marks1
self.marks2 = marks2
self.marks3 = marks3
def calculate(self): # Member Function
print ("usn : ", self.usn, "\nname: ", self.name,"\nTotal is ", (self.marks1 + self.marks2 + self.marks3)/3)
print ("Result of Named object of student calling calculate ")
s1 = student("1MSIS16048", "Parineethi Chopra", 78, 76,62)
s1.calculate()
| true |
57970d0c4d360cb2efbee1272d167883a9af77e9 | pavanibalaram/python | /sampleprograms/maximumnumber.py | 204 | 4.1875 | 4 | def max():
if a<=b:
print(" {} is a maximum number" .format(b))
else:
print(" {} is a maximum number".format(a))
a=int(input("enter a number"))
b=int(input("enter a number"))
max() | false |
de429dafc1e0289e1db3f2959c3898bf108da63f | zbloss/PythonDS-MLBootcamp | /Python-Data-Science-and-Machine-Learning-Bootcamp/Machine Learning Sections/Principal-Component-Analysis/PCA.py | 1,536 | 4.125 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
# PCA is just a transformation of the data that seeks to explain what features really
# affect the data
from sklearn.datasets import load_breast_cancer
cancer = load_breast_cancer()
cancer.keys()
cancer['feature_names']
# We are going to see which components are the most important to this dataset
# i.e. we want to see which features most affect whether a tumor is cancer or benign
df = pd.DataFrame(cancer['data'], columns=cancer['feature_names'])
cancer['target_names']
# Usually PCA is done first to see which features are more important than others
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(df)
scaled_data = scaler.transform(df)
# Perform PCA
from sklearn.decomposition import PCA
pca = PCA(n_components=2)
pca.fit(scaled_data)
x_pca = pca.transform(scaled_data)
scaled_data.shape
x_pca.shape
# Now we have transformed all of our 30 variables down to just 2 variables
plt.figure(figsize=(8,6))
plt.scatter(x_pca[:,0], x_pca[:,1], c=cancer['target'], cmap='plasma')
plt.xlabel('First Principal Component')
plt.ylabel('Second Principal Component')
# We now need to understand what the components are
pca.components_
# we create a dataframe that shows the two outcomes 0,1 and the relationship each feature has on it
df_comp = pd.DataFrame(pca.components_, columns=cancer['feature_names'])
df_comp
plt.figure(figsize=(10,6))
sns.heatmap(df_comp, cmap='plasma')
| true |
46ec9a084ae3e98e217ccd160257b870111b8c4e | coshbar/Trabalhos | /Phyton/Max_Subarray.py | 627 | 4.1875 | 4 | #Have the function MaxSubarray(arr) take the array of numbers stored in arr and determine the largest sum that can be formed by any contiguous subarray in the array.
#For example, if arr is [-2, 5, -1, 7, -3] then your program should return 11 because the sum is formed by the subarray [5, -1, 7].
#Adding any element before or after this subarray would make the sum smaller.
def ArrayChallenge(arr): maxsum = 0
for i in range(len(arr)):
for j in range(i, len(arr)):
tempsum = sum(arr[i:j + 1])
if tempsum > maxsum:
maxsum = tempsum
arr = maxsum
return arr
print ArrayChallenge(raw_input())
| true |
507d763a8196d7f37aeacc592130234b38cf3fa4 | stevenjlance/videogame-python-oop-cli | /game.py | 2,753 | 4.40625 | 4 | import random
class Player:
# Class variables that are shared among ALL players
player_list = [] #Each time we create a player, we will push them into this list.
player_count = 0
def __init__(self, name):
## These instance variables should be unique to each user. Every user will HAVE a name, but each user will probably have a different name.
self.name = name
self.strength = random.randint(8, 12) # The stat values will all be random, but within a range of reasonableness
self.defense = random.randint(8, 12)
self.speed = random.randint(8, 12)
self.max_health = random.randint(18, 24) # The max health value will be random, but higher than the others.
self.health = self.max_health # Set the current health equal to the max health.
print("Player " + self.name + " has entered the game. \n Strength: " + str(self.strength) + "\n Defense: " + str(self.defense) + "\n Speed: " + str(self.speed) + "\n Maximum health: " + str(self.max_health) + ".\n")
## We're going to also manipulate the two class variables - While each user has their own specific defense or strength, the users all share the class variables defined above this method.
Player.player_list.append(self) ## The player will be added to the list of players.
Player.player_count += 1 ## The player count should go up by one.
print("There are currently " + str(Player.player_count) + " player(s) in the game.\n\n")
def attack(self, target):
## With a CLI, we want to print out all the information our users need to play this game.
## Let's show the attacker and defender's names here.
print("Player " + self.name + " attacks " + target.name + "!!!")
print(self.name + "'s strength is " + str(self.strength) + " and target " + target.name + "'s defense is " + str(target.defense) + ".")
## The battle will go differently depending on who is stronger.
if self.strength < target.defense:
print("Due to the target's strong defense, the attack only does half damage...")
damage = self.strength / 2
elif self.strength > target.defense:
print("Since the target is weaker than you are, the attack does double damage!")
damage = self.strength * 2
else:
print("These players are evenly matched. The attack goes through normally.")
damage = self.strength
target.health -= damage
## Let's print out the new totals so that we know the final results of the fight.
print(target.name + " now has " + str(target.health) + "/" + str(target.max_health) + " health remaining.\n\n")
## All other methods you code for the player class will fit best below this line.
## Make sure to indent instance methods properly so the computer knows they're part of the class.
| true |
9a52340002ffd0ac3b93cb796958deee21219aef | eguaaby/Exercises | /ex06.py | 428 | 4.34375 | 4 | # Check whether the input string
# is a palindrome or not
def ex6():
user_input = raw_input("Please enter a word: ")
palindrome = True
wordLength = len(user_input)
for i in range(0, wordLength/2 + 1):
if user_input[i] != user_input[wordLength-1-i]:
palindrome = False
if palindrome:
print "The word is a palindrome!!"
else:
print "The word is not a palindrome"
ex6() | true |
4b5b369fafd5657f10492685af047a6604254d05 | sandeepkundala/Python-for-Everybody---Exploring-Data-in-Python-3-Exercise-solutions | /ex5_1_2.py | 901 | 4.1875 | 4 | # Chapter 5
# Exercise 1 & 2: Write a program which repeatedly reads numbers until the user enters
# “done”. Once “done” is entered, print out the total, count, average of the
# numbers, maximum and minimum of the numbers. If the user enters anything other than a number, detect their mistake
# using try and except and print an error message and skip to the next number.
total = 0
count = 0
while True:
line = input('Enter a number:')
try:
if line =='done':
break
line = float(line)
total = total + line
count = count + 1
if count == 1:
min = line
max = line
else:
if min > line:
min = line
elif max < line:
max = line
except:
print('Invalid input')
avg = total/count
print(total, count, avg, min, max)
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.