blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
0b7d06e83d9a32417b0ef408ffcc340960bf268b | onestarshang/leetcode | /convert-a-number-to-hexadecimal.py | 1,277 | 4.625 | 5 | # coding: utf-8
'''
https://leetcode.com/problems/convert-a-number-to-hexadecimal/
Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used.
Note:
All letters in hexadecimal (a-f) must be in lowercase.
The hexadecimal string must not contain extra lead... | true |
351202ef5ebd3c6de3fc46c446fc1c9ff4d8efc6 | onestarshang/leetcode | /fraction-to-recurring-decimal.py | 2,300 | 4.125 | 4 | '''
https://leetcode.com/problems/fraction-to-recurring-decimal/
Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.
If the fractional part is repeating, enclose the repeating part in parentheses.
For example,
Given numerator = 1, denominator = 2, retur... | true |
12383bafbb9af46d9e220928ccb9746ba4725084 | onestarshang/leetcode | /find-all-anagrams-in-a-string.py | 1,569 | 4.125 | 4 | '''
https://leetcode.com/problems/find-all-anagrams-in-a-string/
Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.
Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.
The order of output does not matter.
... | true |
2924fb03143cf10abacfe8f59a64be61300e8f1a | onestarshang/leetcode | /number-of-1-bits.py | 660 | 4.15625 | 4 | # coding: utf-8
'''
https://leetcode.com/problems/number-of-1-bits/
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should ret... | true |
366baaa2535d13166583420c45c6a80229d810ef | onestarshang/leetcode | /zigzag-conversion.py | 1,235 | 4.25 | 4 | '''
https://leetcode.com/problems/zigzag-conversion/
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the... | true |
83c3d2036ad237a76c79a6a69ef638acd4a01b1e | onestarshang/leetcode | /balanced-binary-tree.py | 1,062 | 4.15625 | 4 | #coding: utf-8
'''
http://oj.leetcode.com/problems/balanced-binary-tree/
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
'''
# Definition for... | true |
e4e68fbe07641281facb7986ebd93b855e85c967 | onestarshang/leetcode | /insertion-sort-list.py | 1,308 | 4.25 | 4 | #coding: utf-8
'''
http://oj.leetcode.com/problems/insertion-sort-list/
Sort a linked list using insertion sort.
'''
class Solution:
# @param head, a ListNode
# @return a ListNode
def insertionSortList(self, head):
if not head or not head.next:
return head
p = he... | true |
9dce19d97804637a281134363814828aba1d17a5 | maxkajiwara/Sorting | /project/iterative_sorting.py | 1,237 | 4.28125 | 4 | # Complete the selection_sort() function below in class with your instructor
def selection_sort(arr):
# loop through n-1 elements
for i in range(0, len(arr) - 1):
cur_index = i
smallest_index = cur_index
# find next smallest element
for j in range(cur_index, len(arr)):
... | true |
cf9e93785bfc81f9d26c666366a78c979a0ec166 | raymondng1893/Python-CodingBatExercises | /CodingBatString-1/extra_end.py | 292 | 4.28125 | 4 | # Given a string, return a new string made of 3 copies of the last 2 chars of the original string. The string length will be at least 2.
def extra_end(str):
start = len(str) - 2
return 3*str[start:]
print(extra_end('Hello'))
print(extra_end('ab'))
print(extra_end('Hi'))
| true |
f8f2d3e0d9fb69a648c079cf5682afb0242eff54 | raymondng1893/Python-CodingBatExercises | /CodingBatString-2/count_hi.py | 266 | 4.25 | 4 | # Return the number of times that the string "hi" appears anywhere in the given string.
import re
def count_hi(str):
count = re.findall('hi', str)
return len(count)
print(count_hi('abc hi ho'))
print(count_hi('ABChi hi'))
print(count_hi('hihi'))
| true |
608aea8f1c2d4fd673d29ee20cadfeff30cdc245 | TarikEskiyurt/Python-Projects | /Determine Prime Number.py | 324 | 4.21875 | 4 | number=int(input("Please enter the number")) #I take a number from user
counter=0
for i in range(2,number):
if number%i==0:
counter=counter+1
if counter > 0:
print("It is not a prime number.") #I print output to screen
else:
print("Is the prime number.") #I print output to screen... | true |
4cf8466775023cd269a1959762ae2d87a9eda0e0 | imodin07/Python-Basics | /FileWritin.py | 797 | 4.125 | 4 | # Creating a new text file.
f = open("writee.txt", "w") # 'f' is file handle. 'w' is write mode.
f.write("It's a beautiful day out there. ") # With the help of 'f.write' we can write the file.
f.close() # Command to close file.
# Append Function in... | true |
a642e37cd7f786b709a2186939ad0615fb4d0f16 | shuihan0555/100-days-of-python | /day014/main.py | 1,068 | 4.1875 | 4 | # coding=utf-8
"""Day 014 - setdefault: When dict.get it's a bad idea.
This example covers the difference between dict.get and dict.setdefault functions.
Setdefault is a function that is more efficient that dict.get,
because it already set a default value if the key doesn't exists
and return the value... | true |
26a496a3ee887173f2ded8cfd166c9987f4ce210 | JonOlav95/algorithm_x | /backtracking/backtrack_helpers.py | 1,371 | 4.125 | 4 | from backtracking.backtrack_node import Node
def arr_to_node(arr):
node_arr = [[Node() for i in range(len(arr))] for j in range(len(arr[0]))]
for i in range(9):
for j in range(9):
node = Node()
node.x = j
node.y = i
if arr[i][j] != 0:
... | true |
f37c99c9a7412bc00b5be50ef7e76e174c859575 | Swinvoy/Cyber_IntroProg_Group1 | /Quizes/Exceptions and Input Validation/getIpAddress.py | 882 | 4.25 | 4 | # Write a function called 'GetIpAddress' that will keep asking the user to enter an IP Address until it is valid. The function will then return the IP address as a string.
# 255.255.255.255
def getIpAddress():
noError = False
while noError == False:
try:
ipAddress = input("What IP Address... | true |
e7a3547585379afed4381762a14e51ffc7400400 | tamsynsteed/palindrometask | /recursiontask.py | 616 | 4.3125 | 4 | #if the string is made of no letters or just one letter, then it is a palindrome.
def palindrome(s):
if len(s) < 1:
return True
#check if first and last letters are the same
else:
if s[0] == s[-1]:
# if the first and last letters are the same. Strip them from the string, and determine whether t... | true |
1daca47cdf2cd8d0feb87b65d4d17f19410a01e8 | acikgozmehmet/Python | /TicTacToe/TicTacToeStudent.py | 2,395 | 4.34375 | 4 | ## @author Mehmet ACIKGOZ
# This program simulates a simple game of Tic-Tac-Toe
def main():
MAX_TURNS = 9
turnsTaken = 0
isWinner = False
board = createBoard()
player = "O"
while (not isWinner and turnsTaken < MAX_TURNS) :
# Switch players
# (If player contained an O assign... | true |
e59e17fabd7f5c6677ce7b90f2735be699f1132b | Ryuuken-dev/Python-Zadania | /Practice Python/List Less Than Ten.py | 740 | 4.34375 | 4 | """
Take a list, say for example this one:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
and write a program that prints out all the elements of the list that are less than 5.
Extras:
1. Instead of printing the elements one by one, make a new list that has all the elements
less than 5 from this list in it and print o... | true |
822f149e5cc3c35b5fd057c38b45de473d2c950a | BhujayKumarBhatta/OOPLearning | /pOOP/pOOp/static_method.py | 1,516 | 4.21875 | 4 | '''
Created on 02-Oct-2018
@author: Bhujay K Bhatta
'''
'''
Static methods are a special case of methods.
Sometimes, you'll write code that belongs to
a class, but that doesn't use the object itself at all.
For example:
'''
class Pizza(object):
@staticmethod
def mix_ingradients(x, y):
... | true |
78c733bb240940129d830fefe817a8bd1d7ac956 | KrishnaSindhur/python-scripts | /cp/stack.py | 1,491 | 4.40625 | 4 | # dynamic stack operation
class Stack(object):
def __init__(self, limit=10):
self.stk = limit*[]
self.limit = limit
def is_empty(self):
return self.stk <= 0
def push(self, item):
if len(self.stk) >= self.limit:
print("stack is full")
print("stack is ... | true |
6f8efad9b8fb1792c14a4af94707d6a9f1cb3d3a | Noorul834/PIAIC | /assignment03.py | 669 | 4.125 | 4 | # 3. Divisibility Check of two numbers
# Write a Python program to check whether a number is completely divisible by another number. Accept two integer values form the user
# Program Console Sample Output 1:
# Enter numerator: 4
# Enter Denominator: 2
# Number 4 is Completely divisible by 2
# Program Console Samp... | true |
79e9aabb9a44898766e4c9fd5af2edefd0f86304 | Jordan-1234/Wave-1 | /Volume of a Cylinder.py | 265 | 4.28125 | 4 | import math
radius = float(input("Enter in the radius of the cylinder "))
height = float(input("Enter in the height of the cylinder "))
cylinder_Area = (2 * math.pi * pow(radius,2) * height)
print('The volume of the cylinder will be ' + str(round(cylinder_Area,1))) | true |
373a821293faaec8b08aa36dd08a9f3753b5e3d6 | lilymaechling/codingAssignment4 | /helper.py | 1,971 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Helper File Created on Mon Mar 23 22:25:37 2020
@author: deepc
"""
# In this "alive" code below, we will provide many subroutines (functions) in Python 3 which may be useful.
# We will often provide tips as well
import matplotlib.pyplot as plt
def read_pi(n):
#opens the file name "pi" ... | true |
d183aa5bbc14b2ec779224ae2ce86ca0be3547b4 | ghostvic/leetcode | /RotateArray.py | 1,151 | 4.25 | 4 | '''
Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].
'''
'''
The idea of this solution is: the array we can cut it into 3, A:[1,2,3,4] B:[5,6,7].
To get the result[B,A], first revers A, then reverse B, then reverse the e... | true |
bb98c4b3f474ea603a9576dd81713e0af8d3bf70 | Ezdkdr/Algorithms | /RainTrap.py | 967 | 4.25 | 4 | # a function that takes a list of positive integers as argument. The elements represent the lengths of the towers
# it returns the number of units of water trapped between the towers
#from typing import List, Any
def measure_trapped_water(arr):
i = 0
trapped_water_units = 0
j = len(arr) - 1
added = Tr... | true |
6b9fda45cb8bbc08d20afba5d0919d2dd2f9e15c | dcgibbons/learning | /advent_of_code/2019/day10.py | 1,988 | 4.25 | 4 | #!/usr/bin/env python3
#
# day10.py
# Advent of code 2019 - Day 10
# https://adventofcode.com/2019/day/10
#
# Chad Gibbons
# December 20, 2019
#
import math
import sys
def read_map(filename):
# reads a map from an input file - assuming one row per line of text
map = []
with open(filename) as fp:
... | true |
34d5fc23e16c4eb8acca98dd368726b427f09b0f | ahhampto/py4e | /ex_7.2.py | 1,108 | 4.125 | 4 | #Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:
#X-DSPAM-Confidence: 0.8475
#Count these lines and extract the floating point values from each of the lines and compute the average of those values and produce an output as shown below.
... | true |
3a833c388abc1fd1e27c14a603e3780b8b6fd657 | Asmin75/Beeflux_soln | /2.py | 235 | 4.125 | 4 | """Q2.
Consider a dictionary
d = {1:1, 2:2, 3:3}
a. whats the value of d[4] ??
b. How can you set 9 value in 2 key.
Write a program to print value with 2 key."""
d = {1:1, 2:2, 3:3}
#print(d[4]) #give KeyError: 4
d[2]=9
print(d[2])
| true |
836b1abfb6f7ba743da277f73799926daf67aad6 | Asmin75/Beeflux_soln | /1.py | 386 | 4.21875 | 4 | """Q1.
Create a function to sum Input Numbers (parameters) which returns sum of inputed numbers. Also write Unittest for the function.
my_sum(1,2) should return 3 e.g.
my_sum(1,2,3) should return 6
my_sum(1,3,5,7,8) = ?"""
def my_sum(*args):
total = 0
for num in args:
total += num
return tota... | true |
a8448f10e865e57443ffddea639346d62ed63b15 | brealxbrealx/beetroot | /Homework5/h5task2.py | 712 | 4.375 | 4 | # Author: Andrey Maiboroda
# brealxbrealx@gmail.com
# Homework5
# task2
# this program Generate 2 lists with the length of 10 with random integers from 1 to 10, \
# and make a third list containing the common integers between the 2 initial lists without any duplicates.
import random
# generate 2 lists in range 10 wit... | true |
2137e9ea6a4349220acb56ee37f258e245d479a8 | brealxbrealx/beetroot | /Homework8/h8task1.py | 481 | 4.28125 | 4 | # Author: Andrey Maiboroda
# brealxbrealx@gmail.com
# Homework8
# task1
# Write a function called oops that explicitly raises an IndexError \
# exception when called. Then write another function that calls oops inside a try/except statement to catch the error. What happens if\
# you change oops to raise KeyError ins... | true |
98f9f3ab231065992f45e0b2a41ecb2904bfd1ef | Diegofergamboa/day-3-1-exercise | /main.py | 468 | 4.4375 | 4 | # 🚨 Don't change the code below 👇
number = int(input("Which number do you want to check? "))
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
if number % 2 == 1:
print('The number is odd')
else:
print('The number is even')
#It´s important to know that the modulo gives 0 when the number is e... | true |
e3c90bb28c3d9df47a7eba8eb2ce678600bf4379 | OperationFman/LeetCode | /RevisionKit/Bubble-Sort.py | 677 | 4.21875 | 4 | # Given an array of integers, sort the array in ascending order using the Bubble
# Print the following three lines:
# Array is sorted in X swaps.
# First Element: Y
# Last Element: Z
# Where X, Y, Z are numbers
def countSwaps(a):
""" [2, 1, 3] """
# Clue: Follow the traditional method of bubble sort and run ... | true |
986bb3f771eaf065f792427508a7a33bc4d3a3ee | themanoftalent/Python-3-Training | /guessWrongNUmber.py | 449 | 4.25 | 4 | num = 0
secretnumber = 3
while True:
try:
num = int(input("Enter an integer 1-5: "))
except ValueError:
print("Please enter a valid integer 1-5")
continue
if num >= 1 and num <= 5:
break
else:
print('The integer must be in the range 1-5')
if num == secretnumber:
... | true |
b250352075bd8f0c8ce67731bd9acea04b8756d2 | DanielOjo/variables | /Task 6.2.py | 402 | 4.28125 | 4 | #Daniel Ogunlana
#9/9/2014
#Task 6
#1.Write a program that will ask the user for three integers and display the total.
#2.Write a program that will ask the user for two integers and display the result of multiplying them together.
#3.Ask the user for the length, width and depth of a rectangular swimming pool. Calc... | true |
1c9c3138bcb59f06b7db6158e04fa706e5df5a52 | VitaliiStorozh/Python_Core | /HW3/3.4.py | 310 | 4.15625 | 4 | area = float(input("Hall's area(S) is: "))
radius = float(input("Stage's radius(R) is: "))
aisle = float(input("Aisle width(K) is: "))
from math import sqrt
if aisle*2 <= (sqrt(area) - (2*radius) ) :
print("The stage can be located in this hall")
else :
print("You should find another stage or hall")
| true |
23fc1a4b24c6bffe7676ae4fde1d37bee3274404 | sakiii999/Python-and-Deep-Learning-Lab | /Python Lab Assignment 2/Source/LA2_4.py | 417 | 4.15625 | 4 | import numpy as np
#Creates a list of array wit size 15 and range in between 0 to 20
random = np.random.randint(low=0,high=20,size=15)
print("The random vector is",random)
#Total count of each integer are calculated using bincount method
totalcount = np.bincount(random)
#Most occurences of an integer i.e. highest count... | true |
8aca065e622cba0a79ce5d6b7332f57783ee15d1 | anujpanchal57/Udemy-Challenges | /Lect-43-challenge.py | 716 | 4.4375 | 4 | # Create a list of items (you may use either strings or numbers in the list),
# then create an iterator using the iter() function.
#
# Use a for loop to loop "n" times, where n is the number of items in your list.
# Each time round the loop, use next() on your list to print the next item.
#
# hint: use the len() ... | true |
62f5189ad9440541eb7aeeb16b4ddcfa3ae944b2 | Psp29/basic-python | /chapter 4/03_list_methods.py | 572 | 4.25 | 4 | # Always use the python docs to find all the info!!
list1 = [1, 5, 3, 7, 86, 420, 69]
print(list1)
# list1.sort() # sorts the list
# list1.reverse() # reverses the list
# list1.append(669) # adds the elements at the end of the list.
# list1.insert(3, 5) # Inserts the element at the specific position here, first ... | true |
28b8d144e32d73af5edd0c5247354c3b65e3d691 | Psp29/basic-python | /speedlearn.py | 521 | 4.125 | 4 | # (tuples are immutable means that we cannot replace the values in an tuples) and are denoted by brackets i.e. ()
# e.g. x = (3, 'string', 4.0)
# list (it is mutable means they store reference of the items not the copy, basically you can change, append, add, remove items in a list) are denoted by square brackets []
# ... | true |
789afdfbbf8c0dec19bb5fb2e2ccfc121b058886 | Psp29/basic-python | /chapter 6/01_conditionals.py | 467 | 4.15625 | 4 | a = input("Enter value of a: ")
b = input("Enter value of b: ")
# if-elif-else ladder
# if(a > b):
# print("The value of a is greater than b.")
# elif(a == b):
# print("value a is equal to b.")
# else:
# print("The value of b is greater than a.")
# Multiple if statements
if(a > b):
print("The value o... | true |
1c744073c9e13b0b8b00aeda923185ea169b549a | vScourge/Advent_of_Code | /2021/09/2021_day_09_1.py | 2,804 | 4.15625 | 4 | """
--- Day 9: Smoke Basin ---
These caves seem to be lava tubes. Parts are even still volcanically active; small hydrothermal vents release smoke into the caves that slowly settles like rain.
If you can model how the smoke flows through the caves, you might be able to avoid it and be that much safer.
The submarine g... | true |
b247e24618e9c2263362c18b5b47ef5faad97e54 | abhijitsahu/python | /project_01/parse.py | 1,236 | 4.34375 | 4 | #!/usr/bin/python
# Import sys for exit()
import sys
# Import os for checking the file if present
import os.path
# Check if input has provided
if len(sys.argv) <= 1:
print('Enter file name to parse the content: ./sample.py <filename>')
sys.exit()
# Get input file from commandline arg
input_file = sys.argv[1]
... | true |
de028eba3f662d85d09305eb24ee3989523344ac | Amirkhan73/Algorithms | /Python/fundamentals/easy/pythonIfElse.py | 648 | 4.46875 | 4 | # Task
# Given an integer, , perform the following conditional actions:
# If is odd, print Weird
# If is even and in the inclusive range of to , print Not Weird
# If is even and in the inclusive range of to , print Weird
# If is even and greater than , print Not Weird
# Input Format
# A single line containing a ... | true |
6546d19b2e52da46f3b38810b1d51cb8b6f69fd1 | ianpaulfo/cs-module-project-algorithms | /sliding_window_max/sliding_window_max.py | 1,773 | 4.3125 | 4 | '''
Input: a List of integers as well as an integer `k` representing the size of the sliding window
Returns: a List of integers
'''
# First-Pass Solution
# Find the maximum for each and every contiguous subarray of size k
# Approach: run a nested loop, the outer loop which will mark the starting point of the subarray ... | true |
a1410bca8d6afc93e4f85f096f37e10982a9a050 | mauricejulesm/python_personal_projects | /creating_files/CreateFiles.py | 895 | 4.125 | 4 | # declare an object name ( just any name)
objectForCreating = open("maurice.txt", "w") # this "w" should be ther to prepare the file for writing on to it
objectForCreating.write("Name: Jules Maurice\n")
objectForCreating.write("Age: 23\n")
objectForCreating.write("School: African Leadership University\n")
objec... | true |
661edcb48e2c8949fb7a4c5315ff3aba10c67369 | eltonlee/Practice | /practice/Notes.py | 1,695 | 4.1875 | 4 | # -------------Arrays----------
# Initalize a array of size k with n stuff inside it
a = ['n']*len(k)
# Loop backwards
for i in range(len(something)-1, -1, -1) # range (start, stop before, step)
# sort the array from lowest to highest
a.sort()
# sort the array from highest to lowest
a.sort(reverse=True)
# Set remo... | true |
e2ac7e249de6f3381063dc20282b793f4d8d7df1 | jarabt/Python-Academy | /Lekce05/stringToList.py | 379 | 4.15625 | 4 | """
Write a Python program which prompts and accepts a string of comma-separated
numbers from a user and generates a list of those individual numeric strings
converted into numbers.
"""
stringFromUser = input("Please enter comma separated numbers: ")
l = stringFromUser.split(",")
result = []
for word in l:
word ... | true |
db9d4c1b74746699433293e9f5f690031c9a202a | sharankonety/algorithms-and-data-structures | /Stack/implement_ll.py | 839 | 4.125 | 4 | # Implementing a stack using linked list
class Node:
def __init__(self,data=None):
self.data = data
self.next = None
class Linked_list:
def __init__(self):
self.head = None
def push(self,new_data):
new_node = Node(new_data)
if self.head is None:
self.head ... | true |
9bcb72d92a0a5e64765e78c2d112e9b62c96f961 | sharankonety/algorithms-and-data-structures | /Geeks_for_Geeks_Prob's/linked_lists/count_nodes.py | 960 | 4.15625 | 4 | # program to count the number of nodes in the linked list
class Node:
def __init__(self,data=None):
self.data = data
self.next = None
class Linked_list:
def __init__(self):
self.head = None
def count_list(self):
count = 0
temp = self.head
while temp:
... | true |
dc28c0282c0be6dbc735f7e79e65ce26862a86e6 | sharankonety/algorithms-and-data-structures | /Trees/Binary_Tree/search.py | 1,189 | 4.1875 | 4 | # program to search if a node exists in a tree or not.
class Node:
def __init__(self,data):
self.data = data
self.left = None
self.right = None
def insert(self,data):
if self.data:
if data<self.data:
if self.left is None:
self.left ... | true |
2a04fec5a4d637fb538a33da170c0bc7c249dda6 | sharankonety/algorithms-and-data-structures | /linked_lists/doubly_linked_lists/create.py | 813 | 4.1875 | 4 | # Inserting in a doubly linked list.
class Node:
def __init__(self,data=None):
self.pre = None
self.data = data
self.next = None
class Doubly_linked_list:
def __init__(self):
self.head = None
self.tail = None
def insert(self,new_data):
new_node = Node(new_data... | true |
b85a8c65a50055d40ed0bd2352b7335055691848 | sharankonety/algorithms-and-data-structures | /linked_lists/linear_linked_lists/deletion/deleting.py | 1,561 | 4.1875 | 4 | class Node:
def __init__(self,data=None):
self.data = data
self.next = None
class Linked_list:
def __init__(self):
self.head = None
def Print_list(self):
print_val = self.head
while print_val:
print(print_val.data,end="-->")
print_val = print_v... | true |
f252cf151ced6f28de04b9e72fedc98d103360ba | ayush-206/python | /assignment13.py | 1,976 | 4.375 | 4 | #Q.1- Name and handle the exception occured in the following program:
a=3
if a<4:
try:
a=a/(a-3)
except Exception:
print("an Exception occured")
#Q.2- Name and handle the exception occurred in the following program:
l=[1,2,3]
try:
print(l[3])
except Exception:
print("an exception occured")
#Q.3... | true |
f90231f573c38e66952d5a0f6c1b6f3d9209d819 | Jdamianbello2/cs190 | /CS190/venv/crashcourse.py | 987 | 4.34375 | 4 | name = "salad head"
print(name.upper())
print(name.lower())
simple_message = "I like you too"
print(simple_message)
print("The language 'Python' is named after Monty Python, not the snake.")
first_name = "ada"
last_name = "lovelace"
full_name = first_name + " " + last_name
print(full_name)
print("Hello, " + full_name.t... | true |
47c7676763843267376b3c17461f418bd285f394 | samipsairam/PythonDS_ALGO | /basics/Dictionary_Tut.py | 1,577 | 4.1875 | 4 | # Dictionary is another data structure which in other language is called as 'HashTable' or 'Map' or 'Object' in another language
# Dictionary or dict is a data type or data structure itself
# Have KV pairs
# Dictionary is unordered Key-Value pairs, Unlike List they are not ordered hence cannot be get by index
dictionar... | true |
aad213697313f4f67d999af41119d0e172cae57a | LiuHB2096/Backup | /notes1.py | 421 | 4.28125 | 4 | # This is a comment, use them very often
print (4 + 6) # addition
print (-4 - 5) # subtraction
print (6 * 3) # multiplication
print (8 / 3) # Division
print (3 ** 3) # exponents- 3 to the 3rd power
print (10 % 3) # modulo - gives you the remainder
print (15 % 5)
print (9 % 4)
print (16 % 3)
print (16 % 7)
... | true |
c299f3c87a9935300a0880b7ad7bfa599bd39f6b | divya-nk/hackerrank_solutions | /Python-practice/Strings/captilize.py | 425 | 4.21875 | 4 | import string
def solve(s):
return string.capwords(s, ' ')
# Split the argument into words using str.split(), capitalize each word using str.capitalize(), and join the capitalized words using str.join(). If the optional second argument sep is absent or None, runs of whitespace characters are replaced by a single s... | true |
59bd1f32dd0cb7ed6f999c0079670b852527787c | Nathhill92/PY4E_Exercise | /Code Challenges/ReducePractice.py | 840 | 4.1875 | 4 | #return max
import functools
lis = [ 1 , 3, 5, 6, 2, ]
print ("The maximum element of the list is : ",end="")
print (functools.reduce(lambda a,b : a if a > b else b,lis))
# ruber ducky walkthrough:
# reduce takes two arguments,
# the function logic and the list to to perform the function logic on
# The value of ... | true |
b872bc0979aab82371c80794eebd6dc61b1dab91 | Nathhill92/PY4E_Exercise | /Code Challenges/ColorInverter.py | 649 | 4.46875 | 4 | # Create a function that inverts the rgb values of a given tuple.
# Examples
# color_invert((255, 255, 255)) ➞ (0, 0, 0)
# # (255, 255, 255) is the color white.
# # The opposite is (0, 0, 0), which is black.
# color_invert((0, 0, 0)) ➞ (255, 255, 255)
# color_invert((165, 170, 221)) ➞ (90, 85, 34)
# Notes
# Must ret... | true |
33c48b23e18d00aa230254ee18f1e48a62b29138 | Nathhill92/PY4E_Exercise | /Code Challenges/OOPCalculator.py | 1,061 | 4.53125 | 5 | # Simple OOP Calculator
# Create methods for the Calculator class that can do the following:
# Add two numbers.
# Subtract two numbers.
# Multiply two numbers.
# Divide two numbers.
# Examples
# calculator = Calculator()
# calculator.add(10, 5) ➞ 15
# calculator.subtract(10, 5) ➞ 5
# calculator.multiply(10, 5) ➞ 50
#... | true |
b38c4fc99ad9bfafa16e07237e3dcb2f89c0496e | Nathhill92/PY4E_Exercise | /chap2.py | 1,177 | 4.625 | 5 | #Chapter 2 exercises
#https://www.py4e.com/html3/02-variables
#Write a program that uses input to prompt the user for their name and then welcomes them
# name = input("Hello! What is your name? ")
# print("Hello " +name)
# print()
#Write a program to prompt users for hours and hourly rate to compute gross wage
hours... | true |
71ac0a3e35fa69cdaf0574332f49a51213594dc7 | Hassan-Farid/DAA-Assignments | /Minimum Numbers/QuadraticMin.py | 670 | 4.21875 | 4 | def findQuadMin(arr):
'''
Sorts the values in the given array in O(n^2) time in ascending order
and returns the first index value i.e. minimum value
'''
for j in range(1, len(arr)):
key = arr[j]
i = j - 1
while i >= 0 and arr[i] > key:
arr[i+1] = arr[... | true |
2b7714e2eb4e8e55cbb62612eb1a8c37b42b0c69 | VikingOfValhalla/PY4E_Python_4_Everybody | /excercise_03_02/excercise_03_02_assignment.py | 499 | 4.21875 | 4 | score = input("Enter Score: ")
# gives the command to try the if statement for letter_grade
try:
letter_grade = float(score)
# if the try command above does not work, it will print the below
except:
print("Error with your score input")
# Possible inputs
if letter_grade >= float(0.9):
print('A')
elif lett... | true |
ce8b58f3c70574491db63b3fd64cd067e42a8849 | yumi2198-cmis/yumi2198-cmis-cs2 | /cs2quiz2.py | 2,114 | 4.21875 | 4 | import math
#PART 1: Terminology
#1) Give 3 examples of boolean expressions.
#q1 a) 2 == 3
#q2 b) a > b and b == c
#q3 c) x == c or a > x
#
#q4 2) What does 'return' do?
# In python programming, return has the job of taking an argument and giving out the result. It basically shows what argument a certain "def" does.
... | true |
9581a123e0f718e4b46fbabf4289ae5b94bdd4af | RajathT/dsa | /python/Linked_List/flatten_doubly_list.py | 1,734 | 4.25 | 4 | """
# Definition for a Node.
class Node(object):
def __init__(self, val, prev, next, child):
self.val = val
self.prev = prev
self.next = next
self.child = child
"""
class Solution(object):
def flatten(self, head):
"""
:type head: Node
:rtype: Node
... | true |
ab60756eb584ef0085c519439de82ba9ef1a365a | RajathT/dsa | /python/Trees/tree_right_side_view.py | 1,011 | 4.21875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
'''
Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
Ex... | true |
8e6cab1789c39d0ec5520e7dddb384f9f3e56682 | gautam199429/pythoncodes | /os.py | 2,784 | 4.3125 | 4 | import os
# Create empty dictionary
player_dict = {}
# Create an empty string
enter_player = ''
# Enter a loop to enter inforation from keyboard
while enter_player.upper() != 'X':
print 'Sports Team Administration App'
# If the file exists, then allow us to manage it, otherwise force creation.
if os.pat... | true |
742e8b0dbf3966fed15d40dc3eee899f3fedb59d | nnagwek/python_Examples | /pycharm/flowcontrolstatements/gradingSystem.py | 466 | 4.25 | 4 | maths = float(input('Enter marks in maths : '))
physics = float(input('Enter marks in physics : '))
chemistry = float(input('Enter marks in chemistry : '))
if maths < 35 or physics < 35 or chemistry < 35:
print('Student has failed!!!')
else:
print('Student has Passed!!!')
average = (maths + physics + chemis... | true |
9e86bd62c745472931f6a27de0e60e1f4646b9df | sridevisriramu/pythonSamples | /raw_input_If_Else.py | 225 | 4.25 | 4 | print 'Welcome to the Pig Latin Translator!'
# Start coding here!
original = raw_input("enter a word = ")
print "User entered word is = " + str(original)
if(len(original)>0):
print original
else:
print "empty string" | true |
58c0349c83d605f31d2cef274793b26355aa25ff | DaniMarek/pythonexercises13 | /lstodic.py | 1,010 | 4.25 | 4 | # Create a function that takes in two lists and creates a single dictionary. The first list contains keys and the second list contains the values. Assume the lists will be of equal length.
# Your first function will take in two lists containing some strings.
name = ["Anna", "Eli", "Pariece", "Brendan", "Amy", "Shan... | true |
48fe2fbb091316a82c366f567aef9c089e73a574 | TejasviniK/Python-Practice-Codes | /getCaptitals.py | 255 | 4.125 | 4 | def get_capitals(the_string):
capStr = ""
for s in the_string :
if ord(s) >= 67 and ord(s) <= 90:
capStr += s
return capStr
print(get_capitals("CS1301"))
print(get_capitals("Georgia Institute of Technology"))
| true |
5890fca781ca1ccec74571a9c5d962cad956b352 | changediyasunny/Challenges | /leetcode_2018/7_reverse_integer.py | 873 | 4.125 | 4 | """
7. Reverse Integer
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range:
[−2^31, ... | true |
fae854c0275661ef01a70a10a9befdd4e35a3756 | changediyasunny/Challenges | /leetcode_2018/655_print_2D_binary_tree.py | 2,209 | 4.125 | 4 | """
655. Print Binary Tree
Print a binary tree in an m*n 2D string array following these rules:
The row number m should be equal to the height of the given binary tree.
The column number n should always be an odd number.
Example 1:
Input:
1
/
2
Output:
[["", "1", ""],
["2", "", ""]]
Example 2:
Input:
... | true |
3cbbdba5fccc9957370774c31a727840c2bd90f3 | changediyasunny/Challenges | /leetcode_2018/208_implement_trie.py | 2,173 | 4.21875 | 4 | """
208. Implement Trie (prefix tree)
Implement a trie with insert, search, and startsWith methods.
Example:
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple"); // returns true
trie.search("app"); // returns false
trie.startsWith("app"); // returns true
trie.insert("app");
trie.search("app"); ... | true |
664c7738c1e235d552343733bd98b7239e3f4213 | changediyasunny/Challenges | /leetcode_2018/150_eval_reverse_polish_notation.py | 2,130 | 4.15625 | 4 | """
150. Evaluate Reverse Polish Notation
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
Note:
Division between two integers should truncate toward zero.
The given RPN expression is always valid. That me... | true |
9a18f7c85ecd1a54178e39c4058f63f6be85edfa | changediyasunny/Challenges | /leetcode_2018/207_course_schedule.py | 2,261 | 4.1875 | 4 | """
207. Course Schedule
There are a total of n courses you have to take, labeled from 0 to n-1.
Some courses may have prerequisites, for example to take course 0 you have to first
take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, is it possible
for ... | true |
c9fdcf043b9a4fdd46f51714328b1c829df41b82 | RuslanIhnatenko/Python-Enchantress | /lectures/tests/asserts_practice.py | 446 | 4.125 | 4 | def is_prime(number):
"""Return True if *number* is prime."""
if number <= 1:
return False
for element in range(2, number):
if number % element == 0:
return False
return True
assert is_prime(7) is True, "7 is prime number"
assert is_prime(10) is False, "10 is not a prime nu... | true |
6d3f6c4facea5db2d699029b8773651fd77a55eb | dabay/LeetCodePython | /MaximumSubarray.py | 1,067 | 4.28125 | 4 | # -*- coding: utf8 -*-
'''
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [−2,1,−3,4,−1,2,1,−5,4],
the contiguous subarray [4,−1,2,1] has the largest sum = 6.
More practice:
If you have figured out the O(n) solution, try coding ano... | true |
b50acc9bb4d87dc26c8798a05e025cbcd275b70e | dabay/LeetCodePython | /172FactorialTrailingZeroes.py | 573 | 4.15625 | 4 | # -*- coding: utf8 -*-
'''
https://oj.leetcode.com/problems/factorial-trailing-zeroes/
Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
'''
class Solution:
# @return an integer
def trailingZeroes(self, n):
result = 0
... | true |
6338838f56dc97b6dbfc227a5693fdc9e0eb4d50 | dabay/LeetCodePython | /FlattenBinaryTreeToLinkedList.py | 2,012 | 4.5 | 4 | # -*- coding: utf8 -*-
'''
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
'... | true |
6f564d7d1802a29f5151d709e96b40232d01ebb7 | dabay/LeetCodePython | /SetMatrixZeroes.py | 1,482 | 4.25 | 4 | # -*- coding: utf8 -*-
'''
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
哎,这道题有点巧妙呐~
'''
class Solution:
# @param matrix, a list of lists of integers
# RETURN NOTHING, MODIFY matrix IN PLACE.
def setZeroes(self, matrix):
row_count = len(matrix)
... | true |
a8b91d51f0cff6f909b3a88f94d3c35f04f455cd | dabay/LeetCodePython | /PartitionList.py | 1,753 | 4.15625 | 4 | # -*- coding: utf8 -*-
'''
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.
'... | true |
cf2cf2ff16a4c6f209b47c69fdc4ea88164dc0aa | jingriver/testPython | /python_language/filter_words/filter_words.py | 700 | 4.21875 | 4 | """
Filter Words
------------
Print out only words that start with "o", ignoring case::
lyrics = '''My Bonnie lies over the ocean.
My Bonnie lies over the sea.
My Bonnie lies over the ocean.
Oh bring back my Bonnie to me.
'''
Bonus points: print out... | true |
1f2aae3ca06df9c0835afed1a77bdda03f9207ec | jingriver/testPython | /numpy/mothers_day/mothers_day_solution.py | 859 | 4.125 | 4 | """
Mother's day
============
In the USA and Canada, Mother's Day is the second Sunday of May. Use
NumPy's datetime64 data type and datetime64 utilities to compute the date of
Mother's Day for the current year.
Note: NumPy datetime64 values can be created from a string with the format
YYYY-MM-DD HH:MM:SS.sss where ev... | true |
240916cbc51c8858649a8d39d9663aeb542482cd | richiede/my_algos | /01_my_sorting_algo.py | 1,316 | 4.4375 | 4 | # This is a program that will take multiple string inputs from a user to create a list
# The algo will then sort the list in alphabetical order.
# 3 lists are initialised
my_list = []
my_temp_list = []
sorted_list = []
# Input is taken from the user and added to the "my_list" list
print('Welcome! Please create a list... | true |
9b06eb2c5458ee0268a5ed2b8e86e02d15ca9ae7 | stoicamirela/PythonScriptingLanguagesProjects | /Project4/main.py | 1,148 | 4.40625 | 4 | #simple exercise with dictionary: we have a dictionary with phone numbers and names, and we show first the names and ask user
#what number phone he wants, based on that we show the value of the key name. Bonus things are changing k to value as shown in
#inverted_dict variable. I also sorted the dictionary in a for
#... | true |
2d4d0e8a2f72334ed27e9cb5855afac242f90897 | Arfa-uroz/practice_program | /tuple.py | 600 | 4.375 | 4 | """Given an integer,n, and n space-separated integers as input, create a tuple ,t , of those n integers.
Then compute and print the result of hash(t).
Note: hash() is one of the functions in the __builtins__ module, so it need not be imported."""
if __name__ == '__main__':
n = int(input()) #n number ... | true |
d3feee4d25dba244579179657ce2005908a7aa1e | Arfa-uroz/practice_program | /swap_case.py | 233 | 4.21875 | 4 | def swap_case(s):
new_string = s.swapcase() #swaps the case of all the letters
return(new_string)
if __name__ == '__main__':
s = input("Enter your string here ")
result = swap_case(s)
print(result) | true |
3f6d19203aedf5b9156817db55db27f471fb0950 | LambdaSchool-forks/DS-Unit-3-Sprint-2-SQL-and-Databases | /SC/northwind.py | 2,296 | 4.21875 | 4 | import sqlite3
# create connection
sl_conn = sqlite3.connect('/Users/Elizabeth/sql/northwind_small.sqlite3')
curs = sl_conn.cursor()
# table names
# [('Category',), ('Customer',), ('CustomerCustomerDemo',),
# ('CustomerDemographic',), ('Employee',), ('EmployeeTerritory',), ('Order',),
# ('OrderDetail',), ('Product',)... | true |
a23aedd69fd4ec2d6500ba5a8bb05b0efbc67a1b | Allen-1242/Python-Prorgrams | /Python Programs/Python Programs/SQL_python/sql2.py | 954 | 4.1875 | 4 | import sqlite3
con = sqlite3.connect('my_data.db')
cur = con.cursor()
while(True):
print("Welcome to the database")
print("1.Insert the row\t2.View the table\n3.Update the table\t 4.Drop the table\n5.Exit")
imp = int(input("Enter the operation needed"))
if imp == 1:
print("Welcome to insertion \n")
f = in... | true |
5758d2fbfde70ce6058f703bd003826a748dc63e | joco1026/Python-Challenge | /4/dynamic_url.py | 757 | 4.125 | 4 | #!/usr/bin/python
#http://www.iainbenson.com/programming/Python/Challenge/solution4.php
#This is an example of using a linked list to dynamically open HTML pages.
#It will parse an HTML page for a number and then dynamically open the next page.
import urllib, re
url="http://www.pythonchallenge.com/pc/def/linkedlist.... | true |
4f42a130f24a8159a696bd2ea33712e5e79b5750 | FranzSchubert92/cw | /python/best_travel.py | 1,976 | 4.21875 | 4 | #! /usr/bin/env python3
"""
John and Mary want to travel between a few towns A, B, C ... Mary has on a
sheet of paper a list of distances between these towns.
ls = [50, 55, 57, 58, 60].
John is tired of driving and he says to Mary that he doesn't want to drive more
than t = 174 miles and he will visit only 3 town... | true |
c57415dc01430b0d3b9824290a5c6828673cb2be | kiba0510/holbertonschool-higher_level_programming | /0x06-python-classes/1-square.py | 329 | 4.21875 | 4 | #!/usr/bin/python3
"""
Square Module - Use when you need to print a square
"""
class Square:
"""
Class defining the size of a square
"""
def __init__(self, size=0):
"""
Initialization of instanced attribute
Args:
size: The size of a square
"""
self.__siz... | true |
ace00dd2e10aefdd23c28b0222f91b6e109374ee | microsoft/python-course | /pycourse.py | 1,413 | 4.125 | 4 | # Functions for Introduction to Python Course
## Turtle Graphics
import jturtle as turtle
def square(x):
"""
Draw a square with side x
"""
for t in range(4):
turtle.forward(x)
turtle.right(90)
def house(size):
"""
Draw a house of specified size
"""
square(size)
turtle.forward(si... | true |
b350082c8536e3b80dd2ac9dd8badd9114f5630b | uncamy/Games | /pigLatin.py | 611 | 4.15625 | 4 | pyg = 'ay'# piece of code for use later
original = raw_input('Enter a word:') #user input word to be translated
if len(original) > 0 and original.isalpha():
print original
word = original.lower()
first =word[0]
#for words that start with a vowel
if first == "a" or first=="e" or first=="i" or firs... | true |
e869611625c651a76222ef709319cd7917eb7a30 | raxxar1024/code_snippet | /leetcode 051-100/95. Unique Binary Search Trees II.py | 1,412 | 4.1875 | 4 | """
Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1...n.
For example,
Given n = 3, your program should return all 5 unique BST's shown below.
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / ... | true |
72ef48d15fdf5d8d3df74a38dd1438f7148f8a33 | raxxar1024/code_snippet | /leetcode 051-100/53. Maximum Subarray.py | 893 | 4.21875 | 4 | """
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.
click to show more practice.
More practice:
If you have figured out the O(n) solution, try cod... | true |
c09c07c9c0234ee00371ec41b11e847df9aa775c | MichaelLenghel/Python-Algorithm-Problems | /recursive_reverse_string/recursive_reverse_string.py | 373 | 4.4375 | 4 | # Program to recursively reverse a string
def reverse(s):
# Base Case
if s == "":
return s
# Recursive calls
else:
return reverse(s[1:]) + s[0]
# return s[-1:] + reverse(s[:len(s) - 1])
# return s[len(s) - 1] + reverse(s[:len(s) - 1])
if __name__ == "__main__":
print(reverse("Hello, world!... | true |
a3e8e1b1798d035a0297d479b785cdaf42589c02 | MichaelLenghel/Python-Algorithm-Problems | /anagram_check/anagram_check.py | 1,745 | 4.28125 | 4 | # Program that will check if two strings are anagrams, not including captials or spaces
# Has a time complexity of O(N), ideal for small data sets, but space complexity is of O(26). As 26 references are made from hashmap.
def anagram_check(s1, s2):
# Declare the dictionary
ana_li = {}
# Removes spaces in bo... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.