blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
280a469bdcb4ad39ffbc21a1a87bc375e1e46e64 | Mojoo25/fall2021mr | /intro_python/lesson6/lesson6c.py | 398 | 4.28125 | 4 | # lesson 6c- append to list
# create an empty list
myList = []
# print the number of items in the list and the list contents
print("empty list")
print("len(myList): ", len(myList))
print("myList: ", myList)
dataRead = 1
while dataRead != 'q':
dataRead = input("\nenter list item or q to quit: ")
myList.append(... | true |
885b117e651e0e0e5de533642b1b3106d1dc292e | TopSteven/python-75-hackathon | /text-input-and-output/text-input-and-output.py | 465 | 4.53125 | 5 | '''
Text input in python
input can be taken from the user by two ways using input function. Both ways are shown in this file.
'''
print('Enter your firstname')
firstname = input()
print('the firstname you entered is '+ firstname)
lastname = input('Enter your lastname')
print('the lastname you entered is ',lastna... | true |
253a8bf086444f006b68021f04cd0cae304e7555 | A-jha/Python-Lab | /1-Data Structure and Algorithm/1.9-calculationDict.py | 740 | 4.3125 | 4 | prices = {
'Apple': 80.89,
'banana': 25.45,
'grapes': 90.56,
'mango': 89.56,
'waterMillon': 10.65
}
# zip() - it is often useful to invert the keys and values of the dictionary
# using zip() .
# ---Note the first argument in zip file is consideres as calculatable
# minimum price among the items
mi... | true |
81cda5f893401908123d4c2008f3ae812f283886 | Seeker3000/AlgoPython | /Roman-cipher/ROMANS-cipher-decrypt-key5.py | 1,339 | 4.21875 | 4 | # Copyright (c) 2021 D.Damian
# Released under the MIT license
# ************************************************************************************************
# All letters of the message are converted to upper case as the Romans used only capital letters
# The cipher alphabet is the plain alphabet shifted left or r... | true |
4a8af0f9ea63829027b92cb0a74e65992901b13b | DiniH1/python_collections | /Lists_Tuples.py | 976 | 4.625 | 5 | # Let's create a shopping list
# Syntax [] - name of list = ["","",""]
shopping_list = ["apples","eggs","dark chocolate","tea","bread"]
#
# print(shopping_list)
# print(type(shopping_list))
#
# #How can access dark chocolate using the same conceptt rgat we learned yesterday INDEXING
#
# print(shopping_list[1]) #wll in... | true |
71ad9acd6c6028aa3dd167884742681fec4f52d1 | avinash108/python | /square.py | 489 | 4.3125 | 4 | def printSquares():
'''
Objective : To print squares of positive numbers entered by the user. The program terminates if user enters null string.
Input Parametes : None
Return Value : None
'''
while True:
numString = input('Enter an integer, to end press Enter:')
if numString ==''... | true |
64512f4b875e3e99b58a2d117f5ee3797aa27d4a | AshpakMulani/PythonLearning | /OtherConcepts/StringFunctions.py | 2,883 | 4.375 | 4 | ################## Escape character \n : new line \t:new tab ###################
print("\thello \n world")
#len : length of string
print(len("hello \n world"))
############ String indexing and slicing #####################
my_string='Hello World'
print(my_string[0]) # here string is treated like zero indexed array.... | true |
7f06e624d863d8f4ed08ba94d7eaed3776d49c78 | jicruz96/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/4-print_square.py | 383 | 4.375 | 4 | #!/usr/bin/python3
""" This module defines print_square, a function that prints a square """
def print_square(size):
""" Prints a square of length size using the hash (#) character """
if type(size) != int:
raise TypeError('size must be an integer')
if size < 0:
raise ValueError('size must... | true |
fc9d9a1e42b60afd85fce0571b3c963c68109cdb | Kamal-vsi/30days-Python-Bootcamp | /Day2 challenge.py | 1,794 | 4.21875 | 4 | # Day 2 Challenge
#How to print a string?
print('30 days 30 hour challenge')
print("30 days 30 hour challenge")
#Assigning string to variables
Hours = "thirty"
print(Hours) #output is thirty
name = 'K.Kamalakannan'
print(name) #output is K.Kamalakannan
#indexing using string
Days="Thirty days"
print(Days[0]) #output... | true |
ae2d90071e73a8f64e0c6346406ae9e4fb77d8db | vmalj/workfiles | /python/hr01-ifelse.py | 471 | 4.4375 | 4 | #!/usr/bin/env python3.6
# Given an integer, perform the following conditional actions:
# If n is odd, print Weird
# If n is even and in the inclusive range of 2 to 5, print Not Weird
# If n is even and in the inclusive range of 6 to 20, print Weird
# If n is even and greater than 20, print Not Weird
... | true |
43fada33711d417aa349b8772c76af8d875dabe7 | hhnguyen-20/A_1 | /Python/07-30-21 ~ ListToOddN.py | 207 | 4.125 | 4 | # Write a list to filter odd numbers from a list entered by the user.
# Input: 1,2,3,4,5,6,7,8,9 --> Output: 1,3,5,7,9
values = input()
n = [x for x in values.split(',') if int(x)%2!=0]
print(','.join(n))
| true |
acecc09290e3c43b620750c8818b03cacd23c5fd | natnew/Python-Projects-Crack-A-Code | /crack the code.py | 2,033 | 4.46875 | 4 | # Define a function to find the truth by shifting the letter by a specified amount
def lasso_letter(letter, shift_amount):
# Invoke the ord function to translate the letter to its ASCII code
# Save the code value to the variable called letter_code
letter_code = ord(letter.lower())
# The ASCII num... | true |
4f07feb519b0462f0d59a0347a2fa2f28f8f59df | sdemikhov/python-project-lvl1 | /brain_games/games/gcd.py | 815 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""Contain game-gcd logic."""
from random import randrange
DESCRIPTION = "Find the greatest common divisor of given numbers."
def gcd(num_left, num_right):
"""Return greatest common divisor of given numbers.
Arguments:
num_left -- int number
num_right -- int number
"""... | true |
553d95af926d383ccdde02a637973a186fe33f81 | Hellofafar/Leetcode | /Medium/17_2.py | 1,695 | 4.21875 | 4 | # ------------------------------
# 17. Letter Combinations of a Phone Number
#
# Description:
# Given a string containing digits from 2-9 inclusive, return all possible letter
# combinations that the number could represent.
#
# A mapping of digit to letters (just like on the telephone buttons) is given below. Note
... | true |
4bcec0b9fb955edfc8e10d308287fce3d5fc58a8 | Hellofafar/Leetcode | /Medium/73_2.py | 2,183 | 4.28125 | 4 | # ------------------------------
# 73. Set Matrix Zeroes
#
# Description:
# Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.
#
# Example 1:
# Input:
# [
# [1,1,1],
# [1,0,1],
# [1,1,1]
# ]
# Output:
# [
# [1,0,1],
# [0,0,0],
# [1,0,1]
# ]
#
# Example 2:
# In... | true |
dbee58c6eaefcf7fb1b6499397691b411eb2ae78 | Hellofafar/Leetcode | /Easy/633.py | 929 | 4.15625 | 4 | # ------------------------------
# 633. Sum of Square Numbers
#
# Description:
# Given a non-negative integer c, your task is to decide whether there're two integers a and b such that a2 + b2 = c.
# Example 1:
# Input: 5
# Output: True
# Explanation: 1 * 1 + 2 * 2 = 5
#
# Example 2:
# Input: 3
# Output: False
#
# Ve... | true |
72596ef16b2f316cf665f0e759cf0c0a4bc1299a | Hellofafar/Leetcode | /Medium/515.py | 1,412 | 4.21875 | 4 | # ------------------------------
# 515. Find Largest Value in Each Tree Row
#
# Description:
# You need to find the largest value in each row of a binary tree.
# Example:
# Input:
# 1
# / \
# 3 2
# / \ \
# 5 3 9
# Output: [1, 3, 9]
#
# Version: 1.0
# 12/22/18 by Jia... | true |
d7d72b6d7b6262d070f3856aa8b406e43cda9664 | Hellofafar/Leetcode | /Easy/374.py | 1,320 | 4.28125 | 4 | # ------------------------------
# 374. Guess Number Higher or Lower
#
# Description:
# We are playing the Guess Game. The game is as follows:
# I pick a number from 1 to n. You have to guess which number I picked.
# Every time you guess wrong, I'll tell you whether the number is higher or lower.
# You call a pre-defi... | true |
b711b04550caeb619ebb2e0c1094154973fa4789 | Hellofafar/Leetcode | /Medium/310.py | 2,741 | 4.46875 | 4 | # ------------------------------
# 310. Minimum Height Trees
#
# Description:
# For an undirected graph with tree characteristics, we can choose any node as the root. The result graph is
# then a rooted tree. Among all possible rooted trees, those with minimum height are called minimum height trees
# (MHTs). Given s... | true |
7c8c9808b39ded7aae90fcd08437c30ea512bf83 | Hellofafar/Leetcode | /Medium/299.py | 2,345 | 4.1875 | 4 | # ------------------------------
# 299. Bulls and Cows
#
# Description:
# You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess mat... | true |
13d52ce55e7795d119090a897341ba9d9b9cfb49 | Hellofafar/Leetcode | /Easy/1122.py | 1,827 | 4.28125 | 4 | # ------------------------------
# 1122. Relative Sort Array
#
# Description:
# Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in
# arr2 are also in arr1.
#
# Sort the elements of arr1 such that the relative ordering of items in arr1 are the same
# as in arr2. Elements that don... | true |
284a136aa543d336cd57b77af2db9854ac234e29 | falasyam/Belajar-Python | /Lists/Lists.py | 433 | 4.25 | 4 | myList = []
myList.append(1)
myList.append(2)
myList.append(3)
print(myList[0])
print(myList[1])
print(myList[2])
for x in myList:
print(x)
# Exercise
numbers = []
string = []
name = ["John", "Siti", "Trump"]
numbers.append(1)
numbers.append(2)
numbers.append(3)
string.append("Hello")
string.append("World")
s... | true |
a1ced63cc25f74d2de31727f607199428de98ddd | peterdjlee/ds_algorithms | /practice.py | 1,557 | 4.34375 | 4 | # Create a program that asks the user to enter their name and their age.
# Print out a message addressed to them that tells them the year that they
# will turn 100 years old.
# print('Please enter your name:')
# name = input()
# print('Please enter your age:')
# age = int(input())
# yearWhenHundred = str(2019 + (10... | true |
499d770a00d9d845c584613b37d846201b646ad6 | rhythmvashist/Algorithms-and-Data-Structures | /longest_string_prefix.py | 768 | 4.1875 | 4 | # Write a function to find the longest common prefix string amongst an array of strings.
# If there is no common prefix, return an empty string "".
# Example 1:
# Input: ["flower","flow","flight"]
# Output: "fl"
# Example 2:
# Input: ["dog","racecar","car"]
# Output: ""
# Explanation: There is no common prefix amon... | true |
31294da56c255faf5df8dcf1abd885d507e3288f | Akshit6828/Learning_Python-Course-Codes | /4. Tuples.py | 615 | 4.21875 | 4 | t1=(1,2,3,1,2,1,2,1,1,1,)
print(t1.count('1'))
print(t1.count(1))#Returns count of element 1 present else returns 0 as output
print(t1[-1])#indexing
print(t1[2:])#Slicing
print(t1.index(2))#prints 1st occurence index of 2
print(t1.index(2,3))#prints 1st occurence index of 2 starting searching from initial index=3
#t1[1... | true |
90dd11661fdad239264d70d00d66a3e28e10fcf7 | Rokunamatata-DK/cosc121_tut | /TUT helper/OS_app.py | 1,746 | 4.34375 | 4 | import os
# Greeter is a terminal application that greets old friends warmly,
# and remembers new friends.
### FUNCTIONS ###
def display_title_bar():
# Clears the terminal screen, and displays a title bar.
os.system('clear')
print("\t**********************************************")
... | true |
aff29d22a4ecdc41507af3ef21b20f9223790c59 | nishchay1576/Simpsons-Phone-Book | /Simphons_phone_book.py | 687 | 4.28125 | 4 | # -*- coding: utf-8 -*-
#Simpsons Phone Book
"""
There are some people with the surname 'Neu'.
We are looking for a 'Neu', but we don't know the
first name, we just know that it starts with a 'J'.
Let's write a Python script, which finds all the lines of
the phone book, which contain a person w... | true |
8714ea01dee10b5fd683dc6da8833bbe24747a2b | alex-moffat/Code-Challenges | /2020-10-13/Challenge_1.py | 613 | 4.46875 | 4 | # PYTHON: 3.8.2
# AUTHOR: Alex Moffat
# PURPOSE: Code Challenge
# Requirement: Write a routine that reverses a string in place.
# =============================================================================
def reverseString(arg):
rstr = ""
for i in range(-1, -len(arg) - 1, -1):
rstr += (arg[i])
... | true |
0634c979e4e715d4f8d7e4617b3f551fdc747c74 | xys234/coding-problems | /algo/dp/target_sum.py | 2,492 | 4.28125 | 4 | """
494. Target Sum
Medium
You are given a list of non-negative integers, a1, a2, ..., an, and a target, S.
Now you have 2 symbols + and -. For each integer, you should choose one from + and - as its new symbol.
Find out how many ways to assign symbols to make sum of integers equal to target S.
Example 1:
Input: ... | true |
fd1fbe51441f1a1b06768c3335b6b48b75d473c1 | xys234/coding-problems | /algo/divide_conquer/reverse_pairs.py | 2,806 | 4.3125 | 4 | """
493. Reverse Pairs
Hard
Given an array nums, we call (i, j) an important reverse pair if i < j and nums[i] > 2*nums[j].
You need to return the number of important reverse pairs in the given array.
Example1:
Input: [1,3,2,3,1]
Output: 2
Example2:
Input: [2,4,3,5,1]
Output: 3
Note:
The length of the given arra... | true |
3ffbf2edac89bdfefdacc83c2ffb9384abc8e991 | xys234/coding-problems | /algo/tree/balanced_binary_tree.py | 1,682 | 4.21875 | 4 | """
110. Balanced Binary Tree (Easy)
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.
Example 1:
Given the following tree [3,9,20,null,null,15,7]:
... | true |
a65318667de6fdc76977573cc4b31403e34f169e | neesh7/Neesh_Python_Dictionaries | /dictionaries2.py | 1,340 | 4.25 | 4 | fruit = {"Orange": "a sweet, oranges, citrus fruit",
"grapes": "a small, sweet fruit, grows in bunches",
"Mango": "Nice shape,Beautiful, so juicy",
"lemon": "citrus fruit , so juicy , so sour, women likes lemon",
"kivy": "it's cute but it's not from new zeland"
}
# while Tr... | true |
faab2f948c1ddde81823b66ad1619cc7b742b2f9 | aarushi-nema/automate_boring_stuff_python | /python/CH7/P010CharacterClasses.py | 2,321 | 4.125 | 4 | # \d : Any numberic digit from 0 to 9
# \D : Any character that is not a numeric digit
# \w : Any letter, numeric digit, or the underscore chracter
# \W : Any character that is not a letter, numeric digit, or underscore character
# \s : Any space, tab, or newline character
# \S : Any character that is not a space, lett... | true |
e0da7e8ffc8e15f231002d0f5c1f8ec16e3ef90f | ducay-aristotle/ClassWork_Spring2020 | /Python_Stuff/AnonymousFunctions.py | 1,576 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Date: 09/23/2020
File: AnonymousFunctions.py
Author: Aristotle Ducay
"""
#varying Lambda Functions
addTwo = lambda health, healthBoost: health + healthBoost
average = lambda score_One,score_Two,score_Three: score_One + score_Two + score_Three / 3
powerThree = lambda pwr_UP: pwr_UP**... | true |
b7bb78c21af06f5391c2abf9a22e6ea077f1e03f | kavyareddyp/Assignments | /pyassign/assign7.py | 231 | 4.1875 | 4 | """
7. take a string from the user and check contains only special chars or not?
"""
s=raw_input("Enter a string:")
if s.isalnum():
print "string doesnot contains special chars"
else:
print "string conatins special chars"
| true |
267989d91f81f26fcacfaa0ec622e3443e5ea9c4 | kavyareddyp/Assignments | /pyassign/assign8.py | 239 | 4.25 | 4 | """
8. take a string from the user and check contains only capiatl letters or not?
"""
s=raw_input("Enter a string:")
if s==s.lower():
print "string doesnot contains captials letters"
else:
print "string contains capital letters"
| true |
197e72499c1c67157cc3499e6ff5f93aa864bd80 | bing1zhi2/algorithmPractice | /pyPractice/algoproblem/Balanced_Binary_Tree110.py | 1,483 | 4.21875 | 4 | """
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.
Example 1:
Given the following tree [3,9,20,null,null,15,7]:
3
/ \
9 20
/ \
1... | true |
d6ac4b2a70ad968a20a33d6e46badf14d6998449 | bing1zhi2/algorithmPractice | /pyPractice/algoproblem/ClimbingStairs_70.py | 812 | 4.125 | 4 | """
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Note: Given n will be a positive integer.
Example 1:
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2.... | true |
e8d6f6c2cfa762723364fd572bcca9c077d22c56 | Lahaela/projecteuler | /#1.py | 488 | 4.21875 | 4 | total = 0
for x in range (1,1000):
if x % 3 == 0 or x % 5 == 0:
total = total + x
print 'Total: ', total
#Take every # between 1 and 1000
#Test to see if multiple of 3
#Test to see if multiple of 5
#If test is successful
#Add the number to the 'total'
# at the end of the 1000, 'total' represent... | true |
d7056fd11a374f3d4010722e1594e90c5a610503 | adhikarianilkumar/LearnPython-2.7 | /learn_python_by_programming/basics/14_list_comprehension.py | 1,546 | 4.875 | 5 | # -*- coding: utf-8 -*-
'''
List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.
... | true |
c112ec7e6f010c1e37cf347ac8f75d5238bf2f3c | adhikarianilkumar/LearnPython-2.7 | /learn_python_by_programming/basics/10_identity_operators.py | 1,300 | 4.1875 | 4 | # -*- coding: utf-8 -*-
'''
Operators Precedence
Operator Description
** Exponentiation (raise to the power)
~ + - Complement, unary plus and minus (method names for the last two are +@ and -@)
* / % // Multiply, divide, modulo and floor division
+ - Addition and subtraction
>> << ... | true |
e81a72cbc1236e618230699269249bc90ee51d55 | saxenams/Projects | /test1.py | 778 | 4.1875 | 4 | # Press COMMAND + ENTER to run a single line in the console
print('Welcome to Rodeo!')
# Press CTRL + ENTER with text selected to run multiple lines
# For example, select the following lines
x = 7
x**2
# and remember to press CTRL + ENTER
# Here is an example of using Rodeo:
# Install packages
# Import packages
i... | true |
b9caf2175ef63ee7684aee0a6b7f98b81558533d | ArunPrasad017/python-play | /coding-exercise/Day25-647PalindromicSubStrings.py | 1,358 | 4.125 | 4 | """
Given a string, your task is to count how many palindromic substrings in this string.
The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.
Input: "abc"
Output: 3
Explanation: Three palindromic strings: "a", "b", "c".
Input: "aaa"
Out... | true |
d0027432aeee2626958540d277ab82f0f96f7a6f | ArunPrasad017/python-play | /coding-exercise/Day66-hIndex.py | 983 | 4.3125 | 4 | """
Given an array of citations (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index.
According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more... | true |
1c888cf10164eebb8d86cefe7a216218631dbb1f | middleverse/ads_prac | /calculateBitwiseComplement.py | 556 | 4.3125 | 4 | def calculate_bitwise_complement(n):
number_of_bits = 0
n_copy = n
# count number of bits
while n_copy > 0:
number_of_bits += 1
n_copy = n_copy >> 1
# now that we have number of bits, shift one more, then subtract
all_bits_set = pow(2, number_of_bits) - 1
# XOR... | true |
9ab0e4e01a230a51e6bc236e0bcb3e62d6edd6fb | middleverse/ads_prac | /rearrangeLinkedListInPlace.py | 1,987 | 4.40625 | 4 | # ============================
# Rearrange LinkedList Problem
# ============================
# PROBLEM STATEMENT
# Given the head of a Singly LinkedList, write a method to modify the
# LinkedList such that the nodes from the second half of the LinkedList
# are inserted alternately to the nodes from the first half in... | true |
de702afacaf28df8fc490678956ae795c5bbb0e8 | middleverse/ads_prac | /findSubsetsWithDuplicates.py | 1,020 | 4.25 | 4 | def find_subsets(nums):
subsets = []
nums.sort()
subsets.append([])
start_index, end_index = 0, 0
# go through each number
for i in range(len(nums)):
# we'll want start_index to be 0 everytime, except for when
# we're dealing with a duplicate element
# in that case we'll... | true |
c874655e3d976339321613f489a57f4f4a32764e | middleverse/ads_prac | /sortCharByFrequency.py | 880 | 4.125 | 4 | from heapq import *
def sort_character_by_frequency(str):
reprogrammed_string = ''
frequency_map = dict()
# build a hashmap with frequence of each string
for i in range(len(str)):
frequency_map[str[i]] = frequency_map.get(str[i], 0) + 1
# insert all into max_heap
max_heap = []... | true |
87c8c14528c135438b919231ffc107ecd56275bb | nellybrenda/september-bootcamp | /for loop/assignment.py | 306 | 4.15625 | 4 | app = str(input("Please input a string\n:"))
newelements = ""
for elements in app:
if elements.islower():
newelements+= elements.upper()
elif elements.isupper():
newelements+=elements.lower()
else:
newelements +=elements
print("The new string is",newelements) | true |
8e5ece21098a7cdc93d391657f5066ab8804c43c | ivanf05/python-programs | /ColorsLinkedList_Assignment.py | 1,063 | 4.15625 | 4 | #Ivan Fonseca
#Assignment 10
class Node:
def __init__(self, info=None, next=None):#Default constructor
self.info = info
self.next = next
def __str__(self):#String function
return str(self.info)
node1 = Node (1)#sets node1 to 1
print ("\nnode1 is ", node1)
node2 = Node ("RED")#sets n... | true |
026769fbd3aca34dc489d01ec1a75b2b07955227 | day5555/MyCookbook | /class.py | 1,310 | 4.125 | 4 | #!/usr/bin/python
class Parent: # define parent class
parentAttr = 100
def __init__(self):
print("Calling parent constructor")
def parentMethod(self):
print('Calling parent method')
def setAttr(self, attr):
Parent.parentAttr = attr
def getAttr(self):
print("Parent attri... | true |
f613e3ffcb4b9f32bd68a07b106c8e48eb430a17 | ReishaPuranik/CMPT120-Puranik | /guessing-game.py | 717 | 4.125 | 4 | # Introduction to Programming
# Author: Reisha Puranik
# Date: October 15, 2019
def main():
name = "dog"
while True:
print("The program is thinking of an animal")
guess = input("Guess the name of the animal: ")
if guess[0] == "q":
print("You quit the game.")
break... | true |
de954adadce8f81cf51e9733867559c7dfd68301 | smrtvishnu/python | /playerlevel/square.py | 299 | 4.1875 | 4 | # PYTHON program to find sum of first
# n natural numbers.
# Returns sum of first n natural
# numbers
def findSum(n) :
sum = 0
x = 1
while x <=n :
sum = sum + x
x = x + 1
return sum
# Driver code
n = 5
print findSum(n)
# This code is contributed by Nikita Tiwari.
| true |
fff5b1bb120006cf9865f7f79967db2aece15ff3 | smrtvishnu/python | /playerlevel/s.py | 701 | 4.53125 | 5 | # Python program to reverse a string with special characters
# Returns true if x is an aplhabatic character, false otherwise
def isAlphabet(x):
return x.isalpha()
def reverse(string):
LIST = toList(string)
# Initialize left and right pointers
r = len(LIST) - 1
l = 0
# Traverse LIST from ... | true |
dee83a8c68ddd4284ec3894eaa0890379c7344b1 | astrochialinko/StanCode | /SC001/Class_Demo/SC001_week_3/checkerboard.py | 533 | 4.375 | 4 | """
File: checkerboard.py
Name: Chia-Lin Ko
------------------------
This program prints an alternating
checkerboard pattern on Console
by using nested for loop.
"""
# These constants control the diameter of the checkerboard
ROW = 5 # The number of rows
COL = 8 # The number of cols
def main():
# print checkerbo... | true |
360a4ce48fd9183434eeb8adbb0d0dd38034e520 | astrochialinko/StanCode | /SC001/Class_Demo/SC001_week_3/predicate_function.py | 573 | 4.40625 | 4 | """
File: predicate_function.py
Name: Jerry Liao 2020/08
-------------------------------
This program introduces a predicate function
, def is_odd(n), which returns True on odd
numbers and False on even numbers
"""
def main():
"""
This program tells users if the input number is odd or not
"""
print("T... | true |
9dbc288d440b84397ece30da452867640cf69a1c | astrochialinko/StanCode | /SC001/Class_Demo/SC001_week_3/replace_keyword.py | 554 | 4.125 | 4 | """
File: replace_keyword.py
Name:
----------------------
This file shows how to replace
old_word with new_word by the function called replace
"""
def main():
s = replace('Jerry hates coding', 'hates', 'teaches')
print(s)
def replace(old_s, old_word, new_word):
if old_word not in old_s:
return 'go away!'
else... | true |
4e3e7822ef65949c773aa3d20cf214a007c5c73d | Yao-Ch/OctPyFun3rdDayAM | /Exercise6WithCustomException.py | 1,209 | 4.21875 | 4 | class IsPrimeError(Exception):
pass
def isPrime(nb):
if not isinstance(nb, int): # Error: an int should be provided!!!
e=IsPrimeError("Wrong type of argument received")
raise e
if nb < 0: # Error: a positive int should be provided!!!
# print("Negative argument rece... | true |
f26af26aca93f7f7ea5b8e6031421957902bbb12 | GitAbdelali/Python | /Homework/HW1/DoubleII.py | 643 | 4.21875 | 4 | # Write a Python program that does the following:
# Reads in a principal amount (A floating point number)
# Reads in the annual percentage interest rate for the investment
# Displays the number of years it will take for the investment to double
# DO NOT USE RULE OF 72
prinAmount = float(input(... | true |
6ccd1122a4c1fad483edde71b1c707f6a05cffe3 | GitAbdelali/Python | /Homework/HW1/List.py | 779 | 4.15625 | 4 | # Write a Python program that reads in a list of integers and displays the following:
# A) The average of the numbers in the list
# B) The median value of the numbers
# C) The number of even numbers in the list
import math
# Part A
print("Please enter a list of integers:")
arr = [int(x) for x in input().split()]
num... | true |
2f48e3749a1e58b4a0599269335762802a7c1670 | UtkarshBhardwaj123/Commit-Ur-Code | /Day - 4/Uddish-Saini.py | 432 | 4.15625 | 4 | # Function to check if the two strings are rotations of each other
def rotation(s1,s2):
if (len(s1)!=len(s2)):
return False
else:
s1 = s1+s1
if (s2 in s1):
return True
else:
return False
# Loop for Execution
for t in range(int(input())):
... | true |
cdc4581635af4a49b154933d57695106f69d9a93 | UtkarshBhardwaj123/Commit-Ur-Code | /Day - 3/deepak_jangid.py | 615 | 4.125 | 4 | for t in range(int(input())): # no. of t tset cases
n,m=input().split(" ") # no. of rows and columns separated by space
n=int(n) # rows are converted from string data type to integer data type
m=int(m) # columns are converted from string data type... | true |
67250f95615000534ddadacfd7ef7a6b1bd59a23 | voltz92/ATBS-Files | /Files, Paths/files_1.py | 924 | 4.15625 | 4 | # open() << opens a specific file on read-mode by default
import os, shelve
fileID = open('test.txt')
print(fileID.read())
fileID.close()
fileID = open('test2.txt','w')
st = 'This string has been written by python'
fileID.write(st)
fileID.close()
# to open a file in append mode use 'a' modifier in the open() funct... | true |
685441dd369d26c2ec488b4fc0629bb76a3d2395 | voltz92/ATBS-Files | /Regex/regex_4.py | 1,010 | 4.40625 | 4 | # '^' before a pattern means that the pattern must be present at the start of the string
# '$' after a pattern means that the pattern must be present at the end of the string
# '^pattern$' <<< will look for the exact match of the pattern within a string. so '^ring$' will only return true for 'ring' not in 'string'
# ... | true |
92b0ab5f4c55804bd3ce4d98ed43574a6b61a9db | voltz92/ATBS-Files | /Class 2/2_2.py | 836 | 4.28125 | 4 | # the seterotypical hello world program
print ('Hello World') # function print() << runs a specific block of code when called. The values inside the '()' are called the arguments of the function.
print ('what is your name? ')
myName = input() # takes user input. data type is string
print('Nice to meets you '+myNa... | true |
0cbb20fadc01bfd7ef05e897f17751536a2d192b | SourabhMohite/Python-programs | /Assignment1_5.py | 264 | 4.125 | 4 | """Write a program which display 10 to 1 on screen.
Output : 10 9 8 7 6 5 4 3 2 1"""
def Display(num):
i=0
for i in range(num,0,-1):
print(i)
def main():
value=int(input("Enter the number:"))
Display(value)
if __name__=="__main__":
main()
| true |
ee72504a82e43ba43f5fa39b977a159be32335c2 | saikatmondal15/Games | /GuessTheNumber-MP2.py | 1,820 | 4.15625 | 4 | # template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console
import simplegui
import random
import math
# initialize global variables used in your code
num_range = 100
# helper function to start and restart th... | true |
e14fa09ec183972a9bdf71d4f75d96fd5784d295 | Babatunde13/30-days-of-code-python-ECX | /Python Files/day_24.py | 2,574 | 4.4375 | 4 | def intensive_properties(properties: tuple, units :tuple) -> tuple:
"""
A function named intensive_properties which converts temperature and pressure to a desired unit.
Parameter: --------
properties: tuple
first element is the pressure in N/m2
... | true |
6e700273ef590a89bfb1cfa82acf607a74e7156a | Babatunde13/30-days-of-code-python-ECX | /Python Files/day_6.py | 706 | 4.28125 | 4 | import math
def PowerSet(set_):
'''
A function named PowerSet which returns the subset of a list
'''
# set_size of power set of a set
# with set_size n is (2**n -1)
pow_set_size = int(math.pow(2, len(set_))
# counter = 0
# j = 0
powerset = [[]]
fo... | true |
e848bdd6a8eea868b031ad0462488cf27e171bfc | dpezzin/dpezzin.github.io | /test/Python/dataquest/modules_and_classes/method_count_team_class.py | 1,543 | 4.375 | 4 | #!/usr/bin/env python
class Zoo():
def __init__(self):
self.animals = []
# This is an instance method.
# It can be invoked on any instance of this class.
# Note that because it is an instance method, we still need to put in the self argument.
def add_animal(self, animal):
# This wil... | true |
d7e6601ac6991cc43ab48bdaae5a377312caeb49 | dpezzin/dpezzin.github.io | /test/Python/dataquest/modules_and_classes/count_wins_during_year.py | 1,271 | 4.375 | 4 | #!/usr/bin/env python
# Modify this function to also take a year as input, and returns the wins by the team in the year.
def nfl_wins(team):
count = 0
for row in nfl:
# We need to ensure that we only increment the count when the row pertains to the year we want.
if row[2] == team:
co... | true |
a6a24e36729de5e5a13eb08d829c6a1202fd2408 | dpezzin/dpezzin.github.io | /test/Python/dataquest/statistics/plot_median_mean_methods_colorlines.py | 953 | 4.15625 | 4 | #!/usr/bin/env python
# Let's plot the mean and median side by side in a negatively skewed distribution.
# Sadly, numpy arrays don't have a nice median method, so we have to use a numpy function to compute it.
import numpy
import matplotlib.pyplot as plt
# Plot the histogram
plt.hist(test_scores_negative)
# Compute th... | true |
e6e3839ad331d1f40c677f28af52551587ea4f92 | dpezzin/dpezzin.github.io | /test/Python/dataquest/list_of_lists.py | 387 | 4.1875 | 4 | #!/usr/bin/env python
# Create a list of lists
lolists = [[1,2,3], [10,15,14], [10.1,8.7,2.3]]
# We can pull out the first element of the list, which is [1,2,3].
# Since [1,2,3] is a list, we can also index it to get elements out.
a = lolists[0]
b = a[0]
c = lolists[1]
value_1_0 = c[0]
d = lolists[1]
value_1_2 = d[2... | true |
ec27a0e68e50921e348fb9be75b847ee4e2f46e7 | dpezzin/dpezzin.github.io | /test/Python/dataquest/matrices_and_numpy/vectors.py | 893 | 4.28125 | 4 | #!/usr/bin/env python
# Vectors are similar to python lists in that they can be indexed with only one number.
# Think of a vector as just a single row, or a single column.
# Countries is a vector.
countries = world_alcohol[:,2]
# We can index a vector with only one number.
print(countries[0])
print(countries[10])
# W... | true |
56571328577bc308b0fda25af7b3b5083467eccd | dpezzin/dpezzin.github.io | /test/Python/dataquest/dataframe_basics/sort_multiple_ascending_descending_columns_by_name_to_var2.py | 1,381 | 4.21875 | 4 | #!/usr/bin/env python
# The food at the first row will be the one with the least fat.
# If there is a tie (several foods have no fat), it will be the food with 0 fat and the least sodium.
ascending_fat_then_ascending_sodium = food_info.sort(["Lipid_Tot_(g)", "Sodium_(mg)"], ascending=[True, True])
# It's different tha... | true |
0f868889959f04a5d98f44f0fdaaee839d6dc5da | dpezzin/dpezzin.github.io | /test/Python/dataquest/functions_debugging/tokenize_aka_split_file.py | 404 | 4.375 | 4 | #!/usr/bin/env python
# We can split strings into lists with the .split() method.
# If we use a space as the input to .split(), it will split based on the space.
text = "Bears are probably better than sharks, but I can't get close enough to one to be sure."
tokenized_text = text.split(" ")
# Tokenize the story, and st... | true |
94d6d7a93ee3b59b9fa51680dab4a1e38ba142b8 | dpezzin/dpezzin.github.io | /test/Python/dataquest/matrices_and_numpy/array_shapes.py | 604 | 4.28125 | 4 | #!/usr/bin/env python
# Print the shape of the world alcohol matrix.
# The first number is the number of rows, and the second is the number of columns
print(world_alcohol.shape)
# We can do the same with a vector, but they only have one dimension, so only one number is printed.
print(world_alcohol[1,:].shape)
# Assi... | true |
b8929b6ebcb3d30d8b009a25340832d3042aa067 | dpezzin/dpezzin.github.io | /test/Python/dataquest/count_rows_list_or_csv.py | 685 | 4.15625 | 4 | #!/usr/bin/env python
# Remember how we counted the length of our list before?
# When the loop finishes, count will be equal to 5, which is the number of items in the_list.
# This is because 1 will be added to count for every iteration of the loop.
the_list = [5,6,10,13,17]
count = 0
for item in the_list:
count = c... | true |
cb7c2084a1b468a833c29a0e67f0a07f5d7d4292 | dpezzin/dpezzin.github.io | /test/Python/dataquest/else.py | 681 | 4.46875 | 4 | #!/usr/bin/env python
# The code in an else statement will be executed if the if statement boolean is False.
# This will print "Not 7!"
a = 6
# a doesn't equal 7, so this is False.
if a == 7:
print(a)
else:
print("Not 7!")
# This will print "Nintendo is the best!"
video_game = "Mario"
# video_game is "Mario", ... | true |
559cfac7e01dc23c3635c2d058c4cb7d4346d1be | michaelcyng/python_tutorial | /tutorial6/while_loop_examples/multiples.py | 342 | 4.5 | 4 | print("Input the value of n:")
n = int(input())
print("Input the value of m:")
m = int(input())
print("Below are the multiples of {0} from 1 to {1}".format(m, n))
# TODO: Write a loop to print out all multiples of m which is in range [1, n].
# For example: if m is 3 and n is 10, the program should print out th... | true |
004f91adbcda4fecca1a4958cc8e4612d0385b8e | michaelcyng/python_tutorial | /assignment2/question3.py | 1,937 | 4.1875 | 4 | # Source: https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/
#
# You are given a integer list called candies, where candies[i] means the number of candies the i-th child has.
# You are also given an integer x, which is the extra number of candies that you can distribute to the children.
# For a giv... | true |
0cfcd55cfaabe48d109b8910f617a17191a74cf6 | michaelcyng/python_tutorial | /tutorial4/conditional_statement_examples/check_odd.py | 225 | 4.3125 | 4 | print("Input an integer below:")
number = int(input())
remainder = number % 2
# TODO: Add the code such that:
# 1. If the number is odd, print out: The number is odd
# 2. Otherwise, print out: The number is even
| true |
9c394fe05a3425555005256ca4f5bf01c250cf90 | michaelcyng/python_tutorial | /tutorial9/for_loop_examples/rectangle.py | 307 | 4.46875 | 4 | print("Enter the number of rows:")
num_rows = int(input())
print("Enter the number of columns:")
num_columns = int(input())
for row in range(num_rows):
for column in range(num_columns):
print("*", end="") # end="" means after printing the string, it will not go to the new line
print("")
| true |
4fc1f76952af7882842ca562ef31ae1e346268c9 | AHKerrigan/Blockchain_Presentation | /fullchain.py | 1,880 | 4.125 | 4 | import hashlib
def file_hash(filename):
"""Takes a string representing a file an input and returns the 256bit hash
of that file"""
file_string = ''
fin = open(filename)
for line in fin:
file_string += line.strip()
return hashlib.sha256(file_string.encode()).hexdigest()
def file_to_list(filename):
fin = ope... | true |
f0ddf99a2c8ffca81599e2f1edc10ab3b792ab07 | alexomachinelearning/ahumanlearningmachinelearning | /python/practicespace/ex001coffee.py | 2,932 | 4.96875 | 5 | # There appear to be multiple ways to print the same content in python
# This command tells python to print, "Alex went to Starbucks". Note that the argument is set directly with the print command
print "Alex went to Starbucks"
# The following three arguments tell python to set the variable `name` to "Alex", the vari... | true |
cba1fb178ffe6786c0c77ecb260bd2d08b44684a | LizaChelishev/homework2909 | /homework_7.py | 426 | 4.46875 | 4 | # input numbers until the number <= 0
max_positive_number = 0
number = int(input('please enter a number:'))
while number > 0:
if number > max_positive_number:
max_positive_number = number
number = int(input('please enter a number:'))
# print the highest value
if max_positive_number == 0:
print('no ... | true |
006ca1aca9aceb7d87b2e3695b0f3666bb7b90a3 | Pyk017/TCS_Xplore_Proctered_Assesments | /TCS_DCA_Practice/Question08.py | 1,045 | 4.5625 | 5 | # Take string as an input and check if it contains all the alphabets in English.
# If it contains all the alphabets in English then give the output as:
# 'Yes this sentence contains all English alphabets'.
# If it does not contain all the alphabets in English then give the output as:
# 'No, this sentence does not con... | true |
d5b9230175da03bbd307346a5b256f210ebd48f5 | amit9p/pythonML | /MultiThread/MultiThread.py | 1,065 | 4.15625 | 4 | import threading
def calc_square(number):
print('Square:' , number * number)
def calc_quad(number):
print('Quad:' , number * number * number * number)
def main(number):
print('Def main called')
thread1 = threading.Thread(target=calc_square, args=(number,))
thread2 = threading.Thread(target=calc_... | true |
788d795302783143e73c22e366bd2c9e494fa97f | alex-sa-ur/python-data-structures-and-algorithms | /P2/problem4.py | 2,245 | 4.15625 | 4 | """
Author: Alejandro Sanchez Uribe
Date: 19 Dec 2019
"""
def sort_012(input_list):
"""
Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.
Args:
input_list(list): List to be sorted
"""
next_zero = 0
next_two = len(input_list) - 1
current = 0
... | true |
fd7bca26f9a3eb2da63abbee7800b7cbc0fdb367 | alex-sa-ur/python-data-structures-and-algorithms | /P0/Task0.py | 1,297 | 4.1875 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 0:
What is the first record of te... | true |
d2c6e4967217d3f3a0129427213779c0a7de5fbf | kasikaruppiah/cs5800f17 | /pa1/FastSqrt.py | 491 | 4.15625 | 4 | # Uses python3
# Algorithm:
# 1. Read the user input
# 2. Run the Babylonian method to find the square root of the algorithm
# Analysis:
# 1. Running Time:log n
# 2. Space Complexity: O(1)
# returns the square root of the input
def getSquareRoot(n):
guess = 1
while abs(pow(guess, 2) - n) > 0.01:
gue... | true |
d48434d18171d54cabb637d28c3ac591ff524664 | jesszabala23/Python-TCPactivities | /pythonActivities/12myMath.py | 713 | 4.375 | 4 | #Basic Math
print( 2 * 3 ) # Basic Arithmetic: +, -, /, *
print( 2**3 ) # Basic Arithmetic: +, -, /, *
print( 10 % 3 ) # Modulus Op. : returns remainder of 10/3
print( 1 + 2 * 3 ) # order of operations
print(10 / 3.0) # int's and doubles
#Advance Math
print( 2 * 3 ) # Basic Arithmetic:... | true |
525fdb04da3192fd104835fd80428e84062ef17b | tmrindia/Important-Programmes | /Sorting_Algorithm/merge_sort.py | 1,033 | 4.21875 | 4 | # implementing merge sort algorithm
# p<=q<r
def merge_list(left,right):
result=[]
i,j=0,0
while i < len(left) and j < len(right):
if left[i] <=right[j]:
result.append(left[i])
print "Left result",result
i=i+1
else:
result.append(rig... | true |
3b98f7edc79dc8cf32c6f3ddd3193b515b8cce18 | MariyaLcs/100DaysOfCode-Python | /NumberGuessingGame/main.py | 1,259 | 4.125 | 4 | #https://repl.it/@MashaPodosinova/guess-the-number-start#main.py
from art import logo
import random
print("Welcome to the Number Guessing Game!\nI'm thinking of a number between 1 and 100.")
print(logo)
game_number = random.randint(0, 100)
# print(f"Pssst, the correct answer is {game_number}")
level = input("Choose ... | true |
ee3eb225efaa8a4c6663e1ec20189c2912be202f | govindsinghrawat/python_codes | /leetcode/easy_set/coding/000088_merge_sorted_array.py | 1,587 | 4.15625 | 4 | ##########
#Question#
##########
'''
URL: https://leetcode.com/problems/merge-sorted-array/
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
The number of elements initialized in nums1 and nums2 are m and n respectively.
You may assume that nums1 has enough space (si... | true |
06911896d2dd0ad7ca42fda44abc9e425f3209b5 | oliver060928/rock-paper-scissor | /main.py | 1,310 | 4.25 | 4 | import random
def play (computer):
user = input("whats your choice? 'r' for rock, 'p' for paper, 's' for scissors\n")
user = user.lower()
if user == computer:
return 0
if user == 'p' and computer == 'r':
return 1
if user == 'p' and computer == 's':
return 2
if user == ... | true |
078d8a2bc4c8e64aa6d80f8280547fc5e686b9ae | mesejo/topo | /topo/__init__.py | 1,882 | 4.125 | 4 | import heapq
from collections import deque
from functools import partial
class Queue:
def __init__(self, data, priority=False):
if priority:
self._structure = data[:]
heapq.heapify(self._structure)
self.pop = partial(heapq.heappop, self._structure)
self.pus... | true |
5bddf4e2e21b59f1771398e0a793a765b4825508 | saiwho/learn-python-the-hardway | /ex14.py | 612 | 4.1875 | 4 | from sys import argv
script, user_name = argv
prompt = '--> '
print(f"Hi {user_name}, I'm the {script}")
print("I would like to ask few questions")
print(f"Do you like me {user_name} ?")
likes = input(prompt)
print(f"Where do you live {user_name} ?")
place = input(prompt)
print(f"What is the name of your computer ... | true |
39ffbeda43b76753a238aaec1f664408923f793f | mostlygeek/python-the-hard-way | /ex37/with.py | 2,293 | 4.15625 | 4 | #
# The 'with' statement allows code to be run, and torn down without
# having to use verbose try/except/finally. Useful to more succinctly
# create resources, do stuff and tear down resources.
#
# Particularily with working with files, or IO when exceptions can occure
#
# ref: http://effbot.org/zone/python-with-st... | true |
9d03f49617b2f6cffaf7eb852b8d50fb917b896c | karthikeyamade/phnumb | /phn.py | 1,157 | 4.34375 | 4 | # Python 3 program to print all
# phone numbers staring with 9
# The method that prints all
# possible strings of length k.
# It is mainly a wrapper over
# recursive function printAllKLengthRec()
def printAllKLength(set, k):
n = len(set)
printAllKLengthRec(set, "", n, k)
# The main recursive method
# to ... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.