blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
8bf7fbff0e0776f7af28af9627c2ebf9dbd6a32d | sohaib-93/SOIS_Assingment | /Embedded_Linux/Part_A/prog9.py | 833 | 4.40625 | 4 | # !/usr/bin/python3
# Python Assignment
# Program 9: Implement a python code to count a) number of characters b) numbers of words c) number of lines from an input file to output file.
f = open("finput.txt", "r+")
text = f.read().splitlines()
lines = len(text) # length of the list = number of lines
words = sum(len(li... | true |
211d6ce07287364d6800a059625419ac93e88e12 | sohaib-93/SOIS_Assingment | /Embedded_Linux/Part_A/prog3.py | 769 | 4.53125 | 5 | # !/usr/bin/python3
# Python Assignment
# Program 3: Implement a python code to find the distance between two points.(Euclidian distance)
# Formula for Euclidian distance, Distance = sqrt((x2-x1)^2 + (y2-y1)^2)
def edist(x1,y1,x2,y2):
dist1 = (x2-x1)**2 + (y2-y1)**2
dist = dist1**0.5
return dist
x1 = float(input("... | true |
7d95ce35091a63117f24f34c936b485f9af5917e | sohaib-93/SOIS_Assingment | /Embedded_Linux/Part_A/prog8.py | 497 | 4.28125 | 4 | # !/usr/bin/python3
# Python Assignment
# Program 8: Implement a python code to solve quadratic equation.
# Quadratic Equation Formula: x = b^2 + (sqrt(b^2 - 4ac) / 2a) or b^2 - (sqrt(b^2 - 4ac) / 2a)
print ("ax^(2)+bx+c")
a = int(input("Enter the value of a:"))
b = int(input("Enter the value of b:"))
c = int(input("E... | true |
9d0a50a37674344e868b687f47b9f4eeef8748fe | jtwray/cs-module-project-hash-tables | /applications/crack_caesar/sortingdicts-kinda.py | 2,932 | 4.59375 | 5 | # Can you sort a hash table?
## No!
## the hash function puts keys at random indices
# Do hash tables preserve order?
## NO
## [2, 3, 4, 5]
# my_arr.append(1)
# my_arr.append(2)
# my_arr.append(3)
# [1, 2, 3]
# my_hash_table.put(1)
# my_hash_table.put(2)
# my_hash_table.put(3)
## *Dictionary
### Yes
### Since Pyt... | true |
9bb8498290f491440011fda2ab93b2f20570d4df | petercripps/learning-python | /code/time_check.py | 368 | 4.25 | 4 | # Use date and time to check if within working hours.
from datetime import datetime as dt
start_hour = 8
end_hour = 22
def working_hours(now_hour):
if start_hour < now_hour < end_hour:
return True
else:
return False
if working_hours(dt.now().hour):
print("It is during work hou... | true |
ea9084b8b4da109d9d364e0c7fc44f961e8ceedc | emmagordon/python-bee | /group/reverse_words_in_a_string.py | 602 | 4.28125 | 4 | #!/usr/bin/env python
"""Write a function, f, which takes a string as input and reverses the
order of the words within it.
The character order within the words should remain unchanged.
Any punctuation should be removed.
>>> f('')
''
>>> f('Hello')
'Hello'
>>> f('Hello EuroPython!')
'EuroPython Hello'
>>> f('The cat s... | true |
8d142982d667457fcf063bef95064599a5d51fe0 | Mujeeb-Shaik/Python_Assignment_DS-AIML | /13_problem.py | 1,966 | 4.1875 | 4 | """
You found two items in a treasure chest! The first item weighs weight1 and is worth value1,
and the second item weighs weight2 and is worth value2. What is the total maximum value
of the items you can take with you, assuming that your max weight capacity is maxW and
you can't come back for the items later?
Not... | true |
be1bb2b7b2fa490f0a1c170ad281088047576532 | mani5348/Python | /Day3/Sum_Of_Values.py | 288 | 4.25 | 4 | #write a Program to Sum All the Items in a Dictionary
n=int(input("Enter the no. of keys :"))
dict1={}
for i in range(1,n+1):
key=input("enter key values:")
value=int(input("enter the values of keys:"))
dict1.update({key:value})
sum1=sum(dict1.values())
print(sum1)
| true |
bbd4be4c2712c6e488b9a70a809032560e1f35d9 | mani5348/Python | /Day3/Bubble_sort.py | 353 | 4.28125 | 4 | #write a program to Find the Second Largest Number in a List Using Bubble Sort
list1=[9,3,6,7,4,5,8]
length=len(list1)
for i in range(0,length):
for j in range(0,length-i-1):
if(list1[j]>list1[j+1]):
temp=list1[j]
list1[j]=list1[j+1]
list1[j+1]=temp
print("Second... | true |
287ca547d96ce97e69e1f4d78a8647cdb9b11ffc | bishalpokharel325/python7am | /sixth day to 9th day/codewithharry decorators.py | 2,253 | 4.5 | 4 | """Decorators modify functionality of function."""
"""1. function can be assigned into another variable which itself act as a function"""
def funct1(x,y):
print(x+y)
funct2=funct1
funct2(5,6)
"""2. function lai assigned garisakexi org funct lai delete garda will funct2 also get deleted?"""
def funct3(x,y):
pr... | true |
93ca28d208ff5af73eb00b39535a17cc97092572 | mubar003/bcb_adavnced_2018 | /bcb.advanced.python.2018-master/review/functions.py | 727 | 4.25 | 4 | '''
Paul Villanueva
BCBGSO 2018 Advanced Python Workshop
'''
# The function below squares a number. Run this code and call it on a
# couple different numbers.
def square(n):
return n * n
# Write a function named cube that cubes the input number.
# Define a function square_area that takes the width... | true |
5f5163b99870b9fac1d95f483fb9b64f346e7db2 | VinneyJ/alx-higher_level_programming | /0x07-python-test_driven_development/5-text_indentation.py | 645 | 4.1875 | 4 | #!/usr/bin/python3
"""Contains definition of text_indentation() function"""
def text_indentation(text):
"""Print given text with 2 new lines after '.', '?', and ':' characters.
Args:
text (str): Text to be formatted.
"""
if not isinstance(text, str):
raise TypeError("text must be a st... | true |
9443bf14f31969ad00955eacf6b01164fd37f39d | the-code-matrix/python | /unit6/practice/Unit6_Dictionaries_practice.py | 1,679 | 4.5 | 4 | #!/usr/bin/python
# 1. Write a program to map given fruit name to its cost per pound.
#Solution:
item_cost={ 'banana': 0.69,
'apple' : 1.29,
'pear' : 1.99,
'grapes' : 2.49,
'cherries' : 3.99 }
print("Cost of apple per lb is: ",item_cost['apple'])
print("Cost of grapes ... | true |
8aef5e8d21ab0f028466b88aa7c7c24ed85b5501 | the-code-matrix/python | /unit1/practice/echo.py | 320 | 4.5625 | 5 | # Create a program that prompts the
# user to enter a message and echoes
# the message back (by printing it).
# Your program should do this 3 times.
message_1 = input("Enter message 1: ")
print(message_1)
message_2 = input("Enter message 2: ")
print(message_2)
message_3 = input("Enter message 3: ")
print(message_3) | true |
5a3eb2642017b2adf55a16bd1aa2d939ea65c3f3 | raptogit/python_simplified | /Programs/06_operators.py | 1,196 | 4.46875 | 4 | # #Arithmetic Operators ::
a=5 #Addition operator
b=3
c=a+b
print(c)
s=8-5 #Substraction operator
print(s)
print(9*2) #Multiplication Operator
print(6/3) #division Operator
print(13%3) #Modulus operat... | true |
40c7b0f8fe9101a9227cac07d0c9f6cbd5ef7fcc | AaronChelvan/adventOfCode | /2016/day6part1.py | 1,079 | 4.15625 | 4 | #!/usr/bin/python3
#Converts a letter to the corresponding number
#a->0, b->1, ..., z->25
def charToNumber(char):
return ord(char) - 97
#Converts a number to the corresponding letter
#0->a, 1->b, ..., 25->z
def numberToChar(number):
return chr(number + 97)
with open('day6_input.txt') as f:
lines = f.readlines()
... | true |
92f59612b2697db155da1bdc625fdabc115867b0 | k08puntambekar/IMCC_Python | /Practical3/Program5.py | 589 | 4.375 | 4 | # 5. Write a program to implement polymorphism.
class Honda:
def __init__(self, name, color):
self.name = name
self.color = color
def display(self):
print("Honda car name is : ", self.name, " and color is : ", self.color)
class Audi:
def __init__(self, name, color):
sel... | true |
f6e52e7cc61e9176624dcb96c899034e8ab011ea | jennyfothergill/project_euler | /problems/p9.py | 712 | 4.28125 | 4 | # A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
# a^2 + b^2 = c^2
# For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
# There exists exactly one Pythagorean triplet for which a + b + c = 1000.
# Find the product abc.
from math import sqrt
n = 1000
def is_triplet(a, b, c):
if a**2 + b... | true |
e75b4ae01cdd3c69351143331b14b526c68b660e | Michael-Zagon/ICS3U-Unit4-07-Python | /1_2_number_printer.py | 485 | 4.375 | 4 | #!/usr/bin/env python3
# Created by: Michael Zagon
# Created on: Oct 2021
# This program lists every number from 1000 to 2000
def main():
# This function lists every number from 1000 to 2000
counter = 0
# Process and Output
for counter in range(1000, 2001):
if counter % 5 == 0:
... | true |
15025d260c7794e1a19a129429e2991d8a705ada | devilhtc/leetcode-solutions | /0x01e9_489.Robot_Room_Cleaner/solution.py | 2,537 | 4.125 | 4 | # """
# This is the robot's control interface.
# You should not implement it, or speculate about its implementation
# """
# class Robot:
# def move(self):
# """
# Returns true if the cell in front is open and robot moves into the cell.
# Returns false if the cell in front is blocked and robot st... | true |
f1b5efe9da688ec3db58dac8a9bb293ef095ae5a | gwccu/day3-Maya-1000 | /problemSetDay3.py | 728 | 4.21875 | 4 | integer = int(input("Tell me a number."))
if integer % 2 == 0:
print("That is even.")
else:
print("Why did you put in an odd number? I don't like them.")
a = int(input("Tell me another number."))
if a % 2 == 0:
print("That is even.")
else:
print("Why did you put in an odd number? I don't like them.")... | true |
313e68bb71568fe1e8709fd03ecb4e999bc29ac5 | lisali72159/leetcode | /easy/1200_min_abs_diff.py | 1,088 | 4.15625 | 4 | # Given an array of distinct integers arr, find all pairs of elements with the minimum absolute difference of any two elements.
# Return a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows
# a, b are from arr
# a < b
# b - a equals to the minimum absolute difference of any two element... | true |
e29ba721cad2cf58d8c8c2e41b6b69347a96a677 | jzohdi/practice | /SimpleSymbols.py | 1,138 | 4.125 | 4 |
# Have the function SimpleSymbols(str) take the str parameter being passed and determine if it is an acceptable sequence
# by either returning the string true or false. The str parameter will be composed of + and = symbols with several letters between them
# (ie. ++d+===+c++==a) and for the string to be true each let... | true |
2c570dd2659fa744d2234d7e70062979008c9fe3 | nsky80/competitive_programming | /Hackerrank/Archive 2019/Python Evaluation(built_ins).py | 412 | 4.375 | 4 | # The eval() expression is a very powerful built-in function of Python. It helps in evaluating an expression.
# The expression can be a Python statement, or a code object.
# >>> x = 3
# >>> eval('x+3')
# 6
# >>> a = 'x**2 + x**1 + 1'
# >>> eval(a)
# 13
# >>> type(eval("len"))
# <class 'builtin_function_or_method'>
#... | true |
e0ceeb1da7502b6db937c7cf7da90f4c8adb1eb4 | BrichtaICS3U/assignment-2-logo-and-action-NAKO41 | /logo.py | 2,391 | 4.34375 | 4 | # ICS3U
# Assignment 2: Logo
# <NICK SPROTT>
# adapted from http://www.101computing.net/getting-started-with-pygame/
# Import the pygame library and initialise the game engine
import pygame
pygame.init()
import math
# Define some colours
# Colours are defined using RGB values
BLACK = (0, 0, 0)
WHITE = (255, 255, 255... | true |
0f0f464b3c550ec5397d59392aa038993d3521a1 | ankurtechtips/att | /circularqueue.py | 1,159 | 4.15625 | 4 | # This is the CircularQueue class
class CircularQueue:
# taking input for the size of the Circular queue
def __init__(self, maxSize):
self.queue = list()
# user input value for maxSize
self.maxSize = maxSize
self.head = 0
self.tail = 0
# add element to the queue
def enqueue(self, dat... | true |
7e4a9f3cd3ebc8aa92284b5b2c62a1256b51f401 | rastislp/pands-problem | /weekday.py | 1,677 | 4.46875 | 4 | #Rastislav Petras
#12 Feb 2020
#Excercise 5
#Write a program that outputs whether or not today is a weekday.
# An example of running this program on a Thursday is given below.
print()
print("Welcome in day teller.")
print()
import datetime #import librarys with time functions.
import calendar #import libr... | true |
04a05dfedb19b73cb631555d9ea17d8c79f00b26 | rastislp/pands-problem | /primenum.py | 542 | 4.125 | 4 |
# Ian McLoughlin
# Computing the primes.
# My list of primes - TBD.
P = []
# Loop through all of the numbers we're checking for primality.
for i in range(2, 1000):
# Assume that i is a prime.
isprime = True
# Loop through all values j from 2 up to but not including i.
for j in P:
# See if j divides i.
... | true |
9d5dd4c12b1186a88ad6379c9a4a058d63d3bfde | ishleigh/PythonProjects | /BulletsAdder.py | 805 | 4.21875 | 4 | """
1. Paste text from the clipboard -pyperclip.paste()
2. Do something to it- add bullets *
3. Copy the new text to the clipboard -pyperclip.copy()
"""
#! python3
# bulletPointAdder.py - Adds Wikipedia bullet points to the start
# of each line of text on the clipboard.
import pyperclip
text = pyperclip.past... | true |
7363fe66b7718058f37b9dcb90dc140b3b569fec | r426/python_basics | /10_special_numbers_no_sum.py | 782 | 4.28125 | 4 | # Find out if it is a special number:
# composed of only odd prime digits and
# the sum of its digits is an even number.
# Implementation based on the number of digits
# (not their sum).
def number():
while True:
userInput = input('Please enter a non-negative integer number: ')
if userInput.isnum... | true |
b5a9de5c17145944f5e182c5a947aafa642e2146 | r426/python_basics | /03_reverse_number.py | 468 | 4.3125 | 4 | # Generate the reverse of a given number N.
def number():
while True:
userInput = input('Please enter a big non-negative integer number: ')
if userInput.isnumeric():
return int(userInput)
else:
print("Input error.")
def reverse(number):
reverseNumber = 0
wh... | true |
74b0ef4a5944da5c9e586712e0b28630abcf1f38 | richardOlson/cs-module-project-recursive-sorting | /src/searching/searching.py | 2,520 | 4.34375 | 4 | # TO-DO: Implement a recursive implementation of binary search
def binary_search(arr, target, start, end):
# the base case
if start > end:
return -1
# pick the middle
point = start + ((end - start)//2)
if arr[point] == target:
return point
if arr[point] > target:
# need ... | true |
b810f69f0cbbd72a740385f8e954cc7524769ab8 | MannyP31/CompetitiveProgrammingQuestionBank | /Arrays/Maximum_Difference.py | 1,177 | 4.28125 | 4 | '''
From all the positive integers entered in a list, the aim of the program is
to subtract any two integers such that the result/output is the maximum
possible difference.
'''
# class to compute the difference
class Difference:
def __init__(self, a):
# getting all elements from the entered li... | true |
3203f96749773440ba87ed366bd845ea5a43a2c9 | MannyP31/CompetitiveProgrammingQuestionBank | /DSA 450 GFG/reverse_linked_list_iterative.py | 960 | 4.125 | 4 | #https://leetcode.com/problems/reverse-linked-list/
# Iterative method
#Approach :
# Store the head in a temp variable called current .
# curr = head , prev = null
# Now for a normal linked list , the current will point to the next node and so on till null
# For reverse linked list, the current node should po... | true |
942a3dd1c36e73edb02447e99929d8025b0814cd | MannyP31/CompetitiveProgrammingQuestionBank | /Data Structures/Stacks/balanced_parentheses.py | 792 | 4.21875 | 4 | ## Python code to Check for
# balanced parentheses in an expression
#Function to check parentheses
def validparentheses(s):
open_brace=["{","[","("]
closed_brace=["}","]",")"]
stack=[]
for i in s:
if i in open_brace:
stack.append(i)
elif i in closed_brace:
p=cl... | true |
7979d5e0293630e4b6934b5cf35600e720028bd2 | MannyP31/CompetitiveProgrammingQuestionBank | /General Questions/Longest_Common_Prefix.py | 868 | 4.28125 | 4 | #Longest Common Prefix in python
#Implementation of python program to find the longest common prefix amongst the given list of strings.
#If there is no common prefix then returning 0.
#define the function to evaluate the longest common prefix
def longestCommonPrefix(s):
p = '' #declare an empty s... | true |
84c655acc227222e4f6e141c97949be2aac1e22a | mori-c/cs106a | /sandbox/sandcastles.py | 1,495 | 4.3125 | 4 | """
File: sandcastles.py
-------------------------
Practice of control flow, variable and function concepts using the following files:
1 - subtract_numbers.py
2 - random_numbers.py
3 - liftoff.py
"""
import random
import array
def main():
"""
Part 1
- user inputs numbers, py separates numbers with substract... | true |
cfeb93211aa0377e330ddde26d4eed63766f790f | vinaym97/Simple-Tic-Tac-Toe | /Topics/Split and join/Spellchecker/main.py | 906 | 4.1875 | 4 | """Write a spellchecker that tells you which words in the sentence are spelled incorrectly. Use the dictionary in the code below.
The input format: A sentence. All words are in the lowercase.
The output format: All incorrectly spelled words in the order of their appearance in the sentence. If all words are spelled co... | true |
8979055b59283c406fc719d073cecbb72c327f06 | mchughj/AirQualitySensor | /storage/create_sqlite_db.py | 1,666 | 4.46875 | 4 | #!/usr/bin/python3
# This program will create the table structure within the
# sqlite3 database instance. It destroys existing data
# but only if you allow it.
import sqlite3
import os.path
def create_connection(db_file):
""" create a database connection to a SQLite database """
conn = None
try:
... | true |
31a805a8387d66f06ecf741aaec458dc413f27f6 | jm9176/Data_structures_practice | /If_Tree_is_BST.py | 734 | 4.40625 | 4 | '''
To check if the given tree is a BST tree or not
'''
# creating a class for the node
class Node:
def __init__(self, node = None):
self.node = node
self.left = None
self.right = None
# Function running a chek on the given tree
def chk_tree(temp):
if not temp:
return
... | true |
a80a73379941066b0356763a25be654d7786db9a | jm9176/Data_structures_practice | /Finding_max_of_sub_arrays.py | 503 | 4.3125 | 4 | '''
Finding the maximum value in each of the
sub array of size k. If the given array is
[10,5,2,7,8,7] then the resulting output
should be [10,7,8,8].
'''
# this fnction will return the list of
# max element of the sub array
def max_sub(arr, k):
max_sub_arr = []
for i in range(len(arr)-k+1):
m... | true |
d2d6b6221c9f0b6ce00befa87966ba9c55a9425c | jm9176/Data_structures_practice | /Finding_pair_with_given_sum.py | 571 | 4.125 | 4 | # finding a pair with a given sum
def pair_check(arr, var_sum):
for var in arr:
if var_sum - var in arr:
print "Match found"
return var, var_sum - var
else:
print "Match not found"
arr = []
try:
for i in range(int(input("Enter the le... | true |
02d59a4c2fad30f306482a63ffa5966511543f88 | jm9176/Data_structures_practice | /Finding_the_lowest_positive_missing_element.py | 645 | 4.375 | 4 | '''
Find the lowest positive integer that does not exist in the
array. The array can contain duplicates and negative numbers
as well. For example, the input [3, 4, -1, 1] should give 2.
The input [1, 2, 0] should give 3.
'''
# Function to find and add the lowest positive element
# to the defined input
def input_elem(... | true |
69163cc318847e1c18b91c7c7c6203aee9e7365b | QUSEIT/django-drf-skel | /libs/utils.py | 701 | 4.125 | 4 | from decimal import Decimal
import random
import string
def convert_weight_unit(from_, to, weight):
"""单位转换"""
units = ['lb', 'oz', 'kg', 'g']
kg_2_dict = {
'oz': Decimal('35.2739619'),
'lb': Decimal('2.2046226'),
'g': Decimal(1000),
'kg': Decimal(1),
}
if from_ no... | true |
987b4ab8d7c7a262ece34dabdbdd182c087adc2c | kelseyoo14/oo-melons | /melons.py | 2,009 | 4.28125 | 4 | """This file should have our order classes in it."""
class AbstractMelonOrder(object):
"""A melon order at UberMelon."""
# initializing class attributes that are default for all melons order
shipped = False
def __init__(self, species, qty, order_type, tax, country_code):
"""Initialize melon o... | true |
1c1a06d62faada3fbb4992a94b6fa909e07ae4fc | Thraegwaster/my-pi-projects | /old-rpi-files/test_count.py | 327 | 4.125 | 4 | # This is just a test
def testcount():
myCount = raw_input("Enter your count: ")
if myCount == '3':
print("The number of thy counting")
elif myCount == '4':
print("Four shalt thou not count")
elif myCount == '5':
print("Five is right out")
else:
print("Thou shalt count to three, no more, no less.")
testc... | true |
9efee6b49cc9b260986d5dbe7db8df7c48d7a1ea | Thraegwaster/my-pi-projects | /python3/chris/primefactorizor/divider.py | 662 | 4.25 | 4 | # Divider
# Takes a number and a divisor as input, then counts how many times
# the number goes into the divisor before a remainder is enocuntered.
def divider(dividend, divisor):
index = 0
# we don't want dividend to be changed by the subsequent calculation.
quotient = dividend
while quotient % divisor == 0:
... | true |
3cc7c35b40fef068a4cc6c697d0016c03a522807 | endurance11/number-game | /gtn.py | 659 | 4.25 | 4 | print('''
Welcome
If you want to beat the Computer, guess the right number between 0 and 9
Remember you have only 3 guesses
''')
name=input("What's your name? ")
import random
number=random.randint(0,9)
guess_count=0
guess_limit=3
while guess_count<guess_limit:
guess=int(input("@@@@>>> GUESS : "))
guess_count+=1... | true |
aba13551e40c413eff1db924393773a94a607eeb | giangtranml/Project-Euler | /P1-10/p4.py | 884 | 4.21875 | 4 | """
Name: Largest palindrome product.
A palindromic number reads the same both ways.
The largest palindrome made from the product of
two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product
of two 3-digit numbers.
---------------------------... | true |
31132c770344013588f88d6178ebca95df3d869c | viltsu123/basic_python_practice | /data_analysis_learning/MatplotlibExample.py | 1,653 | 4.28125 | 4 | import numpy as np
import matplotlib.pyplot as plt
print("** Import matplotlib.pyplot as plt and set %matplotlib inline if you are using the jupyter notebook. What command do you use if you aren't using the jupyter notebook?**")
print("plt.show()")
print()
x = np.arange(0, 100)
y = x*2
z = x**2
'''
## Exercise 1
** ... | true |
94ee5e375cb64e6b6786a95f1e62148b1e45b0ef | Nishi216/PYTHON-CODES | /NUMPY/numpy8.py | 1,107 | 4.34375 | 4 | ''' Numpy sorting '''
#Different ways of sorting
import numpy as np
array = np.array([[10,2,4],[5,9,1],[3,2,8]])
print('The array is : \n',array)
print('The sorted array is : \n',np.sort(array,axis=None))
print('Sorting array along the rows : \n',np.sort(array,axis=1))
print('Sorting array along the columns : ... | true |
99d11a07744936b5fc9f64e07c2237d23c45236e | Nishi216/PYTHON-CODES | /NUMPY/numpy10.py | 614 | 4.25 | 4 | ''' Creating your own data type and using it to create the array '''
import numpy as np
dt = np.dtype(np.int64)
print('The data type is: ',dt)
print()
dt = np.dtype([('age',np.int32)])
print('The data type defined is: ',dt)
print('The data type of age is: ',dt['age'])
print()
dt = np.dtype([('name','S20'... | true |
7760126769cbf27c81971da7354bc33c57fd3085 | Nishi216/PYTHON-CODES | /DICTIONARY/dict1.py | 1,527 | 4.34375 | 4 | #for creating a dictionary
dict = {'prog_lang1':'python','prog_lang2':'java','prog_lang3':'c++','prog_lang4':'javascript'}
print('The dictionary created is: ')
print(dict)
print()
#to get only the keys from dictionary
print('The keys are: ',dict.keys()) #this will give in list form
for val in dict.... | true |
42b3891d2911ea5f8f42f74f223f6120ee4c255a | caglagul/example-prime-1 | /isprimex.py | 555 | 4.1875 | 4 | def isprime(x):
counter = 0
for i in range(2, x):
if x % i == 0:
counter = counter + 1
if counter == 0:
print("True! It is a prime number.")
else:
print("False! It is not a prime number.")
while True:
x = int(input("Enter a number:"))
if x>0:
if x %... | true |
05d25aedab2b5f0916042557f2635ba79a9d9257 | ShunKaiZhang/LeetCode | /search_insert_position.py | 776 | 4.1875 | 4 | # python3
# Given a sorted array and a target value, return the index if the target is found.
# If not, return the index where it would be if it were inserted in order.
# You may assume no duplicates in the array.
# Here are few examples.
# [1,3,5,6], 5 → 2
# [1,3,5,6], 2 → 1
# [1,3,5,6], 7 → 4
# [1,3,5,6],... | true |
8a2027785914b52545d65b1332d2502ced8e3b5d | ShunKaiZhang/LeetCode | /flatten_binary_tree_to_linked_list.py | 1,491 | 4.40625 | 4 | # python3
# 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
# \
# ... | true |
900d468157c948c32bc959f9462e861e765a9d85 | ShunKaiZhang/LeetCode | /reverse_words_in_a_string_III.py | 484 | 4.21875 | 4 | # python3
# Given a string, you need to reverse the order of
# characters in each word within a sentence while still preserving whitespace and initial word order.
# Example:
# Input: "Let's take LeetCode contest"
# Output: "s'teL ekat edoCteeL tsetnoc"
# My solution
class Solution(object):
def reverseWo... | true |
72fa161b02264138f4c7ec6b2e12f31413c23baa | ShunKaiZhang/LeetCode | /binary_search_tree_iterator.py | 1,317 | 4.1875 | 4 | # python3
# Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
# Calling next() will return the next smallest number in the BST.
# Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.... | true |
36574b984807772900de46bab6121a6932936d7c | MaxDol8888/CodeClubProjects | /quizshowGame.py | 736 | 4.125 | 4 | print('======= WELCOME TO GABY''S QUIZSHOW! =======')
score = 0
#ask first question
print("What city is this years Olympics in?")
answer = input()
if answer == "Rio" or answer == "rio":
print("Correct!")
score += 1
print("Your current score is:", score)
else:
print("Your current score is:", score)
... | true |
410308838ec85af96605487ecbcb139688446a83 | christos-dimizas/Python-for-Data-Science-and-Machine-Learning | /pythonDataVisualization/Seaborn/regressionPlot.py | 2,810 | 4.1875 | 4 | # ------------------------------------------------------------ #
# ------- Regression Plots ------- #
# Seaborn has many built-in capabilities for regression plots,
# however we won't really discuss regression until the machine
# learning section of the course, so we will only cover the
# lmplot() function... | true |
bbf8b5718568d7b9ef2974b393b8ce361eeefe1f | TerryLun/Code-Playground | /Leetcode Problems/lc1389e.py | 680 | 4.28125 | 4 | """
1389. Create Target Array in the Given Order
Given two arrays of integers nums and index. Your task is to create target array under the following rules:
Initially target array is empty.
From left to right read nums[i] and index[i], insert at index index[i] the value nums[i] in target array.
Repeat the previous st... | true |
9313918ae338b6950bc3df26b30b83962403e82a | syvwlch/MIT-OpenCourseWare---6.00 | /ps1b.py | 1,291 | 4.34375 | 4 | # Problem Set 1
# Name: Mathieu Glachant
# Collaborators: None
# Time Spent: 0:30
#
# Gathering user inputs
initial_balance=float(raw_input('Enter the outstanding balance'
' on your credit card: '))
annual_interest_rate=float(raw_input('Enter the annual credit card interest rate'
... | true |
185a14e652863682964e15764408405f45459dc9 | harshilvadsara/Getting-started-with-python-Coursera | /Assignment 5.2.py | 391 | 4.15625 | 4 | largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done" :
break
try :
numb = int(num)
except :
print('Invalid input')
if smallest is None :
smallest = numb
elif numb < smallest :
smallest = numb
elif numb > largest :
largest = numb
print("Maximum is", largest)
print("Minimum is", sma... | true |
ce952e7599a131cf66e9079a68505a09438b2b77 | MarcBanuls/Freecodecamp_Projects | /Data_Analysis_With_Python_Projects/Mean_Variance_Standard_Deviation_Calculator/mean_var_std.py | 1,431 | 4.1875 | 4 | # Import Numpy
import numpy as np
def calculate(lst):
# In case the list has the expected length, it will be reshaped to a 3x3 matrix
if len(lst) == 9:
reshaped = np.reshape(lst, (3,3))
# In case the list has a different length, a ValueError is raised
else:
raise ValueError("List must c... | true |
62e00457178016c2402e9e6413b2a6c83505d33d | mohammedvaghjipurwala/Learning-Python- | /Palindrome.py | 414 | 4.625 | 5 | #################################################
#
#Ask the user for a string and print out whether this string is a palindrome or not.
#
#################################################
Str = input("Enter a string: ").lower()
### Reverse the string
Rev_str = Str[::-1]
#condition if palindrome
if Str == Rev_str... | true |
f6847b87e545e85958b4b887a495a89394863a25 | mohammedvaghjipurwala/Learning-Python- | /DrawBoard.py | 1,094 | 4.5 | 4 | #######################################################################
'''
Time for some fake graphics! Let’s say we want to draw game boards that look like this:
--- --- ---
| | | |
--- --- ---
| | | |
--- --- ---
| | | |
--- --- ---
This one is 3x3 (like in tic tac toe). Obviously, t... | true |
594fbb3446570ebd9253162ee6a1f89828a8a49d | Srajan-Jaiswal/Python-Programming | /amstrong_number.py | 213 | 4.1875 | 4 | a=int(input("Enter the number: "))
num=a
ans=0
while(num>0):
d = num%10
ans+=pow(d,3)
num = int(num/10)
if(ans==a):
print("It's an amstrong number.")
else:
print("It's not an amstrong number")
| true |
95d45a6991967fecc5356eefce42740706d50514 | Jcvita/CS1 | /Week7/biggiesort.py | 1,608 | 4.25 | 4 | """
Joseph Vita
CSCI-141 Herring
10/9/19
biggiesort.py reads numbers from a file, puts them in a list and sorts
them using the BiggieSort algorithm
"""
def main():
# file = open(input("Sort which file? "))
file = open('C:\\Users\\jcvit\\Documents\\CS1\\Week7\\nums')
lines = file.readlines()
tempstr =... | true |
8141a45c20d0dc7cc3cb51f2faf361bfbeb7e1b1 | Jcvita/CS1 | /Week4/zigzag.py | 1,728 | 4.3125 | 4 | """
Joseph Vita
Program creates a colored zig zag stair shape using recursion
"""
import turtle
def main():
turtle.speed(0)
depth = int(input("How many layers do you want? "))
zigzag(100, depth, 0)
turtle.done()
def draw_l(size, back, count):
"""
param: size
precondition: turtle facing... | true |
086243d392736aeb25fec6784922fde63c5b0873 | anushalihala/SOC2018 | /hackathons/week2/trienode.py | 1,703 | 4.375 | 4 | #!/usr/bin/env python3
class TrieNode(object):
"""
This class represents a node in a trie
"""
def __init__(self, text: str):
"""
Constructor: initialize a trie node with a given text string
:param text: text string at this trie node
"""
self.__text = text
... | true |
bb3e5d77d477bc3f690b548406bacab3e31ac902 | Zumh/PythonUdemyLessons | /PythonLessons/FibonnaciNumber.py | 2,962 | 4.28125 | 4 | # This is Naive algorithm for calculating nth term of Fibonnaci Sequence
# This is the big-O notation formula, T(n) = 3 + T (n-1) + T(n-2).
# Here we create the program to caclulate fibonnaci number
# First we assign two number in dynamic array or datastructer which is 0 and 1
# Then we add the number using recursive f... | true |
cfd2cc81cc9e04c64b16f0a01c17c9c01da54143 | quanlidavid/top50pythoninterviewquestions | /Q49.py | 386 | 4.15625 | 4 | # 49. What is the output of following code in Python?
# >>>name = 'John Smith'
# print name[:5]+name[5:]
"""
John Smith
This is an example of Slicing. Since we are slicing at the same index,
the first name[:5] gives the substring name upto 5th location excluding 5th location.
The name[:5] gives the rest of the substr... | true |
b3ae13465e597c61dc648a0d91bfb527fdd10ba1 | Daymond-Blair/picking-up-python | /55_oo_inheritance_basics_overriding methods_and_str_special_method_default_values_for_methods.py | 1,995 | 4.125 | 4 | # 55 56 57 OO Inheritance Basics, Overriding Methods, Overriding __str__ special_method_default_values_for_methods
# Python conventions:
# 2. Class names should use CapWords convention.
# 3. Variables should use thisStyle convention.
# 4. Always use self for the first argument to instance methods.
# 5. When writing me... | true |
237598368af3a1fb9f7ef1058419b1ff5cbc8e71 | Daymond-Blair/picking-up-python | /48_49_tkinter_gui.py | 1,098 | 4.125 | 4 | # 48 49 tkinter gui
from tkinter import * # MODULE/PACKAGE that contains many many classes - * means import ALL OF THESE CLASSES FOR USE
root = Tk() # instance of Class Tk() from MODULE TKINTER aka OBJECT!!!
pythonCourseLogo = PhotoImage(file="giphy-downsized.gif") # photo image function grabs image file
rightLab... | true |
ced51dfc8fe013921040fb178e64d9edae42ee3e | dvishnu/py_basics | /classes.py | 1,851 | 4.59375 | 5 | # basics on python classes
# __init_() is always executed when a class is being initiated
class student:
def __init__(self,name,age):
self.name = name # self reference
self.age = age
print("Hi My name is {} and i am {} years old".format(name,age))
s1 = student("Vishnu", 28)
print("My age ... | true |
3e8922eb850931e0ef6b64ca092e497e11f2d668 | NCPlayz/screen | /screen/utils/math.py | 792 | 4.125 | 4 | import math
def distance(*pairs):
"""
Calculates euclidean distance.
Parameters
----------
*pairs: Tuple[:class:`int`, :class:`int`]
An iterable of pairs to compare.
Returns
-------
:class:`float`
The euclidean distance.
"""
return math.sqrt(sum((p[0] - p[1])... | true |
312a93a4d26a775412c1be13455ec503f6fc1f16 | dbhoite/LearnPython | /DataStructures.py | 2,199 | 4.25 | 4 | def findFirstDuplicate(numlist):
"""Returns the first duplicate number in a given list, None if no duplicate
Arguments:
numlist {list[integer]} -- input list of integers
Returns:
integer -- first duplicate number
"""
# set operations
numset = set()
for num in numlist:
... | true |
d1962c1a9a3a1bbb97a7ab9bd7567f4638230674 | dsabalete/binutils | /lpthw/ex15.py | 617 | 4.15625 | 4 | # -*- coding: utf-8 -*-
# http://learnpythonthehardway.org/book/ex15.html
# import feature argv from package sys
from sys import argv
# extract values packed in argv
script, filename = argv
# open file which name is in filename var
txt = open(filename)
# Nice output
print "Here's your file %r:" % filename
# File co... | true |
85a41b62ec3f79d1243a852f3f88fa1a0900d328 | pbchandra/cryptography | /cryptography/Python/caesar_crack.py | 869 | 4.3125 | 4 | #we need the alphabet because we convert letters into numerical values to be able to use
#mathematical operations (note we encrypt the spaces as well)
ALPHABET = ' ABCDEFGHIJKLMNOPQRSTUVWXYZ'
#cracking the caesar encryption algorithm with brute-force
def caesar_crack(cipher_text):
#we try all the possible key... | true |
c6130096fc3a581323001dcea1f2c9fb696adab7 | piyushPathak309/100-Days-of-Python-Coding | /Area of a Circle.py | 489 | 4.46875 | 4 | # Write a Python program that finds the area of a circle from the value of the diameter d.
#
# The value of d should be provided by the user.
#
# The area of a circle is equal to pi*(radius)^2. The radius is the value of the diameter divided by 2.
#
# Round the value of the area to two decimal places.
#
# You m... | true |
1da282a3db3a9b690c69d8b9a7261d8685ad6d5a | piyushPathak309/100-Days-of-Python-Coding | /Challenge Solve Quadratic Equations.py | 1,300 | 4.375 | 4 | # Write a Python program that prints the positive and negative solutions (roots) for a quadratic equation.
#
# If the equation only has one solution, print the solution as the output.
#
# If it has two solutions, print the negative one first and the positive one second on the same line.
#
# If the equation has no... | true |
4e56f040e15f71067bf725fa1c6368fe9600ef62 | piyushPathak309/100-Days-of-Python-Coding | /Check String Contain Numbers or not.py | 217 | 4.21875 | 4 | # Write a Python program that check if a string only contains numbers.
#
# If it does, print True. Else, print False.
text = input("Enter a text: ")
if (text.isdigit()):
print(True)
else:
print(False)
| true |
5b646ffd8354cebd9e929ecf336550b31792e52d | amiskov/real-python | /part1/02. Fundamentals: Working with Strings/notes.py | 1,390 | 4.5625 | 5 | """
Fundamentals: Working with Strings
"""
# "Addition" and "multiplication" of strings
print('hello' * 3)
print('hello' + 'world')
# Convert strings to numbers
print(int('22') + float(1.35))
# We can't convert floating point strings to integers
# int('22.3') # error
# Convert numbers to strings
print(str(22.3) + '... | true |
5997e47a7d55ef99daf50d986493eeca7a7245a4 | zecookiez/CanadianComputingCompetition | /2018/Senior/sunflowers.py | 1,424 | 4.15625 | 4 | """Barbara plants N different sunflowers, each with a unique height, ordered from smallest to largest, and records their heights for N consecutive days. Each day, all of her flowers grow taller than they were the day before.
She records each of these measurements in a table, with one row for each plant, with the first... | true |
abd86de13f0ee03be189915181c1bb753ef1d88c | UnknownAbyss/CTF-Write-ups | /HSCTF 7/Miscellaneous/My First Calculator/calculator.py | 805 | 4.21875 | 4 | #!/usr/bin/env python2.7
try:
print("Welcome to my calculator!")
print("You can add, subtract, multiply and divide some numbers")
print("")
first = int(input("First number: "))
second = int(input("Second number: "))
operation = str(raw_input("Operation (+ - * /): "))
if first != 1 or se... | true |
9f709bddfc95ddef6e0b1e4c074924cc2fe8278f | mikesorsibin/PythonHero | /Generators/Example_three.py | 285 | 4.15625 | 4 | def myfunc():
for x in range(3):
yield x
x = myfunc()
#using next to call the values of x one by one
print(next(x))
#iter keyword
s="hello"
for x in s:
print(x)
#here we cannot directly call next method, we need to iter s.
iter_s = iter(s)
print(next(iter_s))
| true |
3f7235eccddf88ef10b556af01ffbe1a8c0cf44f | mikesorsibin/PythonHero | /Inbuilt and Third Party Modules/re_one.py | 585 | 4.1875 | 4 | import re
# List of patterns to search for
patterns = ['term1', 'term2']
# Text to parse
text = 'This is a string with term1, but it does not have the other term.'
for pattern in patterns:
print('Searching for "%s" in:\n "%s"\n' %(pattern,text))
#Check for match
if re.search(pattern,text):
p... | true |
0906f368808b375ed77eb7fd946b3c2ea78d073f | danrihe/Fractals | /TriangleFractal.py | 2,413 | 4.40625 | 4 | import turtle #input the turtle module
wn = turtle.Screen() #create the screen
wn.bgcolor("black")
hippo = turtle.Turtle() #create 4 turtles
fishy = turtle.Turtle()
horse = turtle.Turtle()
sheeha = turtle.Turtle()
print("What color would you like **hippo** to be? (Not black)") #allows user to define t... | true |
7c6a81e88ffb8eb0dc9c3b67fe9552bdbfcaa2af | momentum-cohort-2019-09/examples | /w5d2--word-frequency/word_frequency.py | 2,753 | 4.125 | 4 | import string
STOP_WORDS = [
'a', 'an', 'and', 'are', 'as', 'at', 'be', 'by', 'for', 'from', 'has', 'he',
'i', 'in', 'is', 'it', 'its', 'of', 'on', 'that', 'the', 'to', 'were',
'will', 'with'
]
def remove_stop_words(words):
"""Given a list of words, remove all words found in STOP_WORDS."""
filter... | true |
14c0855e08dca33dedd9b2a619b6aad79373f892 | harkbot/beginners_python | /whos_yo_daddy.py | 1,898 | 4.34375 | 4 | #Who's yo daddy?
#Self-coded
#create dictionary of sons and fathers
#key = son, value = father
#make options to exit, enter name of son to get father, add, replace, and delete son-father pairs
daddy = {"Bill": "Tedd", "Jack": "Jill?", "Rory": "Kyle", "Kevin": "Adam", "Dylan": "Jeremy"}
choice = None
print()
while ... | true |
ffb8b75b6d47da30a53c358148b0e64012a95495 | khaloodi/graphs_codecademy | /graph_search/bfs.py | 1,282 | 4.28125 | 4 | '''
Breadth-First Search: Take My Breadth Away
Unlike DFS, BFS is primarily concerned with the shortest path that exists between two points, so that’s what we’ll be thinking about as we build out our breadth-first search function.
Using a queue will help us keep track of the current vertex and its corresponding path. ... | true |
7530c19e94561d02d5f4f26a0d3a6a3d25018949 | nahTiQ/poker_bot | /table.py | 2,815 | 4.15625 | 4 | '''Table object'''
from random import randint
from players import Player
import console as c
class Table:
def __init__(self):
self.players = 0
self.cards = []
self.pot_round = 0
self.pot = 0
def ask_for_players(self):
'''Ask for a number, convert to int, then return that number to pass
t... | true |
91b6c2dbe6ff6c2d2c4ff492c6a4e872a5da5d22 | pwatson1/python | /exampleCode/inheritance_ex1.py | 896 | 4.125 | 4 | # Object oriented programing based around classes and
# instances of those classes (aka Objects)
# How do classes interact and Directly effect one another?
# Inheritence - when one class gains all the attributes of
# another class
# BaseClass is the parent class
# Must use object so the child class can refer ... | true |
db3d42f5b60b5478fe2081a5f564f48bca96c71c | pwatson1/python | /exampleCode/nesting_functions_decorators.py | 2,138 | 4.625 | 5 | # what are nesting functions? Functions that are
# declared within other Functions
'''
def outside():
def printHam():
print "ham"
return printHam
myFunc = outside()
myFunc()
'''
'''
# why nest a function within a function?
def outside():
# this acts like a class for the subfunctions... | true |
c97bb7b63b95d8e4004876c4fcc9ec45afdacb85 | pwatson1/python | /exampleCode/singletonMetaClass.py | 1,215 | 4.375 | 4 | # Chapter 17
class Singleton(type):
# _instance is just a container name for the dictionary
# but it makes it easier to foloow what's happening
_instances = {}
# this function uses cls instead of self . Unlike self which refers
# to the parent class, cls refers to any class
def __call__(cls, *args, **kwa... | true |
5d5adcde16694ecb2dcf02af9af1264f972c823a | crazcalm/PyTN_talk_proposal | /recipies/recipe1/recipe1.py | 701 | 4.3125 | 4 | """
Source: Python Cookbook, 3rd edition, number 4.14
Problem:
--------
You have a nested sequence that you want to flatten into a single list of
values
Solution:
---------
This is easily solved by writing a recursive generator function involving a
yield from statement
Notes:
------
1. Python 2 does not have ... | true |
89dfe9e4aef4b838180e5e36928a4bb1bfde8b19 | nnanchari/CodingBat | /Warmup-1/front3.py | 313 | 4.15625 | 4 | #Given a string, we'll say that the front is the first 3 chars of the string. If the string length is less than 3,
#the front is whatever is there. Return a new string which is 3 copies of the front.
def front3(str):
front=str[:3]
if len(str)<3:
return str+str+str
else:
return front+front+front
| true |
ef733ebbf670d6d41b80406a57c09b261e029856 | pcolonna/coding-exercises | /Chapter_2/2.3_delete_mid_node.py | 1,226 | 4.34375 | 4 | # Question 2.3: delete_middle_node.
"""
Algo to delete a node in the middle of a singly linked list.
Not necessarily the middle, just any node that is not the first or last one.
"""
from LinkedList import LinkedList
"""
To delete a node in a linked list, you can just skip it. Jump or ignore it.
So if... | true |
c1e9d0096130246882886fecb3dd52106bb4f657 | pcolonna/coding-exercises | /Chapter_3/3.5_Sort_Stack.py | 1,182 | 4.125 | 4 | # Question 3.5: Sort Stack
#
# Sort a stack such as the smallest item is on top.
# Use only one additional temporary stack.
from random import randrange
class Stack(list):
def peak(self):
return self[-1]
def push(self, item):
self.append(item)
def empty(self):
return len(self... | true |
a50dac74db197f2e63675b1bf0bbcaaa53c3eaa1 | heenashree/pyTutorialsforAnalytics | /Lists/listOperations.py | 2,292 | 4.34375 | 4 | #!/bin/python
import sys
mega_list = [2,3,4,5.5,6,'hi']
list1 = ["hi", "1", 1, 3.4, "there", True]
def add_an_item(item):
print("Your list before append", list1)
print("Adding/appending an item at the end of the list\n")
list1.append(item)
print("Item is appended\n")
print(list1)
def update_to_list... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.