blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
e79b3bee9714ca2a548311b7e78fd203503d70e1 | ShifaZaman/IntroToPython | /Pyramid.py | 215 | 4.34375 | 4 | print("Input a number to make a pyramid!")
number=input()
for a in range(2,13): #I started at 2 because when you start at 1, it repeats. it'll be like
#3
#3
#33
#333
print(number*a)
'''c="5"
print(3*c)''' | true |
fc0c9b2102f094a2f6b79dd97e276ed6eb0f0679 | ShifaZaman/IntroToPython | /24hourto12hour.py | 1,283 | 4.5 | 4 | print("Type hours in 24-hour mode")
hours=int(input())
hoursnew=hours%12 #% - gives you the remainder. Modulus of something that is smaller will be itself e.g 11 is smaller than 12 so it will be 11
if((hours>24)|(hours<1)): # If comparing two things, put brackets around both so it does bedmas and evaluates brackets first. | = OR operator, & = AND Operator.
print("This time does not exist")
elif(hours==24): # Elif runs if if statement is false
print("Your time in 12-hour mode is:12am")
#these spaces dont have to be here
elif(hours>12):
print("Your time in 12-hour mode is:" ,hoursnew, "pm")
elif(hours==12):
print("Your time in 12-hour mode is: 12pm")
else:
print("Your time in 12-hour mode is:" ,hoursnew, "am") #else comes when none of the others apply
#You can comment out several lines of code using ''' to have your code saved for later but not run by python
'''example program '''
'''if((hours>24)| (hours<1)):
print("This does not exist")
elif((hours>12) & (hours<24)):
print("Your time in 12-hour mode is:" ,hoursnew, "pm")
elif(hours==24):
print("Your time in 12-hour mode is:12am")
elif(hours==12):
print("Your time in 12-hour mode is: 12pm")
else:
print("Your time in 12-hour mode is:" ,hoursnew, "am")'''
#this is the less complex one
| true |
bb66288e230ed522491b095ba3e344221bd27ba1 | CodeSeven-7/password_generator | /password_generator.py | 670 | 4.25 | 4 | # password_generator.py
import random
import string
print('Welcome to PASSWORD GENERATOR!')
# input the length of password
length = int(input('Enter the length of the password you would like to create: '))
# define data
num = string.digits
symbols = string.punctuation
lower = string.ascii_lowercase
upper = string.ascii_uppercase
# sum the data
all = num + symbols + lower + upper
# use random
temp = random.sample(all,length)
# create the password
password = "".join(temp)
print('Your generated password contains lowercase and uppercase letters, numbers and symbols in a random arrangement:')
print(password)
| true |
df43194f5d82d5808925736e24351938641ac355 | Juanjo-M/Primero | /Lab31112.py | 360 | 4.125 | 4 | year = int(input("Enter a year: "))
if year >= 1582:
if year % 4 != 0:
print("This is a common year.")
elif year % 100 != 0:
print("This is a leap year.")
elif year % 400 != 0:
print("This is a common year.")
else:
print("This is a leap year.")
else:
print("Not within the Gregorian calendar period") | true |
473e2eff54f1ee5faa5151c8968fab0f705b73c1 | unclebae/python_tutorials | /DataStructures/DictionariesTest.py | 2,154 | 4.34375 | 4 | # Dictionaries are sometimes found in other languages as "associative memories" or "associative arrays"
# Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys,
# which can be any immutable type;
# strings and numbers can always be keys
tel = {'jack':4098, 'sape':4139}
tel['guido'] = 4127
print(tel)
print(tel['jack'])
del tel ['sape']
tel['irv'] = 4127
print(tel)
print(list(tel.keys()))
print(tel.values())
print(list(tel.values()))
print(sorted(tel.keys()))
print('guido' in tel)
print('sape' in tel)
# The dict() constructor builds dictionaries directly from sequences of key-value pairs.
a = dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
print(a)
print({x: x**2 for x in (2, 5, 6)})
b = dict(shape=4139, guido=4127, jack=4098)
print(b)
# When looping throught dictionaries, the key and corresponding value can be retrieved at the same time using the items() method.
knights = {'gallahad':'the_pure', 'robin':'the brave'}
for k, v in knights.items():
print(k, v)
# When looping throught a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate() function.
for i, v in enumerate(['tic', 'tac', 'toe']):
print(i, v)
# To loop over two or more sequences at the same time, the entries can be paired with the zip() function.
questiongs = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']
for q, a in zip(questiongs, answers) :
print('What is your {0}? It is {1}.'.format(q, a))
# To loop over a sequence in reverse, first sepcify the sequence in a forward direction and then call the reversed() function/
for i in reversed(range(1, 10, 2)):
print(i)
# The loop over a sequence in sorted order, use the sorted() function which returns a new sorted list while leaving the source unaltered.
basket = ['apple', 'oragne', 'apple', 'pear', 'orange', 'banana']
for f in sorted(set(basket)):
print(f)
import math
raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]
filtered_data = []
for value in raw_data:
if not math.isnan(value):
filtered_data.append(value)
| true |
4598d2e50265da88fab8cfe116c5581a57816524 | nshagam/Python_Practice | /Divisors.py | 463 | 4.28125 | 4 | # Create a program that asks the user for a number and then prints out a list of all
# the divisors of that number. (If you don’t know what a divisor is, it is a number that
# divides evenly into another number. For example, 13 is a divisor of 26 because 26 / 13 has no remainder.)
num = int(input("Enter a number: "))
numrange = range(1, num + 1)
divisors = []
for i in numrange:
if num % i == 0:
divisors.append(i)
print(divisors) | true |
ed105b7cf0dbaee6468a2c8a298708a344894b08 | shanekelly/SoftDesSp15 | /toolbox/word_frequency_analysis/frequency.py | 1,568 | 4.5625 | 5 | """ Analyzes the word frequencies in a book downloaded from
Project Gutenberg """
import string
def get_word_list(file_name):
""" Reads the specified project Gutenberg book. Header comments,
punctuation, and whitespace are stripped away. The function
returns a list of the words used in the book as a list.
All words are converted to lower case.
"""
f = open(file_name,'r')
lines = f.readlines()
curr_line = 0
while lines[curr_line].find('START OF THIS PROJECT GUTENBERG EBOOK') == -1:
curr_line += 1
lines = lines[curr_line+1:]
text = ''.join(lines)
text = text.replace('\n', ' ')
words = text.split()
for x in xrange(len(words)):
words[x] = words[x].lower()
return words
def get_top_n_words(word_list, n):
""" Takes a list of words as input and returns a list of the n most frequently
occurring words ordered from most to least frequently occurring.
word_list: a list of words (assumed to all be in lower case with no
punctuation
n: the number of words to return
returns: a list of n most frequently occurring words ordered from most
frequently to least frequentlyoccurring
"""
#Create a dictionary in the format 'word':'number of times word appears'
word_counts = dict()
for word in word_list:
if word not in word_counts:
word_counts[word] = 1
else:
word_counts[word] += 1
#Sort the dictionary by number of times word appears
ordered_by_frequency = sorted(word_counts, key=word_counts.get, reverse=True)
return ordered_by_frequency[:n]
print get_top_n_words(get_word_list('MobyDick.txt'), 100) | true |
ddc7d4172e1200bef9ffa01f9b5682eab34e8be1 | bearddan2000/python-cli-pydoc-ugly-num-functional-prog | /bin/main.py | 1,323 | 4.1875 | 4 | """
Given a number find the next number
that is divides by 2, 3, or 5.
"""
def max_divide(a, b):
"""
This function divides a by greatest divisible power of b
:param a: const number 2, 3, 5
:param b: current number iteration
:return: max number 2, 3, 5
"""
if a % b != 0:
return a;
c = a/b;
return max_divide(c, b);
def is_ugly(n, args, no):
"""
Function to check if a number is ugly or not
:param n: index of const list
:param args: const list of 2,3,5
:param no: number to test
:return: is number tested ugly
"""
if n >= len(args):
return no == 1
c = max_divide(no, args[n]);
return is_ugly(n+1, args, c);
def find_ugly(n, i, count, args):
"""
Recursively iterate numbers to find first
ugly number.
:param n: number to test
:param i: index of iteration
:param count: running index of recurcion
:param args: const list of 2,3,5
:return: first ugly number found
"""
if (n < count):
return i-1
if is_ugly(0, args, i):
return find_ugly(n, i+1, count+1, args);
else:
return find_ugly(n, i+1, count, args)
def main():
i = 10
args = [2,3,5]
print( "[INPUT] %d" % i)
output = find_ugly(i, 1, 1, args)
print( "[OUTPUT] %d" % output)
main()
| true |
4bb59227eb63e743e7bd58732cbe7fcc07ae0af9 | Sarah1108/HW070172 | /hw_5/ch_7_5.py | 422 | 4.15625 | 4 | # exersice 5, chapter 7
#
def main():
weight = float(input("Enter your weight in pounds: "))
height = float(input("Enter your height in inches: "))
BMI = (weight*720)// (height**2)
if BMI < 19:
print("Your BMI", BMI, "is underweight!")
elif 19 < BMI<= 25:
print("Your BMI", BMI, "is healthy")
else:
print("Your BMI", BMI, "is above the healthy range!")
main()
| false |
aa124bfe70359c8c48a3e43d12949bc2ec18c8d0 | Sarah1108/HW070172 | /hw_5/ch_6_3.py | 475 | 4.21875 | 4 | #exercise 3
#
import math
def sphereArea(radius):
area = 4* math.pi * radius**2
return area
def sphereVolume(radius):
volume = 4/3 * math.pi* radius**3
return volume
def main():
print("This programm calculates the Volume and surface area of a sphere.")
print()
radius = int(input("Enter the radius of the sphere: "))
print("The Volume of the sphere is", sphereVolume(radius) , "and the surface area is", sphereArea(radius))
main() | true |
b362f102f6792584eb2846684668dbd4fb85fd05 | Jyoti-27/Python-4 | /Python 4.1 string.py | 1,362 | 4.3125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[2]:
string1 = "My name is Jyoti and I am working a Data Scientist"
# In[4]:
print(string1)
# In[5]:
# Converting from a string to list
list1 = string1.split()
# In[7]:
print(list1)
# In[9]:
len(list1)
# In[15]:
list1.append('DL','AI')
# In[13]:
list1.append(['DL','AI']) # append takes only one argument so when you pass a list as an argument it considers it as only one element
# In[16]:
print(list1)
# In[17]:
list1.insert(4,'Sabarad')
# In[19]:
print(list1)
# In[20]:
list1[3] = "Jyoti Sabarad"
# In[22]:
print(list1)
# In[46]:
list1.pop(2)
# In[52]:
list2 = ['A','B','C','D']
# In[54]:
print(list2.reverse())
# In[56]:
print(list2.reverse())
print(list2)
# In[65]:
list3 = ["Maharashtra","Karnataka","Goa","Rajasthan","Hariyana","Punjab"]
print(list3)
type(list3)
# In[60]:
list3 = tuple(list3) # I have converted my list to tuple using tuple function
type(list3)
# In[61]:
print(list3)
# In[63]:
list3 = list(list3) # Converting my tiple to list using list() function
type(list3)
# In[66]:
tuple1 = () # To initialize a tuple
list = [] # To Initialize a list
# In[70]:
list3 = ["Maharashtra","Karnataka","Goa","Rajasthan","Hariyana","Punjab"]
print(list3.reverse())
print(list3)
# In[71]:
list3.pop(3)
print(list3)
# In[ ]:
| false |
a56255215d64a8f5e8481ec0ab04c7132510bf0c | AayushmanJung/pythonProjectlab1 | /lab1/lab6.py | 371 | 4.34375 | 4 | '''
Solve each of the problem using Python Scripts. Make sure you use appropriate variable names and comments. When
there is a final answer have Python print it to the screen.
A person's body mass index (BMI) is defined as:
BMI = mass in kg / (height in m)**2
'''
mass= int(input('Enter the mass'))
height= int(input('Enter the height'))
bmi = mass/height**2
print(bmi)
| true |
8b4f79396bc2048b247139c8b3ced9dba4183a07 | Renan-S/How-I-Program | /Python/Curso de Python/Escopo de variaveis.py | 708 | 4.25 | 4 | """
Escopo pode ser entendido como as limitações
Dois casos de escopos de variáveis:
1- Variáveis globais <> Seu escopo compreende todo o programa
2- Variáveis locais <> Seu escopo compreende apenas no bloco onde foram declaradas
Python é de tipagem dinâmica.
A linguagem infere um tipo específico de acordo com o valor dado a variável
"""
numero_inteiro = "Quarenta e dois" #Variáveis do tipo GLOBAL
print(numero_inteiro)
print(type(numero_inteiro))
numero_inteiro = 42 #Variáveis do tipo GLOBAL
print(numero_inteiro)
print(type(numero_inteiro))
if numero_inteiro > 10:
numero_real = numero_inteiro + 3.14 #numero_real é uma Variável do tipo LOCAL
print(numero_real) | false |
4b6d2d8a1ac75450d33d15a8c93bd68e652e792b | Renan-S/How-I-Program | /Python/Curso de Python/For - Loop.py | 1,605 | 4.21875 | 4 | """
for item in interavel: (exemplo)
Os loops são para iterar sobre sequências ou valores iteráveis
Iteráveis:
1- Strings: "Renan"
2 - Lista: [1,3,5,7]
3 - Range: numeros = range [1, 10]
"""
nome = "Renan Cavalcante"
lista = [1, 3, 5, 7, 9]
numeros = range(1, 10) #É necessário transforma em lista
for letra in nome: #Iteração em String
print(letra)
for letra in nome:
print(letra, end=" ") #Elimina o /n padrão
for numero in lista: #Iteração em lista determinada
print(numero)
for numero in range(1, 11): #Iteração em escopo determinado
print(numero)
"""
((0, "R"), (1, "e"), (2, "n"), (4, "a"), (5, "n")...)
Enumera cada valor em um índice
for indice, letra in enumerate(nome):
print(nome[indice])
for indice, letra in enumerate(nome):
print(letra)
for _, letra in enumerate(nome): #O underline serve para ignorar um valor
print(letra)
"""
for valor in enumerate(nome):
print(valor)
for valor in enumerate(nome):
print(valor[0]) #Só imprime os índices
for valor in enumerate(nome):
print(valor[1]) #Só imprime os valores sem índices
quantidade = int(input("O loop vai rodar até quantos valores?\n"))
soma = 0
for numero in range(1, quantidade+1): #+1 pois o Range vai até o penúltimo item
calculo = int(input(f"Informe o {numero}/{quantidade} valor: "))
soma = soma + calculo
print(f"O valor total é: {soma}")
for numero in range(1, 11):
if numero == 6:
break
else:
print(numero)
print("Chegou no numero e saiu do loop") | false |
dfcf70c0ecbb6bc19cec52deee8c5483ecce962f | divyatejakotteti/100DaysOfCode | /Day 62/Collections.deque().py | 753 | 4.125 | 4 | '''
Task
Perform append, pop, popleft and appendleft methods on an empty deque
.
Input Format
The first line contains an integer
, the number of operations.
The next
lines contains the space separated names of methods and their values.
Constraints
Output Format
Print the space separated elements of deque
.
Sample Input
6
append 1
append 2
append 3
appendleft 4
pop
popleft
Sample Output
1 2
'''
from collections import deque
d = deque()
for i in range(int(input())):
s = input().split()
if s[0] == 'append':
d.append(s[1])
elif s[0] == 'appendleft':
d.appendleft(s[1])
elif s[0] == 'pop':
d.pop()
else:
d.popleft()
print (" ".join(d)) | true |
edc95514a21b81e5ed7c36399fb35a1b5ba666a4 | divyatejakotteti/100DaysOfCode | /Day 23/SherlockAndAnagrams.py | 1,512 | 4.21875 | 4 | '''
Two strings are anagrams of each other if the letters of one string can be rearranged to form the other string. Given a string, find the number of pairs of substrings of the string that are anagrams of each other.
For example s= mom, the list of all anagrammatic pairs is [m,m],[mo,om]at positions [[0],[2]],[[0,1],[1,2]]respectively.
Function Description
Complete the function sherlockAndAnagrams in the editor below. It must return an integer that represents the number of anagrammatic pairs of substrings in s.
sherlockAndAnagrams has the following parameter(s):
s: a string .
Input Format
The first line contains an integer q, the number of queries.
Each of the next q lines contains a string s to analyze.
Output Format
For each query, return the number of unordered anagrammatic pairs.
Sample Input
2
abba
abcd
Sample Output
4
0
'''
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the sherlockAndAnagrams function below.
def sherlockAndAnagrams(s):
l=0
for i in range(1,len(s)):
d={}
for j in range(len(s)-i+1):
string="".join(sorted(s[j:j+i]))
if string not in d:
d[string]=1
else:
d[string]+=1
l+=d[string]-1
return l
if __name__ == '__main__':
q = int(input())
for q_itr in range(q):
s = input()
result = sherlockAndAnagrams(s)
| true |
d0dab6a753a2682e9a5f4a898ca72cef7908d9b5 | divyatejakotteti/100DaysOfCode | /Day 38/FairRations.py | 2,329 | 4.15625 | 4 | '''
You are the benevolent ruler of Rankhacker Castle, and today you're distributing bread. Your subjects are in a line, and some of them already have some loaves. Times are hard and your castle's food stocks are dwindling, so you must distribute as few loaves as possible according to the following rules:
Every time you give a loaf of bread to some person
, you must also give a loaf of bread to the person immediately in front of or behind them in the line (i.e., persons or
).
After all the bread is distributed, each person must have an even number of loaves.
Given the number of loaves already held by each citizen, find and print the minimum number of loaves you must distribute to satisfy the two rules above. If this is not possible, print NO.
For example, the people in line have loaves
. We can first give a loaf to and so . Next we give a loaf to and and have which satisfies our conditions. We had to distribute
loaves.
Function Description
Complete the fairRations function in the editor below. It should return an integer that represents the minimum number of loaves required.
fairRations has the following parameter(s):
B: an array of integers that represent the number of loaves each persons starts with .
Input Format
The first line contains an integer
, the number of subjects in the bread line.
The second line contains
space-separated integers.
Output Format
Print a single integer taht denotes the minimum number of loaves that must be distributed so that every person has an even number of loaves. If it's not possible to do this, print NO.
Sample Input 0
5
2 3 4 5 6
Sample Output 0
4
'''
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the fairRations function below.
def fairRations(B):
loaves=0
for i in range(N-1):
if(B[i]%2==0):
continue
B[i]+=1
B[i+1]+=1
loaves+=2
if(B[-1]%2==1):
return("NO")
else:
return(loaves)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
N = int(input())
B = list(map(int, input().rstrip().split()))
result = fairRations(B)
fptr.write(str(result) + '\n')
fptr.close()
| true |
dc1b524bca8b58ea8c13d461eda010e45d759ba4 | divyatejakotteti/100DaysOfCode | /Day 74/CheckStrictSuperset.py | 1,057 | 4.15625 | 4 | '''
You are given a set and other sets.
Your job is to find whether set is a strict superset of each of the
sets.
Print True, if
is a strict superset of each of the
sets. Otherwise, print False.
A strict superset has at least one element that does not exist in its subset.
Example
Set
is a strict superset of set.
Set is not a strict superset of set.
Set is not a strict superset of set
.
Input Format
The first line contains the space separated elements of set
.
The second line contains integer , the number of other sets.
The next
lines contains the space separated elements of the other sets.
Constraints
Output Format
Print True if set
is a strict superset of all other
sets. Otherwise, print False.
Sample Input 0
1 2 3 4 5 6 7 8 9 10 11 12 23 45 84 78
2
1 2 3 4 5
100 11 12
Sample Output 0
False
'''
A = set(input().split())
n = int(input())
c = True
for i in range(n):
s = set(input().split())
if (s&A != s) or (s == A):
c = False
break
print(c) | true |
2f8d24b3f1bea47e316b56a6484a82888b9c80ab | divyatejakotteti/100DaysOfCode | /Day 60/WordOrder.py | 1,079 | 4.125 | 4 | '''
You are given
words. Some words may repeat. For each word, output its number of occurrences. The output order should correspond with the input order of appearance of the word. See the sample input/output for clarification.
Note: Each input line ends with a "\n" character.
Constraints:
The sum of the lengths of all the words do not exceed
All the words are composed of lowercase English letters only.
Input Format
The first line contains the integer,
.
The next
lines each contain a word.
Output Format
Output
lines.
On the first line, output the number of distinct words from the input.
On the second line, output the number of occurrences for each distinct word according to their appearance in the input.
Sample Input
4
bcdef
abcdefg
bcde
bcdef
Sample Output
3
2 1 1
'''
import collections
N = int(input())
d = collections.OrderedDict()
for i in range(N):
word = input()
if word in d:
d[word] +=1
else:
d[word] = 1
print(len(d))
for k,v in d.items():
print(v,end=' ') | true |
f574490c0c3e9924c031d262b6d43440d5ad5552 | divyatejakotteti/100DaysOfCode | /Day 25/SequenceEquation.py | 917 | 4.15625 | 4 | '''
Given a sequence of integers, where each element is distinct and satisfies . For each x where 1<=x<n, find any integer y such that p(p(y))=x and print the value of y on a new line.
Function Description
Complete the permutationEquation function in the editor below. It should return an array of integers that represent the values of
.
permutationEquation has the following parameter(s):
p: an array of integers
Input Format
The first line contains an integer
, the number of elements in the sequence.
The second line contains space-separated integers where .
'''
#!/bin/python3
import math
import os
import random
import re
import sys
def permutationEquation(p):
print((p.index(p.index(x+1)+1)+1)for x in range(n))
if __name__ == '__main__':
n = int(input())
p = list(map(int, input().rstrip().split()))
permutationEquation(p)
| true |
2a88f0aa503ceb61fcd07144fdd10e2562c32b62 | divyatejakotteti/100DaysOfCode | /Day 37/FlatlandSpaceStations.py | 1,718 | 4.5 | 4 | '''
Flatland is a country with a number of cities, some of which have space stations. Cities are numbered consecutively and each has a road of
length connecting it to the next city. It is not a circular route, so the first city doesn't connect with the last city. Determine the maximum distance from any city to it's nearest space station.
For example, there are
cities and of them has a space station, city . They occur consecutively along a route. City is unit away and city is units away. City is units from its nearest space station as one is located there. The maximum distance is
.
Function Description
Complete the flatlandSpaceStations function in the editor below. It should return an integer that represents the maximum distance any city is from a space station.
flatlandSpaceStations has the following parameter(s):
n: the number of cities
c: an integer array that contains the indices of cities with a space station,
-based indexing
Input Format
The first line consists of two space-separated integers,
and .
The second line contains
space-separated integers, the indices of each city having a space-station. These values are unordered and unique.
There will be at least
city with a space station.
No city has more than one space station.
Output Format
Print an integer denoting the maximum distance that an astronaut in a Flatland city would need to travel to reach the nearest space station.
Sample Input 0
5 2
0 4
Sample Output 0
2
'''
n,m=(int,input().split())
c=sorted(map(int,input().strip.split())
m=max(n-c[-1]-1,c[0])
for i in range(1,len(c)):
d=math.floor((c[i]-c[i-1])/2)
if(d>m):
m=d
print(m) | true |
b6be72984e340456b8f87b4ddd8ec845a21fc938 | divyatejakotteti/100DaysOfCode | /Day 27/SherlockAndSquares.py | 1,206 | 4.46875 | 4 | '''
Watson likes to challenge Sherlock's math ability. He will provide a starting and ending value describing a range of integers. Sherlock must determine the number of square integers within that range, inclusive of the endpoints.
Function Description
Complete the squares function in the editor below. It should return an integer representing the number of square integers in the inclusive range from
to
.
squares has the following parameter(s):
a: an integer, the lower range boundary
b: an integer, the uppere range boundary
Input Format
The first line contains q, the number of test cases.
Output Format
For each test case, print the number of square integers in the range on a new line.
Sample Input
2
3 9
17 24
Sample Output
2
'''
#!/bin/python3
import math
import os
import random
import re
import sys
def squares(a, b):
sqrtA = math.ceil(math.sqrt(a))
sqrtB = math.floor(math.sqrt(b))
return(sqrtB - sqrtA + 1)
if __name__ == '__main__':
q = int(input())
for q_itr in range(q):
ab = input().split()
a = int(ab[0])
b = int(ab[1])
result = squares(a, b)
| true |
3a054171a05293d817336dc7b56af7ab7421fcb3 | divyatejakotteti/100DaysOfCode | /Day 25/BeautifulDays_at_theMovies.py | 1,733 | 4.4375 | 4 | '''
Lily likes to play games with integers. She has created a new game where she determines the difference between a number and its reverse. For instance, given the number 12, its reverse is 21. Their difference is 9. The number 120reversed is 21, and their difference is 99.
She decides to apply her game to decision making. She will look at a numbered range of days and will only go to a movie on a beautiful day.
Given a range of numbered days,|i....j| and a number k, determine the number of days in the range that are beautiful. Beautiful numbers are defined as numbers where |i-reverse(i)|is evenly divisible by k. If a day's value is a beautiful number, it is a beautiful day. Print the number of beautiful days in the range.
Function Description
Complete the beautifulDays function in the editor below. It must return the number of beautiful days in the range.
beautifulDays has the following parameter(s):
i: the starting day number
j: the ending day number
k: the divisor
Input Format
A single line of three space-separated integers describing the respective values of i, j, and k.
Output Format
Print the number of beautiful days in the inclusive range between i and j.
Sample Input
20 23 6
Sample Output
2
'''
#!/bin/python3
import math
import os
import random
import re
import sys
def beautifulDays(i, j, k):
count=0
for i in range(i,j+1):
a=str(i)
b=a[::-1]
c=abs(int(i)-int(b))%k
if(c==0):
count+=1
return(count)
if __name__ == '__main__':
ijk = input().split()
i = int(ijk[0])
j = int(ijk[1])
k = int(ijk[2])
result = beautifulDays(i, j, k) | true |
339c11950657fd59e71804f3a54b0f548642c627 | divyatejakotteti/100DaysOfCode | /Day 48/StrongPassword.py | 2,194 | 4.15625 | 4 | '''
Louise joined a social networking site to stay in touch with her friends. The signup page required her to input a name and a password. However, the password must be strong. The website considers a password to be strong if it satisfies the following criteria:
Its length is at least
.
It contains at least one digit.
It contains at least one lowercase English character.
It contains at least one uppercase English character.
It contains at least one special character. The special characters are: !@#$%^&*()-+
She typed a random string of length
in the password field but wasn't sure if it was strong. Given the string she typed, can you find the minimum number of characters she must add to make her password strong?
Note: Here's the set of types of characters in a form you can paste in your solution:
numbers = "0123456789"
lower_case = "abcdefghijklmnopqrstuvwxyz"
upper_case = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
special_characters = "!@#$%^&*()-+"
Input Format
The first line contains an integer
denoting the length of the string.
The second line contains a string consisting of
characters, the password typed by Louise. Each character is either a lowercase/uppercase English alphabet, a digit, or a special character.
Constraints
Output Format
Print a single line containing a single integer denoting the answer to the problem.
Sample Input 0
3
Ab1
Sample Output 0
3
'''
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the minimumNumber function below.
def minimumNumber(n, password):
count = 0
if any(i.isdigit() for i in password)==False:
count+=1
if any(i.islower() for i in password)==False:
count+=1
if any(i.isupper() for i in password)==False:
count+=1
if any(i in '!@#$%^&*()-+' for i in password)==False:
count+=1
return max(count,6-n)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
password = input()
answer = minimumNumber(n, password)
fptr.write(str(answer) + '\n')
fptr.close()
| true |
eb5770b15ba0e06dbff9cb5e9f4ac1b4aaca1453 | divyatejakotteti/100DaysOfCode | /Day 06/SocksMerchant.py | 1,064 | 4.5625 | 5 | '''
John works at a clothing store. He has a large pile of socks that he must pair by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are.
For example, there are n=7 socks with colors ar=[1,2,1,2,1,3,2]. There is one pair of color 1 and one of color 2. There are three odd socks left, one of each color. The number of pairs is 2.
Function Description:
Complete the sockMerchant function in the editor below. It must return an integer representing the number of matching pairs of socks that are available.
sockMerchant has the following parameter(s):
n: the number of socks in the pile
ar: the colors of each sock
Input Format:
The first line contains an integer n, the number of socks represented in ar.
The second line contains space-separated integers describing the colors ar[i] of the socks in the pile.
'''
#Code:
n=input()
socks=input().strip().split()
pair=0
for i in set(socks):
pair=pair+socks.count(i)//2
print(pair)
| true |
fa6737f47bf7733838a05784d3da6a97ff8835ff | Saltyn1/tasks_db | /OOP.Encapsulation.py | 2,376 | 4.1875 | 4 | """
1)Создайте класс и объявите в нём 3 метода: публичный, защищённый и приватный. Затем создайте экземпляр данного класса и вызовите по очереди каждый из методов.
"""
class Website:
def to_open(self):
return 'www.google.com'
def _get_email (self):
return "Limited access"
def __get_email(self):
return "Error"
website = Website()
print(website.to_open())
print(website._get_email())
print(website.__get_email())
"""
2)Определите класс A, в нём объявите метод method1, который печатает строку "Hello World". Затем создайте класс B, который будет наследоваться от класса A. Создайте экземпляр от класса B, и через него вызовите метод method1.
"""
class A:
def method1(self):
print('Hello World')
class B(A):
pass
b = B()
b.method1()
"""
3)Объявите класс Car, в котором будет приватный атрибут экземпляра speed. Затем определите метод set_speed, который будет устанавливать значение скорости и метод show_speed, с помощью которого Вы будете получать значение скорости.
"""
class Car:
__speed = 50
def set_speed(self, value):
self.__speed = value
def show_speed(self):
return self.__speed
car = Car()
print(car.show_speed())
"""
4)Перепишите класс Car из предыдущего задания.
Перепишите метод set_speed() с использование декоратора @speed.setter, а метод show_speed() с использованием декоратора @property, для того чтобы можно было работать с данным классом следующим образом:
car = Car()
car.speed = 120
print(car.speed)
"""
class Car:
__speed = 50
@property
def speed(self):
return self.__speed
@speed.setter
def speed(self, value):
self.__speed = value
car = Car()
car.speed = 120
print(car.speed) | false |
606334ca145a342d401e35dc271d7d0ee5080fab | joehammahz808/CS50 | /pset6/mario/mario.py | 789 | 4.125 | 4 | # Ruchella Kock
# 12460796
# this program will take a given height and print a pyramid with two spaces in between
from cs50 import get_int
# prompt user for positive integer
while True:
height = get_int("height: ")
if height > 23 or height < 0:
continue
else:
break
# do this height times
for x in range(height):
# calculate the number of spaces
number_of_spaces = height - (x + 1)
for y in range(number_of_spaces):
print(" ", end="")
# calculate the number of #'s
hashtag = 1 + x
for y in range(hashtag):
print("#", end="")
# print two spaces in between
print(" ", end="")
# print the other hashes
for y in range(hashtag):
print("#", end="")
# make a space to go to the next line
print() | true |
110737c9958d67282c27f00c82543f97723bbf06 | bpatgithub/hacker | /python/objectPlay/Inheritance.py | 1,495 | 4.53125 | 5 | # Understanding inheritance.
#
class PartyAnimal:
# this class has two local data store x and name.
x = 0
name = ""
# now lets define constructor.
# Constructor is optional. Complier will perform that operation by itself if you don't.
# all methods with __ are special.
# self is just the point to the instant of the object. That's always the first argument and it is optional.
# you will see that I am constructed is displayed as soon as we execute the program.
def __init__(self, nm):
self.name = nm
print "I am constructed ", self.name
def party(self):
self.x = self.x + 1
print "So far ", self.x, "for", self.name
#Destructor are optional too just like constructor.
# you will see that when program ends, it will display I am destructed.
def __del__(self):
print "I am destructed"
# Now lets create subclass which inherits from PartyAnimal.
class FootballFan(PartyAnimal):
# this subclass has its own local data store for points.
points = 0
# this subclass also has its own local method, which is more stuff than parent class.
def touchdown(self):
self.points += 7
print self.name, "has points ", self.points
# Now main block of the function.
# Create the class, just like calling function.
# This will now create an object and assigned to variable to s and another to j.
s = PartyAnimal("Sally")
s.party()
j = FootballFan("Jim")
j.party()
j.touchdown()
| true |
3c6ee85b82e2410032e6f5be4c6d9750b59977e4 | bpatgithub/hacker | /machineLearning/mapReduce/asymmetricFriends/mr_asymmetric_friends.py | 1,780 | 4.21875 | 4 | '''
Find all Asymmetric relationship in a friend circle.
The relationship "friend" is often symmetric, meaning that if I am your friend,
you are my friend. MapReduce algorithm to check whether this property
holds. It will generate a list of all non-symmetric friend relationships.
Map Input
Each input record is a 2 element list [personA, personB] where personA is a
string representing the name of a person and personB is a string representing
the name of one of personA's friends. Note that it may or may not be the case
that the personA is a friend of personB.
Reduce Output
The output should be all pairs (friend, person) such that (person, friend)
appears in the dataset but (friend, person) does not.
author: bhavesh patel
'''
import mro_asymmetric_friends as mr
import sys
import json
# Part 1
# create map reduce object.
mro = mr.MapReduce()
# Part 2
# Mapper: tokenizes each doc and emits key-value pair.
def mapper(record):
mro.emit_intermediate(record[0], record[1])
# Part 3
# Reducer: Sums up the list of occurrence counts and emits a count for word.
def reducer(key, list_of_values):
# first let's create list of all names.
list = []
opp_friend_list = None
for friend in list_of_values:
#if my friend has a list, check to see if I am in his friend list.
flist = mro.intermediate.get(friend, None)
if flist == None: # My friend has no friends!
mro.emit([friend, key])
mro.emit([key, friend])
else: # my friend has friends.
# Am I in his list?
if key not in flist:
mro.emit([friend,key])
mro.emit([key, friend])
# Part 4
# Load data and executes mr (map reduce).
inputdata = open(sys.argv[1])
mro.execute(inputdata, mapper, reducer)
| true |
e6d33a819da979fb63e086bbad1d7309e71f9954 | gcpdeepesh/harshis-python-code | /Can You Drive Now !.py | 303 | 4.15625 | 4 | driving_age = eval(input("What is the legal driving age in your area ? "))
your_age = eval(input("What is your age ? "))
if your_age >= driving_age :
print ("You are old enough to drive legally")
if your_age < driving_age :
print ("Sorry you can drive" , driving_age - your_age, "years later.")
| false |
d22875a8da5a677f6008db9705f6ae097a1abafc | joker2013/education | /Python/Lesson-7-List1.py | 1,003 | 4.21875 | 4 |
cities = ['New York', 'Moscow', 'new dehli', 'Simferopol', 'Toronto']
print(cities)
# Колличество в массиве
print(len(cities))
# Выбор из массива
print(cities[0])
# Первый с канца
print(cities[-1])
print(cities[2].upper())
# замена в массиве
cities[2] = 'Tula'
print(cities)
# Добавление в массив
cities.append('Kursk')
cities.append('Yalta')
print(cities)
# Добавление в нужное место
cities.insert(1, 'Feodosiya')
print(cities)
# Стирание из массива
del cities[-1]
print(cities)
# Стирание из массива по названию
# cities.remove('Tule')
# print(cities)
# Обрезает последний символ
deleted_city = cities.pop()
print("Deleted city is: " + deleted_city)
print(cities)
# Сортировка
cities.sort()
print(cities)
# Сортировка наоборот
cities.sort(reverse=True)
print(cities)
cities.reverse()
print(cities)
| false |
a8bd48aeefb58ed69fd609ffa55c27bb32aa048f | borko81/SU_OOP_2021 | /Iterators_generators/fibo_gen.py | 256 | 4.21875 | 4 | def fibonacci():
previous = 0
current = 1
while True:
yield previous
previous, current = current, current + previous
if __name__ == '__main__':
generator = fibonacci()
for i in range(5):
print(next(generator))
| true |
b3080e1275ecd99a94af2492bfe5ed5894b48fc8 | likair/python-programming-course-assignments | /Assignment3_4.py | 773 | 4.15625 | 4 | '''
Created on 15.5.2015
A program, which finds all the indexes of word 'flower' in the following text:
"A flower is a beautiful plant, which can be planted in the garden or used to decorate
home. One might like a flower for its colors and the other might like a flower for its
smell. A flower typically symbolizes soft feelings".
@author: e1201757
'''
text = 'A flower is a beautiful plant, which can be planted in the garden or used to decorate home. One might like a flower for its colors and the other might like a flower for its smell. A flower typically symbolizes soft feelings'
index = 0
while index < len(text):
index = text.find('flower', index)
if index == -1:
break
print(index)
index += 6
| true |
b6184226d54b6c62649165d0c0cfec0eec104e2a | TimJJTing/test-for-gilacloud | /part1_multiples.py | 703 | 4.3125 | 4 | # part1_multiples.py
# If we list all the natural numbers below 10 that
# are multiples of 3 or 5, we get 3, 5, 6 and 9.
# The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
def find_multiples_of_3_or_5(below):
# ans = []
# multiples of 3
# n = 0
# while 3*n < below:
# ans.append(3*n)
# n += 1
# multiples of 5
# n = 0
# while 5*n < below:
# # if n is not a multiple of 3, 5*n won't be.
# if n%3 != 0:
# ans.append(5*n)
# n += 1
# return ans
mult = [i for i in range(below) if i % 3 == 0 or i % 5 == 0]
return mult
print(sum(find_multiples_of_3_or_5(1000)))
| true |
5b7d0e84fc7c0aa52dc3717ec492fab1f5772bee | aarthymurugappan101/if-else-elif-python1 | /L3_2_elif.py | 308 | 4.125 | 4 | mark = input("Enter your mark in the test -> ")
print ("\nYou have entered" , mark , "marks")
marks = int(mark)
grade = "F"
if marks >= 80:
grade = "A"
elif marks >= 70:
grade = "B"
elif marks >= 60:
grade = "C"
elif marks >= 50:
grade = "D"
# else
# grade = "F"
print ("Your grade is " + grade)
| false |
6b42ee24ea21731d01da1b487f3f5374671a766d | xiangchan/python_study | /2.list_dict_tuple_set/1.tuple.py | 485 | 4.15625 | 4 | # filename: tuple.py
tuple01 = (1, 2, 3, 4, 5, 6, 7, 8)
print(tuple01, type(tuple01))
tuple02 = (1, 2, 3, [], 9, 6)
print(tuple02)
tuple02[3].append(1)
print(tuple02)
# tuple02[3] = [1, 2, 3, 4, 5, 6]
# print(tuple02)
for i in range(2,11):
tuple02[3].append(i)
print(tuple02)
# get list[index=4].
# a = tuple02[3]
# print(a)
# print(a[4])
print(tuple02[3][4])
tuple03 = (2, 30) #130
tuple04 = (2, 20) #220
if tuple03 > tuple04:
print("t3 > t4")
else:
print("t3 < t4") | false |
16374e3c97e3fee9c378a3e2ba0ab955b2fc9188 | implse/Code_Challenges | /Random/flatten_nested_dictionary.py | 922 | 4.375 | 4 | # Write a function to flatten a nested dictionary. Namespace the keys with a period.
#
# For example, given the following dictionary:
#
# {
# "key": 3,
# "foo": {
# "a": 5,
# "bar": {
# "baz": 8
# }
# }
# }
#
# it should become:
#
# {
# "key": 3,
# "foo.a": 5,
# "foo.bar.baz": 8
# }
#
# You can assume keys do not contain dots in them, i.e. bo clobbering will occur.
def flatten_dict(d):
def expand(key, value):
if isinstance(value, dict):
return [ (key + '.' + k, v) for k, v in flatten_dict(value).items() ]
else:
return [ (key, value) ]
items = [ item for k, v in d.items() for item in expand(k, v) ]
return dict(items)
# Test
foo_bar = {
"key": 3,
"foo": {
"a": 5,
"bar": {
"baz": 8
}
}
}
print(flatten_dict(foo_bar))
| false |
f9db575371ab34db729a931c0db269a8ae17e041 | wildflower-42/FLVS-Foundations-of-Programing | /FavoriteColoursProgram.py | 1,710 | 4.375 | 4 | #Alaska Miller
#6/23/2020
#The Perpouse of this program is to prompt the human end user to input a series of questions that will have them rank their favorite colours, then the program will match them against MY previously listed into the program, favorite colours!
def favoritesCompare():
#This section of code creates the nessecary variables and lists to preform the functions of the program:
myFavoriteColours = ["blue","pink","red","black","white"] #This is the List of my favorite colours
numOfColours = len(myFavoriteColours) #This variable tells us how many colours are in the previous list "myFavoriteColours"
yourFavoriteColours = [] #This list is blank and is used to be a blank target for the "xyz.appened", so we can pogressively create a list and check it against the "myFavoriteColours" list
#This section of code is a loop that prompts the human end user to input their favorite colours into a series of promts, ranking them:
for n in range(0,numOfColours):
humanListNum = int(n)+int(1)
inputColours = input(str("please enter your #")+str(humanListNum)+str(" favorite colour:"))
yourFavoriteColours.append(inputColours)
#This section of code is a loop that checks the user input against the existing list "myFavoriteColours", and then uses an "if-else" statement to detirmine what it's response should be, then lists the responses:
for n in range(0,numOfColours):
if myFavoriteColours[n] == yourFavoriteColours[n]:
print("Your #"+str(n+1)+" favorite colour is: "+str(yourFavoriteColours[n])+", Mine is too!")
else:
print("Your #"+str(n+1)+" favorite colour is: "+str(yourFavoriteColours[n])+", but mine is: "+str(myFavoriteColours[n]))
favoritesCompare()
| true |
ea3ee2d7d504aa666b0c6823f27359135482ec0e | jeffdeng1314/CS16x | /cs160_series/python_cs1/labs/lab2/again.py | 261 | 4.28125 | 4 | x = input("Give me a positive number that is less than 256\n")
try:
x = int()
if x > 256 or x <0:
print('error')
else:
while (x > 0):
print(int(x%2))
x=x//2
except ValueError:
print('bad input')
| true |
f3ebdc3e84c3eaf396fccbe1d32eef39b1eb97e0 | sarcasm-lgtm/Python-Learning | /Printing Arrays Homework Assignment.py | 616 | 4.3125 | 4 | #I tried doing it, but it said this:
#['Ahana', 'is', 'my', 'sister']
#Traceback (most recent call last):
#File "/Users/aarohi/Documents/Printing Arrays Homework Assignment.py", line 4, in <module>
#v=ahana
#NameError: name 'ahana' is not defined
array1=["Ahana","is","my","sister"]
print(array1)
v="Ahana "
q="is "
t="my "
s="sister"
print(v + q + t + s + ". Noice, right?")
#This is some code that I got from a website
arr = [2,4,5,7,9]
print("The Array is : ")
for i in arr:
print(i, end = ' ')
arr2 = ["Ahana","is","my","sister"]
print("The Array is : ")
for i in arr:
print(i, end = ' ')
| true |
2d16bb6cf202fdccdee2c8e1b679173b652fb48c | armstrong019/coding_n_project | /Jiuzhang_practice/implement_trie.py | 2,083 | 4.25 | 4 | class TrieNode():
def __init__(self):
self.children = {}
self.is_word = False
class Trie(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def insert(self, word):
"""
Inserts a word into the trie.
:type word: str
:rtype: None
"""
root = self.root
for w in word:
if w not in root.children:
root.children[w] = TrieNode()
root = root.children[w] # iterate on root
else:
root = root.children[w]
root.is_word = True
def search(self, word):
"""
Returns if the word is in the trie.
:type word: str
:rtype: bool
"""
root = self.root
for w in word:
print(w)
if w not in root.children:
return False
else:
root = root.children[w]
if root.is_word:
return True
else:
return False
def startsWith(self, prefix):
"""
Returns if there is any word in the trie that starts with the given prefix.
:type prefix: str
:rtype: bool
"""
root = self.root
for w in prefix:
if w not in root.children:
return False
else:
root = root.children[w]
return True
# Your Trie object will be instantiated and called as such:
obj = Trie()
obj.insert('apple')
param_2 = obj.search('apple')
print(param_2)
print('a' in obj.root.children)
# Trie Node has two attributes
#1. children: initially is empty dict, as we insert, this became a dictionary with child name: child TireNode object
# 名字和名字对应的那个Node, dictionary 这个structure比较好理解, 主要是找对应关系
# 那么为什么需要node? 因为我们需要封装, 否则关系混乱
#2. is_word: whether at the level all the node above form a word. Initally is False
| true |
5ebd4360a8efde45eb3803b5e0adffea32030691 | Abhishek19009/Algorithms_and_Data_structures | /Common_Algorithms/String_splitting.py | 649 | 4.5 | 4 | # String splitting algorithm is basic but will be used multiple times so know how to create it
# String splitter will split the string into list based on the special character
def string_splitter(string, replace):
string_temp = ""
string_list = []
for char in string:
if char != replace:
string_temp += char
else:
string_list.append(string_temp)
string_temp = ""
string_list.append(string_temp)
return string_list
def main():
string = input("Enter the string: ")
split_list = string_splitter(string, " ")
print(split_list)
if __name__ == "__main__":
main() | true |
981f67ed61c882fff9322d9538615cbde8a99a68 | Abhishek19009/Algorithms_and_Data_structures | /Miscellaneous/Swap_quickly.py | 320 | 4.25 | 4 | '''
Python has a very cool and short codeline to swap elements without using any temporary variable.
'''
arr = [3,4,5,6,9,1]
arr[2],arr[3] = arr[3],arr[2] # swap element at 3 index with element at 2 index
'''
This is much shorter than creating temp variable to store 3 element and then assigning it to 2 element.
''' | true |
ce648722f6691b0801d22da61026fe3b8f1e04d3 | Abhishek19009/Algorithms_and_Data_structures | /Data Structures/Hashing/Hashing_with_chaining.py | 419 | 4.125 | 4 | '''
Usually hashing creates problem of multiple elements belonging to same hash.
To accommodate this we can store such elements in some data structure like list.
'''
# Consider the hash function f(n) = n mod 7 where n is the element of the list.
arr = [15, 47, 23, 34, 85, 97, 56, 89, 70]
# Creating 7 empty buckets
buckets = [[] for _ in range(7)]
for elem in arr:
buckets[elem%7].append(elem)
print(buckets) | true |
4e293ceb648bf422376f5deb5386b8923ef5ad57 | Abhishek19009/Algorithms_and_Data_structures | /Common_Algorithms/Graph/Dijkstra_shortest_path.py | 1,956 | 4.1875 | 4 | # Implementing Dijkstra
# Not working, fix the bug
import heapq as hp
class Node:
def __init__(self, index, distance): # We can also add extra properties of the node.
self.index = index
self.distance = distance
class Graph:
def __init__(self, n): # n == no of nodes
self.n = n
self.adj = [[] for _ in range(n)]
self.visited = [0 for _ in range(n)]
self.nodeList = [None for _ in range(n)]
self.pq = []
def nodeInit(self, node):
# Initialize the nodes in Graph
# The distance is what we need to update. The shortest path to reach Node(6) would be corresponding distance.
self.nodeList[node.index] = node
def addEdge(self, u, v, path_cost): # u, v corresponds to node index NOT distances!!
self.adj[u].append((v, path_cost))
def dijkstra(self, start, dest):
hp.heappush(self.pq, (self.nodeList[start].distance, start, 0))
self.visited[start] = 1
cur = (0, start, 0)
while self.pq:
print(cur)
if cur[1] == dest:
break
prev_distance = cur[0]
for neighbour in self.adj[cur[1]]:
if not self.visited[neighbour[0]]:
hp.heappush(self.pq, (self.nodeList[neighbour[0]].distance, neighbour[0], neighbour[1]))
# neighbour[0] = index, neighbour[1] = path_cost
self.visited[neighbour[0]] = 1
cur = hp.heappop(self.pq)
if prev_distance + cur[2] < cur[0]:
self.nodeList[cur[1]].distance = prev_distance + cur[2]
return self.nodeList[cur[1]].distance
if __name__ == "__main__":
g = Graph(7)
g.addEdge(0, 1, 2)
g.addEdge(0, 2, 3)
g.addEdge(1, 3, 4)
g.addEdge(2, 4, 9)
g.addEdge(3, 4, 8)
g.addEdge(3, 5, 3)
g.addEdge(4, 6, 7)
g.nodeInit(Node(0, 0))
g.nodeInit(Node(1, 2))
g.nodeInit(Node(2, 3))
g.nodeInit(Node(3, float("Inf")))
g.nodeInit(Node(4, float("Inf")))
g.nodeInit(Node(5, float("Inf")))
g.nodeInit(Node(6, float("Inf")))
print(g.dijkstra(0, 6))
| true |
a06859bddd8042dcc1e5775a9ae0406b62c70ad6 | NikolaosPanagiotopoulos/PythonLab | /lectures/source/lecture_04/lecture_04_exercise_2a.py | 1,125 | 4.1875 | 4 | """Άσκηση 2 – Lectures 4
Ένας φοιτητής ζήτησε από τους γονείς του να αγοράσει έναν H/Y
αξίας 3000€. Οι γονείς του συµφώνησαν να του δώσουν τα χρήµατα
µε τον εξής τρόπο: Την πρώτη εβδοµάδα θα του δώσουν 20€. Στο
τέλος κάθε εβδοµάδας θα του δίνουνε τα διπλάσια από αυτά που
του δώσανε την προηγούµενη εβδοµάδα µέχρι να συγκεντρωθεί το
ποσό που χρειάζεται.
Να γίνει πρόγραµµα σε Python το οποίο θα υπολογίζει και θα
εµφανίζει τον αριθµό των εβδοµάδων που χρειάστηκε ο φοιτητής
να πάρει τον Η/Υ καθώς και το πόσο που περισσεύει (αν περισσεύει).
"""
# Το πρόγραμμα δεν έχει τελειώσει ακόμα!
money = 20
weeks = 0
i = 0
while money <= 3000:
money = 2 * money
i += 1
print(i)
| false |
880ad96ee77a46f04c81562aa4b415f56841ce5a | harshitakumbar/pythonlabprogramme | /put.py | 216 | 4.25 | 4 | num1=3
num2=4
num3=5
if (num1>=num2) and (num2>=num3):
largest=num1
elif (num2>=num1) and (num2>=num3):
largest=num2
else:
largest=num3
print("the largest number between",num1,",",num2,"and",num3,"is",largest) | false |
c8e4f3f3e64aa94661dd075f670798a7121ad2b4 | andrewhml/dev-sprint2 | /chap6.py | 2,024 | 4.1875 | 4 | # Enter your answrs for chapter 6 here
# Name:Andrew Lee
import math
# Ex. 6.3
def area (radius):
temp = math.pi * pow(int(radius), 2)
return temp
def distance(x1, y1, x2, y2):
dx = x2-x1
dy = y2-y1
dsquared = pow(dx, 2) + pow(dy, 2)
d = math.sqrt(dsquared)
return d
def circle_area(xc, yc, xp, yp):
radius = distance(xc, yc, xp, yp)
result = area(radius)
print result
return result
#circle_area(1, 2, 4, 6)
def is_divisible(x, y):
if x % y == 0:
return True
else:
return False
def is_divisible(x, y):
return x % y == 0
#is_divisible(6, 4)
def is_between(x, y, z):
if x <= y and y <= z:
return True
else:
return False
def factorial(n):
if not isinstance(n, int):
print 'Factorial is only defined for integers.'
return None
elif n < 0:
print 'Factorial is not defined for negative integers.'
return None
elif n == 0:
return 1
else:
recurse = factorial(n-1)
result = n * recurse
return result
# Ex. 6.6
def first(word):
return word[0]
def last(word):
return word[-1]
def middle(word):
return word[1: -1]
# Wrong answer still need help understanding where this goes wrong.
#def is_palindrome(word):
# n = len(word)
# if middle(word) == '':
# return None
# elif word[0] == word[n-1]:
# word = middle(word)
# is_palindrome(word)
# result = True
# return result
# else:
# result = False
# return result
def is_palindrome(word):
if len(word) <= 1:
return True
if first(word) != last(word):
return False
return is_palindrome(middle(word))
#print is_palindrome('moooooooiooom')
#print is_palindrome('noon')
#print is_palindrome('racecar')
# Ex 6.7
def is_power(a,b):
if a%b == 0:
if a/b == 1:
return True
else:
c = a/b
return is_power(c, b)
else:
return False
#print is_power(27, 3)
# Ex 6.8
def gcd(a,b):
if a > b:
if a%b == 0:
return b
if a%b != 0:
return gcd(b,a%b)
if b > a:
if b%a == 0:
return a
if b%a != 0:
return gcd(a,b%a)
print gcd(1071, 462)
print gcd(234, 3009)
print gcd(200, 1000)
| false |
584652ea2632671d89e0d6228c44b05518cc1856 | antoniotorresz/python | /py/Logical/reverse_string.py | 285 | 4.28125 | 4 | def get_reverse(base_string):
base_list = list(base_string)
reverse = ""
for i in range(len(base_list)):
reverse += base_list[(len(base_list) - 1) - i]
return reverse
word = input("Enter a word to get its reverse: ")
print(word + " -> " + get_reverse(word)) | false |
0bf431af9180d8e61c6d6ef1bd95d453d72d9a82 | antoniotorresz/python | /py/Logical/factorial_number.py | 324 | 4.375 | 4 | #Recursive function to calculate factorial froma given number
def get_factorial(number):
if not number == 0 or number == 1:
return (get_factorial(number - 1) * number)
else:
return 1
x = int(input("Please, type a number to calculate its factorial: "))
print(str(x) + "! = " + str(get_factorial(x)))
| true |
dff935b5eff8e09fac2d299613963670a8eb8511 | BenjiYang/python-foundation | /day4/4-2-oop2.py | 924 | 4.1875 | 4 | # 类 模板
class People:
# 对象可以强行增加类没有的属性 - 非常容易被增加属性对象,灵活性,但涉及安全问题
# __slots__: 限制属性,对象不可另外增加其他属性
__slots__ = {"name", "age", "weight"}
# __init__: __特殊方法__,用于对象初始化:
# self 相当于自身,java的this
def __init__(self, name, age, weight):
self.name = name
self.age = age
self.weight = weight
def work(self):
print("%s正在努力工作" % self.name)
def get_name(self):
return self.__name
def set_name(self, new_name):
self.__name = new_name
# 基于类创建对象
p1 = People(name="Annie", age=25, weight=90)
# 类似java的toString()打印出所有对象属性
print(p1.get_name)
# print(p1.__dict__)
p2 = People(name="SlotCase", age=20, weight=80)
p2.newField = '2'
print(p2.__dict__)
| false |
5a7b7cfe9cef4d67c8942b549b604ce77f2b7dd0 | rusalinastaneva/Python-Advanced | /07. Error handling/01. Numbers Dictionary.py | 1,039 | 4.3125 | 4 | numbers_dictionary = {}
line = input()
class IsNotNumberStringError(Exception):
"""Raised when the value is a digit"""
pass
while line != "Search":
try:
number_as_string = line
if number_as_string.isdigit():
raise IsNotNumberStringError("Input must be a string")
number = int(input())
numbers_dictionary[number_as_string] = number
except ValueError:
print("The variable number must be an integer")
except IsNotNumberStringError as error:
print(error)
finally:
line = input()
line = input()
while line != "Remove":
searched = line
try:
print(numbers_dictionary[searched])
except KeyError:
print("Number does not exist in dictionary")
finally:
line = input()
line = input()
while line != "End":
searched = line
try:
del numbers_dictionary[searched]
except KeyError:
print("Number does not exist in dictionary")
finally:
line = input()
print(numbers_dictionary)
| true |
36ba2d301680a56b5d556eef7a3cd7865a9aee4f | rusalinastaneva/Python-Advanced | /05. Functions advanced/Lab_ 07. Operate.py | 807 | 4.15625 | 4 | def operate(operator, *args):
result = 0
if operator == '*' or operator == '/':
result = 1
for num in args:
if operator == '+':
result += num
elif operator == '-':
result -= num
elif operator == '*':
result *= num
elif operator == '/':
result /= num
return result
# import operator
# def operate(sign, *args):
# operations = {
# "+": operator.add,
# "-": operator.sub,
# "*": operator.mul,
# "/": operator.truediv,
# }
# result = args[0]
# for x in args[1:]:
# result = operations[sign](result, x)
# return result
#
# print(operate("-", 10, 2, 1.1))
# print(operate("+", 0))
# print(operate("*", 3, 2, 10, 8))
# print(operate("/", 10, 2, 5))
| false |
50d80a5a2e60d98d760fe151f6a7772e8446069e | imarkofu/PythonDemo | /Demo/day04.py | 2,870 | 4.3125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 可变参数
# 但是调用的时候,需要先组装出一个list或tuple:
def calc(numbers):
sum = 0
for n in numbers:
sum += n * n
return sum
print(calc([1, 2, 3]))
print(calc((1, 3, 5, 7)))
# 在参数前面加了一个*号
def calc(*numbers):
sum = 0
for n in numbers:
sum += n * n
return sum;
print(calc(1, 2, 3))
print(calc(1, 3, 5, 7))
print(calc())
nums = [1, 2, 3]
print(calc(nums[0], nums[1], nums[2]))
# *nums表示把nums这个list的所有元素作为可变参数传进去
calc(calc(*nums))
# 关键字参数
# 可变参数允许你传入0个或任意个参数,这些可变参数在函数调用时自动组装为一个tuple
# 关键字参数允许你传入0个或任意个含参数名的参数
# 关键字参数在函数内部自动组装为一个dict
def person(name, age, **kw):
print('name:', name, " age:", age, " other:", kw)
person("Michael", 30)
person('Bob', 35, city='Beijing')
person('Adam', 45, gender='M', job='Engineer')
# 关键字参数可以扩展函数的功能
extra = {'city': 'Beijing', 'job': 'Engineer'}
person('Jack', 24, city=extra['city'], job=extra['job'])
# **extra表示把extra这个dict的所有key-value用关键字参数传入到函数的**kw参数
person('Jack', 24, **extra)
# 命名关键字参数
# 到底传入了哪些,就需要在函数内部通过kw检查
def person(name, age, **kw):
if 'city' in kw:
pass
if 'job' in kw:
pass
print('name:', name, " age:", age, " other:", kw)
# 调用者仍可以传入不受限制的关键字参数
person('Jack', 24, city='Beijing', addr='Chaoyang', zipcode=123456)
# 如果要限制关键字参数的名字,就可以用命名关键字参数
def person(name, age, *, city, job):
print('name:', name, " age:", age, " city:", city, " job:", job)
person('Jack', 24, city='Beijing', job='Engineer')
# 如果函数定义中已经有了一个可变参数,后面跟着的命名关键字参数就不再需要一个特殊分隔符*了
# def person(name, age, *args, city, job):
# print(name, age, args, city, job)
# person('Jack', 24, 'Beijing', 'Engineer')
def person(name, age, *, city='Beijing', job):
print(name, age, city, job)
person('Jack', 24, job='Engineer')
def f1(a, b, c=0, *args, **kw):
print('a=', a, 'b=', b, 'c=', c, 'args=', args, 'kw=', kw)
def f2(a, b, c=0, *, d, **kw):
print('a=', a, 'b=', b, 'c=', c, 'd=', d, 'kw=', kw)
f1(1, 2)
f1(1, 2, c=3)
f1(1, 2, 3, 'a', 'b')
f1(1, 2, 3, 'a', 'b', x=99)
f1(1, 2, d=99, ext=None)
args = (1, 2, 3, 4)
kw = {'d': 99, 'x': '#'}
f1(*args, **kw)
args = (1, 2, 3)
kw = {'d': 88, 'x': '#'}
f2(*args, **kw)
# 递归函数
def fact(n):
if n == 1:
return 1
return n * fact(n - 1)
print(fact(1))
print(fact(5))
print(fact(100))
| false |
71013446d528f0dce9a7439ee4c84b364a5ea2c6 | hancoro/Python_Learn_Project | /PythonFile_RPH7_If_Statements.py | 1,036 | 4.4375 | 4 |
# set a boolean variable as true
boolean_for_if_statement = False
second_boolean_for_if_statement = False
# If statement with one condition
if boolean_for_if_statement:
print("One condition if statement HAS been met")
else:
print("One condition if statement was NOT met")
# If statement with multiple conditions
if boolean_for_if_statement and second_boolean_for_if_statement:
print("Both conditions have been met")
else:
print("Both conditions were not met")
# If statement with multiple conditions
if boolean_for_if_statement or second_boolean_for_if_statement:
print("One conditions has been met")
else:
print("Neither conditions were met")
# If statement where a condition is not equal and else if
if boolean_for_if_statement and second_boolean_for_if_statement:
print("Both conditions has been met")
elif not boolean_for_if_statement and not second_boolean_for_if_statement:
print("Neither condition has been met")
else:
print("one of the conditions was met")
| true |
3b31c41338a759b313b8195f4765aebca106c17c | hancoro/Python_Learn_Project | /PythonFile_RPH13_Exponent_Function.py | 266 | 4.15625 | 4 |
# this is a function that accepts 2 parameters
def raise_to_the_power_of(base_num, pow_num):
result = 1
for num in range(pow_num):
result = result * base_num
# print(num)
return result
print(raise_to_the_power_of(3, 3))
| true |
aeaf4ad44859525a4845e9a178e66bc3173c137f | hancoro/Python_Learn_Project | /PythonFile_RPH14_2d_lists_nested_loops.py | 661 | 4.5 | 4 |
# 2d lists are essentially lists of lists
# for example
number_grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[0]
]
# the example now has 4 rows with three columns
# to access a specific element in the list by reference to the row and column
print(number_grid[1][2]) # This will print row 1, column 2
# to print row
print(number_grid[2])
# this for loop will read out each row of the grid
for row in number_grid:
print(row)
# Nested for loop will read each element of the grid
# each column of row 0 will be read before moving onto the next row
for row in number_grid:
for col in row:
print(col)
| true |
518392eae8e2127061b15b1a75927899001537d1 | egroshev/old | /pyfolder/old/python3/learn/decorators.py | 1,356 | 4.28125 | 4 |
'''
# BEFORE USING A DECORATOR
def some_function(number):
print ("{}".format(number+1))
'''
"""
>>> some_function(11)
12
>>> some_function(8)
9
>>> some_function(1)
2
"""
# AFTER USING A DECORATOR
def history_decorator(my_function):
history = [] # list
def wrapper(my_argument): # creates a function wrapper within a function
history.append(my_argument) # since defined in this scope,has snapshot
my_function(my_argument) # of history list.
print ("History: {}".format(history))
return wrapper # returns a function wrapper from a function
# These 3 lines are equivalent to the bottom 3 lines
@history_decorator
def some_function(number):
print ("{}".format(number + 1))
# These 3 lines are equivalent to the above 3 lines
def some_function(number):
print ("{}".format(number + 1))
some_function = history_decorator(some_function) # same as @history_decorator
some_function(11) # testing
some_function(14)
"""
>>> some_function(11)
12
History: [11]
>>> some_function(8)
9
History: [11, 8]
>>> some_function(1)
2
History: [11, 8, 1]
"""
def addOne(myFunc):
def addOneInside(*args, **kwargs):
return myFunc(*args, **kwargs) + 1
return addOneInside
@addOne
def oldFunc(x=0):
return x
print ("{}".format(oldFunc())) # testing
print ("{}".format(oldFunc(500)))
| false |
fba98d5bc7c45544c8dbc47aa6ca5b75c4ae7762 | anuraga2/Coding-Problem-Solving | /Sorting/BubbleSort.py | 404 | 4.1875 | 4 | #Function to sort the array using bubble sort algorithm.
def bubbleSort(self,arr, n):
# code here
# running the outer loop
for i in range(n-1):
swapped = True
for j in range(n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
swapped = False
if swapped:
return arr
return arr | true |
386583b7139d1ffa01daaf3f430e2972e9dd821e | SravaniDash/Coursera-Python-For-Everyone | /exercises/chapter13/extractXML.py | 696 | 4.125 | 4 | # In this assignment you will write a Python program somewhat similar to http://www.py4e.com/code3/geoxml.py. The program will
# prompt for a URL, read the XML data from that URL using urllib and then parse and extract the comment counts from the XML data,
# compute the sum of the numbers in the file.
# Actual Data: http://py4e-data.dr-chuck.net/comments_1012757.xml
import urllib.request, urllib.parse, urllib.error
import xml.etree.ElementTree as ET
sum=0
address = input('Enter location: ')
handle = urllib.request.urlopen(address).read()
tree = ET.fromstring(handle)
for count in tree.findall('comments/comment'):
val = int(count.find('count').text)
sum = sum + val
print(sum)
| true |
143b32c0cbf692e4072c707d9e9de0bf77fb077f | HohShenYien/Harvard-CS50 | /Week6/credit.py | 1,954 | 4.125 | 4 | def main():
# Putting in all the return strings into a list
# so that the function just return an int
return_type = ["INVALID", "AMEX", "MASTERCARD", "VISA"]
nums = all_nums(get_nums())
# Print invalid if failed Luhn algorithm
if not luhn_check(nums):
print(return_type[0])
# Prevent the main function from proceeding to 11th line
return
print(return_type[check_card(nums)])
# A simple function to convert the numbers into a list
# This enables easier manipulation
def all_nums(n):
nums = []
while n > 0:
nums.append(n % 10)
n //= 10
# Inverts the list because the numbers are put into the list
# in an inverted order
return nums[::-1]
# Repeats until getting a valid number
def get_nums():
while True:
try:
nums = int(input("Number: "))
return nums
except:
pass
# Luhn algorithm implemented here
def luhn_check(nums):
# Copied the given list so that it can be changed in place
my_nums = nums.copy()
# every 2 numbers from 2nd last is multiplied by 2
for i in range(-2, -len(nums) - 1, -2):
my_nums[i] *= 2
total = 0
# Summing up the digits of the numbers in the list
for i in my_nums:
while i > 0:
total += i % 10
i //= 10
# Checking if last digit of total is 0
if total % 10 == 0:
return True
return False
# Finally, this checks the type of the card
def check_card(nums):
if len(nums) == 15:
if nums[0] == 3 and (nums[1] == 4 or nums[1] == 7):
return 1
elif len(nums) == 13 or len(nums) == 16:
if nums[0] == 4:
return 3
elif len(nums) == 16:
if nums[0] == 5:
for i in range(1, 6):
if nums[1] == i:
return 2
return 0
main()
| true |
b84126a63bac595977f08afcfe84130d80bd6f64 | Jahir575/Python3.8OOP | /EmployeeAssaignment.py | 1,342 | 4.4375 | 4 | """
Create an Employee class with following attributes and methods:
- constructor, which will create an instance of Employee class based on provided arguments:
first name, last name, email address and monthly salary
- get_annual_salary method, which will calculate and return employee annual salary
- show_employee_information method, which will show employee information in such syntax:
Employee: <full name>
Email address: <email>
Annual salary: <annual salary>
- an attribute, which will store the number of created objects of an Employee class
"""
class Employee:
def __init__(self, first_name, last_name, email, monthly_salary):
self.first_name = first_name
self.last_name = last_name
self.email = email
self.monthly_salary = monthly_salary
def annual_salary(self):
annual_salary = self.monthly_salary * 12
return annual_salary
def employee_details(self):
print(f"Employee: {self.first_name} {self.last_name}\n")
print(f"Email: {self.email}\n")
print(f"Annual Salary: {self.annual_salary()}\n")
employee1 = Employee('Sudhir', 'Ghosh','sudhir.ghosh@gmail.com', 16000)
employee2 = Employee('Ismail', 'Sheikh','ismail.sk@gmail.com', 18000)
employees = [employee1, employee2]
for employee in employees:
employee.employee_details()
print('\n')
| true |
a34dc0a076d26372679924c80bafee594878891b | gocommitz/PyLearn | /pydict.py | 732 | 4.15625 | 4 | #Import library
import json
#Loading the json data as python dictionary
#Try typing "type(data)" in terminal after executing first two line of this snippet
data = json.load(open("data.json"))
#Function for retriving definition
def retrive_definition(word):
if word in data:
return data[word]
elif word.title() in data:
return data[word.title()]
elif word.upper() in data:
return data[word.upper()]
elif word.lower() in data:
return data[word.lower()]
else:
return("Try later please check again, we cant find this word")
#Input from user
word_user = input("Enter a word: ")
#Retrive the definition using function and print the result
print(retrive_definition(word_user)) | true |
941223ed6e1f2897992eb7b0db86c7918305110a | Bshock817/basic-python | /basic2.py | 1,709 | 4.1875 | 4 | """
# Countdown - Create a function that accepts a number as an input.
# Return a new list that counts down by one, from the number (as the 0th element) down to 0 (as the last element).
def countdown(num):
nums = []
for val in range(num,-1,-1):
nums.append(val)
return nums
print(countdown(15))
# Print and Return - Create a function that will receive a list with two numbers.
# Print the first value and return the second.
def pr(nums_list):
print(nums_list[0])
return(nums_list[1])
print(pr([5,2]))
# First Plus Length - Create a function that accepts a list and returns the sum of the first value in the list plus the list's length.
def fpl(lst):
return lst[0] + len(lst)
print(fpl([5,2,3,5,6]))
# Write a function that accepts a list and creates a new list containing only the values from the original list that are greater than its 2nd value. Print how many values this is and then return the new list. If the list has less than 2 elements, have the function return False
def val_g(orig_list):
new_list = []
sec_val = orig_list[1]
for idx in range(len(orig_list)):
if orig_list[idx] > sec_val:
new_list.append(orig_list[idx])
print(len(new_list))
return new_list
print(val_g([3,5,8,4,7,9,6,1]))
# This Length, That Value - Write a function that accepts two integers as parameters: size and value.
# The function should create and return a list whose length is equal to the given size, and whose values are all the given value.
def l_v(size, value):
new_list = []
for num_times in range(size):
new_list.append(value)
return new_list
print(l_v(4,7))
"""
| true |
1111183e8cd379b298acbc3535787508395ba06b | Ajay-Puthiyath/Luminar_Django | /Luminar_Project/Flow_Controls/Decesion_Making_Statement/Maximum_Of_Three_Numbers.py | 985 | 4.25 | 4 | num1 = int(input("Enter the first number"))
num2 = int(input("Enter the second number"))
num3 = int(input("Enter the third number"))
if(num1>=num2) and (num1>=num3):
largest = num1
print("The largest number is",largest)
elif(num2>=num1) and (num2>=num3):
largest = num2
print("The largest number is",largest)
else:
largest = num3
print("The largest number is",largest)
if(num1>=num2) and (num1<=num3) or (num1>=num3) and (num1<=num2):
secondLargest = num1
print("the second largest number is", secondLargest)
if (num2 >= num1) and (num2 <= num3) or (num2 >= num3) and (num2 <= num1):
secondLargest = num2
print("the second largest number is", secondLargest)
if (num3 >= num2) and (num3 <= num1) or (num3 >= num1) and (num3 <= num2):
secondLargest = num3
print("the second largest number is", secondLargest)
a1 = min(num1,num2,num3)
a3 = max(num1,num2,num3)
a2 = (num1+num2+num3) - a1 - a3
print("Numbers in sorted order: ", a1, a2, a3)
| true |
0783801f9fc57d08bf0552c5935c4fed801628aa | SergioKulyk/Stepic | /Математика и Python для анализа данных/1 Неделя 1 - Основы Python/1.8 Функции/1.8.5.py | 597 | 4.1875 | 4 | # Напишите функцию convert(L), принимающую на вход список, состоящий из чисел и строк вида:
#
# [1, 2, '3', '4', '5', 6]
# и возвращающую список целых чисел (в том же порядке):
#
# [1, 2, 3, 4, 5, 6]
# Примечание. В этой задаче не нужно ничего считывать и ничего выводить на печать. Только реализовать функцию.
def convert(L):
return list(map(int, L))
# print(convert([1, 2, '3', '4', '5', 6]))
| false |
e8a759ffe437a57b693b79f6d3eb7dcff18f921e | addinkevin/programmingchallenges | /MedalliaChallenges/2017Challenge/problema2.py | 1,382 | 4.1875 | 4 | import unittest
"""
Given an integer n, we want you to find the amount of four digit
numbers divisible by n that are not palindromes.
A palindromic number is a number that remains the same when
its digits are reversed. Like 1661, for example, it is
"symmetrical".
For example, if n equals 4000, the only four digit numbers
divisible by 4000 are 4000 and 8000. Neither of those numbers
is a palindrome, so the answer would be 2.
If n equals 2002, then the only four digit numbers divisible by
2002 are 2002, 4004, 6006 and 8008. As all of them are
palindromes, the answer would be 0.
Complete a function named nonPalindromicMultiples that
receives an integer n. It should return the amount of four digit
numbers divisible by n that are not palindromes.
"""
MAX_NUMBER = 10000
def isPalindrom(number):
number = str(number)
i = 0
j = len(number) - 1
while i < j:
if number[i] != number[j]:
return False
i += 1
j -= 1
return True
def nonPalindromicMultiples(n):
count = 0
for number in range(n, MAX_NUMBER, n):
if not isPalindrom(number):
count += 1
return count
class MyTestCase(unittest.TestCase):
def test0(self):
self.assertEqual(2, nonPalindromicMultiples(4000))
self.assertEqual(0, nonPalindromicMultiples(2002))
if __name__ == '__main__':
unittest.main()
| true |
0cf95999f495b6e72ae69acef4eb2cc28ed21c88 | Aniket-99/Python-programs | /Python/Age.py | 291 | 4.3125 | 4 | age = int(input("Enter your age: "));
if(age <= 1):
print("You are infant")
elif(age >1 and age<13):
print("You are a child")
elif(age >13 and age<20):
print("You are a Teenager")
elif(age >=20 and age<=110):
print("You are an adult!!")
else:
print("Enter valid input")
| false |
d7e38ea8166127fd9b1d403d88094a0cc0f17b0a | commGom/pythonStudy | /sparta_algorithim/week_1/1_2_최빈값찾기02.py | 624 | 4.125 | 4 | input = "hello my name is sparta"
def find_max_occurred_alphabet(string):
alphabet_occurence_array = ["a","b",'c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
max_occurrence=0
max_alphabet=alphabet_occurence_array[0]
for alphabet in alphabet_occurence_array:
occurence=0
for char in string:
if char==alphabet:
occurence+=1
if occurence>max_occurrence:
max_occurrence=occurence
max_alphabet=alphabet
return max_alphabet
result = find_max_occurred_alphabet(input)
print(result) | false |
04caeadc2469e4bca2256b0731e62ee1d93c13a1 | SreeramSP/Python-Data-Collection-and-Processing | /#Below, we have provided a list of tuuple.py | 399 | 4.34375 | 4 | #Below, we have provided a list of tuples that contain students’ names and their final grades in PYTHON 101. Using list comprehension, create a new list passed that contains the names of students who passed the class (had a final grade of 70 or greater).
l1 = ['left', 'up', 'front']
l2 = ['right', 'down', 'back']
opposites=filter(lambda x: len(x[1])>3 and len(x[0])>3 , zip(l1,l2) )
| true |
fc72535954544203ce0c60b5dbdfa23c608bf7f3 | JustinKnueppel/CSE-1223-ClosedLab-py | /ClosedLab07a.py | 374 | 4.25 | 4 | def getWordCount(input):
numWords = 1
while " " in input:
numWords += 1
input = input[input.index(' ') + 1: len(input)]
return numWords
string = input('Enter a string: ')
while not string:
print('ERROR - string must not be empty\n')
string = input('Enter a string: ')
print(getWordCount(string))
print('Your string has', str(getWordCount(string)), 'words in it.') | true |
6f4de077c0f535f5a6e635ce86e95e13542508fa | JustinKnueppel/CSE-1223-ClosedLab-py | /ClosedLab04a.py | 663 | 4.15625 | 4 | grade = float(input('Enter a grade value between 0 and 100: '))
while (grade < 0 or grade > 100):
grade = float(input('ERROR: Grade must be between 0 and 100: '))
if (grade > 93):
print('You received an A')
elif (grade > 90):
print('You received an A-')
elif (grade > 87):
print('You received a B+')
elif (grade > 83):
print('You received a B')
elif (grade > 80):
print('You received a B-')
elif (grade > 77):
print('You received a C+')
elif (grade > 73):
print('You received a C')
elif (grade > 70):
print('You received a C-')
elif (grade > 67):
print('You received a D+')
elif (grade > 60):
print('You received a D')
else:
print('You received an E') | false |
e68cf7c5c99d97df4dc021ba20c7a0fd01ae791b | UF-CompLing/Word-Normalization | /FromLecture.py | 1,010 | 4.21875 | 4 | import re
TextName = 'King-James-Bible'
## ~~~~~~~~~~~~~~~~~~~~
## START OF FUNCTIONS
print('opening file\n')
input_file = open('Original-Texts/' + TextName + '.txt', 'r')
# the second parameter of both of these open functions is
# the permission. 'r' means read-only.
#
# The 'Original-Texts/' part is so that it looks
# in the 'Original-Texts' folder
print('going through every line in file. hold on a sec...')
# store every word in here
for line in input_file:
# regex expressions
regexed = re.compile(r'\W+', re.UNICODE).split(line)
# this function takes out characters that are not
# letter or numbers
#
# BUT... it makes a list. let's join that list back together!
# build word to print back to file
toOutput = ''
for word in regexed:
# there are lots of blank spaces that get
# caught up in our program
if word is '':
continue
toOutput += word.lower() + ' '
# print word to our screen
print(toOutput + '\n')
| true |
0473322373aa0f9d9989f69cb221b7eb88fa176f | OmChaurasia/Python-modules-I-worked | /garbage python/lists.py | 1,052 | 4.28125 | 4 | things=["apple","mango","banana",56]
print(things)#to print pura
print(things[1])#to print specific
num=[2,3,2,5,6]
num.sort()#sort karne ke liye
num.reverse()#reverse karne ke liye
print(num)
"""
list me slice usi tarah hota hai jaise string me hota tha
slice karne par original change nahi hota keval print ho jata hai
sort aur reverse original list ko change kar deta hai
list lenth ke liye len esme bhi use hota hai
maximum and minimum bhi find kar sakte hai
append se number add kar sakte hai list me
we can make empty list and add using append
insert se bhi add kar sakte hai
insert me phala index aur dusara value hota hai
pop ka use last element ko remove karta hai
romve specific value ko remove karta hai
mutable can change
unmutable can not change ex tapal
tapal me []ki jagah () ka use karte hai
"""
print(num[0:5])
print(len(num))
print(max(num))
print(min(num))
num.append(7)
num.insert(1,55)
num.remove(5)
num.pop()
num[1]=45
print(num)
tp=(5,6,7)
print(tp)
a=5
b=6
a,b=b,a
"""
temp var banaye bhina value ko change karna
"""
print(a,b) | false |
2aa0ea0761121f1eeb626b17e3c04c97282c9bd1 | amcclintock/Breakfast_Programming_Guild | /broken_1_6.py | 1,217 | 4.46875 | 4 | Take user input, and tell me stuff about the data
user_input = input('Enter something:')
#Check if the data contains alpha
if (user_input.isalpha()):
print (user_input, " contains alpha characters")
#Do some math on characters
three_user_input = user_input * 3
print (user_input, " three times is: ", three_user_input) # End of code comment
#Is it upper case?
if (user_input.isupper()):
print (user_input, " is all uppercase")
elif (user_input.islower()):
print (user_input, " is all lowercase")
else:
print (user_input, " is a mix of upper and lowercase")
#Check if the data is a whole number
if (user_input.isdigit()):
print (user_input, " is a whole numbers")
#Only if a whole number, dig deeper
three_user_value = int(user_input) * 3
print (user_input, " times 3 =", three_user_value)
#is it an even number?
if (int(user_input) % 2 == 0):
print (user_input, " is an even number")
else:
print ("Checking to see if it's odd")
elif:
print (user_input, " is an odd number")
#No good guess for the data
print ("I don't know what ", user_input, " is!")
| true |
abad7aaa10a6918b8eb3b763e179178eeb677253 | driscoll42/leetcode | /0876-Middle_of_the_Linked_List.py | 1,381 | 4.15625 | 4 | '''
Difficulty: Easy
Given a non-empty, singly linked list with head node head, return a middle node of linked list.
If there are two middle nodes, return the second middle node.
Example 1:
Input: [1,2,3,4,5]
Output: Node 3 from this list (Serialization: [3,4,5])
The returned node has value 3. (The judge's serialization of this node is [3,4,5]).
Note that we returned a ListNode object ans, such that:
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next = NULL.
Example 2:
Input: [1,2,3,4,5,6]
Output: Node 4 from this list (Serialization: [4,5,6])
Since the list has two middle nodes with values 3 and 4, we return the second one.
Note:
The number of nodes in the given list will be between 1 and 100.
'''
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def middleNode(self, head: ListNode) -> ListNode:
'''
midNode = head
cnt = 0
while True:
cnt += 1
if cnt == 2:
cnt = 0
midNode = midNode.next
if head.next is None:
break
head = head.next
return midNode
'''
slow = head
while head and head.next:
head = head.next.next
slow = slow.next
return slow | true |
016b4c71006d62f4ca5857c8d3eb52c46a109c74 | saisatwikmeda/Personal-Programs | /find_short.py | 471 | 4.15625 | 4 | #Sai Satwik Reddy Meda
# Returning the length of the smallest word in a given string
def find_short(s):
L = s.split(' ') #split list
final = ""
final = L[0]
for i in range(len(L)):
if len(final) > len(L[i]):
final = L[i] # Assign smallest word everytime it changes
i += 1
return len(final) # returning length of hte smallest word
#Alternatively
def find_short(s):
return min(len(x) for x in s.split())
#After learning more python | true |
36ad03ca7141958e68f7429d438c9f0f7a51834e | clintmod/aiden | /2023.05.06/Worldcount.py | 451 | 4.15625 | 4 | # Ask the user to enter a sentence
sentence = input("Enter a sentence: ")
# Initialize a variable to count vowels
vowel_count = 0
# Loop over each character in the sentence
for char in sentence:
# Check if the character is a vowel
if char.lower() in "aeiou":
# If it is, increment the vowel count
vowel_count += 1
# Print the total number of vowels found
print("The total number of vowels in the sentence is:", vowel_count)
| true |
98c9974136879a86fbc53fcc7ec65c4ee81b9864 | Davin-Rousseau/ICS3U-Assignment-6-Python | /assignment_6.py | 1,198 | 4.25 | 4 | #!/usr/bin/env python3
# Created by: Davin Rousseau
# Created on: November 2019
# This program uses user defined functions
# To calculate surface area of a cube
import math
def surface_area_cube(l_c):
# calculate surface area
# process
surface_area = (l_c ** 2) * 6
# output
return surface_area
def main():
# This checks if input is an integer and positive,
# then calls function and keeps going until user
# enters a positive integer
# Input
input_1 = input("Enter the length of the cube(cm): ")
print("")
while True:
try:
length_cube = int(input_1)
if length_cube > 0:
# call functions
surface_area = surface_area_cube(l_c=length_cube)
print("The surface area of the cube is: {0:,.2f}cm^2"
.format(surface_area))
break
else:
print("Invalid input")
input_1 = input("Please try again: ")
continue
except ValueError:
print("Invalid input.")
input_1 = input("Please try again: ")
continue
if __name__ == "__main__":
main()
| true |
83376880f7ac1c33a8b35d4b00b6b703891a1d32 | jkim23/python-code-samples-1 | /radius JTKIM (1).py | 445 | 4.34375 | 4 | #jt kim
#2.29.2019
#compute radius of circle
#radius = int(input("Enter radius for your circle: "))
#area_of_circle = (radius * 3.14) * radius
#print ("Your circle is: ", area_of_circle)
def areaOfCircle(radius):
area = (radius ** 2) * 3.14
return area
print("the area of the circle is ", areaOfCircle(10))
print("the area of the circle is ", areaOfCircle(20))
print("the area of the circle is ", areaOfCircle(30))
| true |
600afdcf40cba9a2efacde240c6a71a669e4fbfa | kenigandrey/python | /Lesson-2/Task3.py | 837 | 4.15625 | 4 | #3. Пользователь вводит месяц в виде целого числа от 1 до 12. Сообщить к какому времени года относится месяц (зима, весна, лето, осень).
# Напишите решения через list и через dict.
# list
n = int(input("Укажите номер месяца (целое число от 1 до 12) = "))
lst = "зима,зима,весна,весна,весна,лето,лето,лето,осень,осень,осень,зима".split(',')
print(lst[n-1] + ' (по списку)')
# dict
my_dict = dict()
for i in range(len(lst)):
my_dict.update({i: lst[i]})
print(my_dict.get(n-1) + ' (по словарю)')
#print("\nВсе значения:")
#for i in range(len(lst)):
# print(f"{lst[i]} - {my_dict.get(i)}")
| false |
bde9ebc19081fed03780da6564698d9f5d1b8c06 | kenigandrey/python | /Lesson-3/Task1.py | 797 | 4.34375 | 4 | # Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление.
# Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль.
def my_div(arg_1, arg_2):
"""Возвращает результат деления arg_1 на arg_2"""
try:
return arg_1 / arg_2
except ZeroDivisionError:
print('На 0 делить нельзя')
print('my_div(2, 1) = ', my_div(2, 1))
print('my_div(1, 2) = ', my_div(1, 2))
print('my_div(-2, 1) = ', my_div(-2, 1))
print('my_div(-1, 2) = ', my_div(-1, 2))
print('my_div(0, 2) = ', my_div(0, 2))
print('my_div(2, 0) = ', my_div(2, 0))
| false |
4cbdb9a15e97a8bc1158cc1db2588d095bfc6003 | carlos-carlos/different-solutions | /solution_03.py | 1,535 | 4.46875 | 4 | '''
Write a script that sorts a list of tuples based on the number value in the tuple.
For example:
unsorted_list = [('first_element', 4), ('second_element', 2), ('third_element', 6)]
sorted_list = [('second_element', 2), ('first_element', 4), ('third_element', 6)]
'''
#driver code and empty list for the desired results
unsorted_list = [('first_element', 4), ('second_element', 2), ('third_element', 6)]
sorted_list = []
#for each item in the unsorted_list for the whole list
#set to 'min' to value of list index 0 tuple index 1
for x in range(0, len(unsorted_list)):
min = unsorted_list[0][1]
print(min)
index = 0
#for each item in unsorted_list for the whole list
# if index 1 of each item in unsorted_list is less than the value of 'min'
# min should equal the value of index 1 of each item in unsorted_list
# 'index' shall equal each item in the unsorted list
for i in range(0, len(unsorted_list)):
if unsorted_list[i][1] < min:
min = unsorted_list[i][1]
index = i
# add to sorted_list each index from unsorted_list
sorted_list.append(unsorted_list[index])
#remove each index from unsorted_list
unsorted_list.remove(unsorted_list[index])
print(unsorted_list)
print(sorted_list)
# this is super confusing to me. I'm not exactly sure what is going on starting from 'min'
# especially confused by the unsorted_list[0][1] bit and the use of range(). Why not use just len()?
# I lost track of how the end connects to index which is set to zero
| true |
34dc764b76b229373cda809ddde5a0372170ef6b | outoftune2000/Python | /strings/substringcount.py | 508 | 4.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#program to count the number of times a given substring has been repeated in a given string
def countingSubstrings(string,substring):
count=0
for i in range(0,len(string)):
if string[i:i+len(substring)]==substring:
count=count+1
return count
S=input("Enter a string: ")
SUB=input("Enter the subsring: ")
COUNT=countingSubstrings(S,SUB)
print ("The number of times the given substring: ",SUB," ,in the string: ",S,", is: ",COUNT)
| true |
accd5bfd406cab61113d642643f2bed1307bd865 | danieltshibangu/Mini-projects | /kilometer.py | 598 | 4.34375 | 4 | # This program will prmpt for distance in km
# then convert distace to miles by formula
# miles = kilometers * 0.6214
# define variables
miles = 0.0
kilometers = 0.0
# define miles constant
K_FACTOR = 0.6214
# main will prompt for kilometers,
# use km to miles funtion
# print result
def main():
kilometers = float( input( "Enter number of kilometers: " ) )
km_to_miles( kilometers )
print( format( km_to_miles( kilometers ), '.3f' ) )
# takes argument, returns miles
def km_to_miles( kilometers ):
miles = kilometers * K_FACTOR
return miles
# call main function
main()
| true |
1cdb8009743880959b3f7b17feecfec0a3e64031 | danieltshibangu/Mini-projects | /PYTHON PRACT.py | 598 | 4.21875 | 4 | # This program displays property taxes
TAX_FACTOR = 0.0065 #Represents tax factor
# Get the first lot number
print( 'Enter the property lot number' )
print( 'or rnter 0 to end.' )
lot = int( input( 'Lot number: ' ) )
# continue processing as long as the user
# does not enter lot number 0
while lot != 0:
#Get the property tax
tax = value * TAX_FACTOR
#Display the tax
print( 'Property tax: $', format( tax, '.2f' ), sep=' ' )
#get the next lot number
print( 'Enter the next lot number or' )
print( 'enter 0 to end.' )
lot = int( input( 'Lot number: ' ) )
| true |
a2b2651ad516b9d159954d37d301cda056dcced4 | danieltshibangu/Mini-projects | /initials.py | 932 | 4.1875 | 4 | # this program gets title data from user and
# prints the data
# the main function gets a first, middle and
# last name from user, passing them as arguments
# for get_initials functions. Initial name
# entered and the initials of name printed
def main():
first = input( "Enter first name: " )
middle = input( "Enter middle name: " )
last = input( "Enter last name: " )
get_initials( first, middle, last )
print( "Initial name:", first, middle, last )
print( "Initials:", get_initials( first, middle, last ) )
# the get_initials function gets first, middle,
# last names as arguments and returns a string
# containing each inital
def get_initials( first, middle, last ):
initials = ''
first = first[0].upper() + '.'
middle = middle[0].upper() + '.'
last = last[0].upper() + '.'
initials += first + middle + last
return initials
# call main function
main()
| true |
e6710b0744d0703493aa2434f4a7a171cda70c28 | danieltshibangu/Mini-projects | /total_sales.py | 709 | 4.34375 | 4 | # this program will display the total sales for
# the days of the week
# DAYS_OF_WEEK is used as a constant for the
# size of the list
DAYS_OF_WEEK = 7
def main():
# create the list for days of the week
sales = [0] * DAYS_OF_WEEK
# define the accumulator
total = 0.0
# get the sales for each day of the week
for index in range( DAYS_OF_WEEK ):
print( "Enter sales for day", index+1,
": ", end='' )
sales[ index ] = float( input() )
# Get the total sales for the week
for value in sales:
total += value
# print the values
print( "The total is: $", format( total, ',.2f'),
sep='' )
# call the main function
main()
| true |
ba2de7234a0c6c4ad0c467db583dd97bd6721be2 | danieltshibangu/Mini-projects | /kinetic_energy.py | 732 | 4.3125 | 4 | # program calculates kinetic energy of object
# define variables
mass = 0.0
velocity = 0.0
k_energy = 0.0
# main function will prompt for
# mass and velocity, call the kinetic_energy
# function and display the kinetic energy
def main():
mass = float( input( "Enter mass in kilograms: " ) )
velocity = float( input( "Enter velocity in m/s: " ) )
kinetic_energy( mass, velocity )
print( "The kinetic energy of this object is:" )
print( format( kinetic_energy( mass, velocity ), ',.3f' ) )
# kinetic_energy func calculates
# kinetic energy from mass and velocity
def kinetic_energy( mass, velocity ):
k_energy = 0.5 * mass * ( velocity ** 2 )
return k_energy
# calls main function
main()
| true |
02467d255c9184e51c2fd62edd052e5a9dd1a5dd | danieltshibangu/Mini-projects | /rand_file_writer.py | 793 | 4.3125 | 4 | # this program will print a user specified amount
# of random numbers to the random_numbers.txt file
# import the random module
import random
# state the variables used
num_of_rand = 0
random_num = 0
# state the constants
RAND_MAX = 500
def main():
# create variable for user input
num_of_rand = int( input( "Enter amount of random numbers: " ) )
# open the file
infile = open( 'random_numbers.txt', 'w' )
# randomize number, writes to file as number var
# gets too num_of_rand iterations
for number in range( 1, num_of_rand+1 ):
random_num = random.randint( 1, RAND_MAX )
infile.write( str( random_num ) + '\n' )
# close the file
infile.close()
print( "Saved in the random_numbers.txt file." )
# call the main function
main()
| true |
9c4aea9dd5ed5b7f1ebc7f69cc058032e0582d4d | subash-sunar-0/python3 | /Assignment1.py | 815 | 4.25 | 4 | #WAP that ask user to enter their name and their age.print out a message address to them that tells them the year they will turn 100 years old
try:
name = str(input("please enter your name:" ))
age = int(input("Please enter your age: "))
num = 100-age
if age >=100:
print(name, "you are already 100 years old. Your age is", age)
else:
print(name, "you will turn 100 years old after", num, "years")
except ValueError:
print("invalid name or age \n please try again \n ")
name = str(input("please enter your name again: "))
age = int(input("please enter your age again: "))
if age>=100:
print(name, "your are already 100 years old. your age is", age)
else:
print(name, "you will turn 100 years old after", age, "years")
| true |
ca327674cf6069bd0628d2ffb013bc021e5b2b5b | Tulip2MF/100_Days_Challenge | /day_010/number_of_days.py | 716 | 4.125 | 4 | def divisionFunction(year):
if (year % 4) == 0:
if (year % 400) == 0:
return True
elif (year % 100) == 0:
return False
else:
return True
else:
return False
def days_in_month(year, month):
leap_year = divisionFunction(year)
month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if leap_year is True and month == 2:
month_days[1] += 1
month_index = month - 1
number_of_days = month_days[month_index]
return number_of_days
year = int(input("Enter a year: "))
month = int(input("Enter a month: "))
days = days_in_month(year, month)
print(f"There is {days}days in month no- {month} of year- {year}")
| true |
b0d6a2da26dbb9753984c4e809ecd416bda12714 | defaults/algorithms | /Python/Geometry/orientation_of_3_ordered_points.py | 1,858 | 4.15625 | 4 | # coding=utf-8
from __future__ import print_function
"""
Orientation of an ordered triplet of points in the plane can be
1. counterclockwise
2. clockwise
3. collinear
If orientation of (p1, p2, p3) is collinear, then orientation of (p3, p2, p1) is also collinear.
If orientation of (p1, p2, p3) is clockwise, then orientation of (p3, p2, p1) is counterclockwise and
vice versa is also true.
Slope of line segment (p1, p2): σ = (y2 - y1)/(x2 - x1)
Slope of line segment (p2, p3): τ = (y3 - y2)/(x3 - x2)
If σ < τ, the orientation is counterclockwise (left turn)
If σ = τ, the orientation is collinear
If σ > τ, the orientation is clockwise (right turn)
Using above values of σ and τ, we can conclude that,
the orientation depends on sign of below expression:
(y2 - y1)*(x3 - x2) - (y3 - y2)*(x2 - x1)
Above expression is negative when σ < τ, i.e., counterclockwise
Above expression is 0 when σ = τ, i.e., collinear
Above expression is positive when σ > τ, i.e., clockwise
"""
class Point(object):
"""
Structure for point
"""
def __init__(self, x, y):
self.x = x
self.y = y
def orientation(point_1, point_2, point_3):
"""
Method to find orientation of three points
:param point_1: First point
:param point_2: Second point
:param point_3: Third point
:return orientation: String denoting orientation of points
"""
value = (point_2.y - point_1.y) * (point_3.x - point_2.x) - \
(point_2.x - point_1.x) * (point_3.y - point_2.y)
print(value)
return 'collinear' if value == 0 \
else 'clockwise' if value > 0 else 'counter clockwise'
p_1 = Point(0, 0)
p_2 = Point(4, 4)
p_3 = Point(1, 2)
result = orientation(p_1, p_2, p_3)
expected_result = 'counter clockwise'
print('These points are:', result)
assert result == expected_result
| true |
1b6a6723c48abfd90938356ffd29f520c346c55f | thevolts/PythonSnippets | /Day_of_the_week.py | 319 | 4.25 | 4 | # Python program to Find day of
# the week for a given date
import datetime
import calendar
def findDay(date):
born = datetime.datetime.strptime(date, '%d %m %Y').weekday()
return (calendar.day_name[born])
# Driver program
date = '03 02 2019'
date = str(input("Enter Date :"))
print(type(date))
print(findDay(date)) | true |
f43ab77e2049e5525b260811534d8e925a66b45b | ViRaL95/HackerRank | /strings/find_maximum_consecutive_repeating.py | 1,211 | 4.3125 | 4 | def find_max_consecutive(string):
"""
This method finds the largest consecutive characters in a string. It does this by
having a previous and a current 'pointer' which checks if they are equal. If they
are equal we can increase a count and check if its value is greater than max_.
If it is we update the new character that contains the longest consecutive
characters and update max_.
If the two characters are not equal we can update the value of the count
to 1. Count is represented by the variable index in this code.
"""
index = 1
count = 0
max_ = 1
largest = string[0]
while count < len(string) - 1:
prev = string[count]
current = string[count + 1]
if prev == current:
index += 1
else:
index = 1
if index >= max_:
max_ = index
largest = string[count]
count += 1
return largest
if __name__ == '__main__':
a = find_max_consecutive("geeekk")
b = find_max_consecutive("aaaabbccbbb")
c = find_max_consecutive("ab")
d = find_max_consecutive("aaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbb")
print(a)
print(b)
print(c)
print(d)
| true |
4f9d9ba09b4835ccef2fd4aac4a76296be2250bc | dmitchell28/Other-People-s-Code | /quessing a number.py | 815 | 4.28125 | 4 | from random import randint
print ("In this program you will enter a number between 1 - 100."
"\nAfter the computer will try to guess your number!")
number = 0
while number < 1 or number >100:
number = int(input("\n\nEnter a number for the computer to guess: "))
if number > 100:
print ("Number must be lower than or equal to 100!")
if number < 1:
print ("Number must be greater than or equal to 1!")
guess = randint(1, 100)
print ("The computer takes a guess...", guess)
while guess != number:
if guess > number:
guess -= 1
guess = randint(1, guess)
else:
guess += 1
guess = randint(guess, 100)
print ("The computer takes a guess...", guess)
print ("The computer guessed", guess, "and it was correct!") | true |
131534c10785852aad6b7b75f442f7b2d3708e37 | amnaamirr/python-beginners | /volume-of-sphere.py | 246 | 4.3125 | 4 | """Write a python program to get the volume of a sphere, take the radius as input from user. V = 4/3 πr3"""
import math
radius = float(input("ENTER RADIUS: "))
pi = math.pi
volume = 4/3*(pi)*(radius**3)
print("THE VOLUME OF SPHERE IS",volume) | true |
79e4531c7cddbe0819ed8f25f947271b43a0a7fe | amnaamirr/python-beginners | /checking-palindrome.py | 461 | 4.1875 | 4 | """Write a program to check whether given input is palindrome or not """
# palindrome is a number which reads the same forward or backward
num = (input("ENTER A NUMBER: "))
reverse_num = num[::-1]
while int(num) > 9:
if num == reverse_num:
print(f"THE NUMBER {num} IS A PALINDROME!")
break
else:
print(f"THE NUMBER {num} IS NOT A PALINDROME!")
break
else:
print(f"THE NUMBER {num} IS NOT A PALINDROME!")
| true |
83d52ed13f38fe1a7a8a56676fbdd2df539ebb42 | 16030IT028/Daily_coding_challenge | /SmartInterviews/SmartInterviews - Basic/044_Half_Diamond_pattern.py | 654 | 4.21875 | 4 | # https://www.hackerrank.com/contests/smart-interviews-basic/challenges/si-basic-print-half-diamond-pattern/problem
"""
Print half diamond pattern using '*'. See example for more details.
Input Format
Input contains a single integer N.
Constraints
1 <= N <= 50
Output Format
For the given integer, print the half diamond pattern.
Sample Input 0
3
Sample Output 0
*
**
***
**
*"""
n = int(input())
def pattern(n):
for i in range(0, n):
for j in range(0, i+1):
print ('*', end = '')
print()
for i in range(n, 0, -1):
for j in range(0, i-1):
print("*", end = '')
print()
pattern(n) | true |
857582fbc152c5f27e6203ff838284f458161dba | 16030IT028/Daily_coding_challenge | /SmartInterviews/047_Swap_Bits.py | 1,551 | 4.15625 | 4 | # https://www.hackerrank.com/contests/smart-interviews/challenges/si-swap-bits/problem
"""
Given a number, swap the adjacent bits in the binary representation of the number, and print the new number formed after swapping.
Input Format
First line of input contains T - number of test cases. Each of the next T lines contains a number N.
Constraints
1 <= T <= 100000
0 <= N <= 109
Output Format
For each test case, print the new integer formed after swapping adjacent bits, separated by new line.
Sample Input
4
10
7
43
100
Sample Output
5
11
23
152
Explanation
Test Case 1
Binary Representation of 10: 000...1010
After swapping adjacent bits: 000...0101 (5)
Test Case 2
Binary Representation of 7: 000...0111
After swapping adjacent bits: 000...1011 (11)"""
# Reference : https://www.geeksforgeeks.org/swap-all-odd-and-even-bits/
# If we take a closer look at the example, we can observe that we basically need to right shift (>>) all even bits (In the above example, even bits of 23 are highlighted) by 1 so that they become odd bits (highlighted in 43), and left shift (<<) all odd bits by 1 so that they become even bits.
def swapBits(n):
# Get all even bits of n
even_bits = n & 0xAAAAAAAA
# Get all odd bits of n
odd_bits = n & 0x55555555
# Right shift of even bits
even_bits >>= 1
# Left shift of odd bits
odd_bits <<= 1
# Combine even and odd bits
return (even_bits | odd_bits)
t = int(input())
for tc in range(t):
n = int(input())
print (swapBits(n)) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.