blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
77efe1b0c6dce387b29f9719ec8be6c217373b86 | gpastor3/Google-ITAutomation-Python | /Course_1/Week_4/iterating_over_the_contents_of_a_dictionary.py | 1,835 | 4.6875 | 5 | """
This script is used for course notes.
Author: Erick Marin
Date: 10/20/2020
"""
# You can use for loops to iterate through the contents of a dictionary.
file_counts = {"jpg": 10, "txt": 14, "csc": 2, "py": 23}
for extension in file_counts:
print(extension)
# If you want to access the associated values, you ca... |
2d593998eaf8c47e2b476f7d5c50143ef75f409a | gpastor3/Google-ITAutomation-Python | /Course_2/Week_5/charfreq.py | 873 | 4.1875 | 4 | #!/usr/bing/env python3
"""
This script is used for course notes.
Author: Erick Marin
Date: 12/26/2020
"""
# To use a try-except block, we need to be aware of the errors that functions
# that we're calling might raise. This information is usually part of the
# documentation of the functions. Once we know this we ca... |
7c1386e726f4867617ac9682657532da2425df07 | gpastor3/Google-ITAutomation-Python | /Course_1/Week_2/returning_values.py | 1,324 | 4.25 | 4 | """
This script is used for course notes.
Author: Erick Marin
Date: 10/08/2020
"""
def area_triangle(base, height):
""" Calculate the area of triange by multipling `base` by `height` """
return base * height / 2
def get_seconds(hours, minutes, seconds):
""" Calculate the `hours` and `minutes` into sec... |
f6db2b7d63a1b338658251c103c2cf28692d6849 | gpastor3/Google-ITAutomation-Python | /Course_2/Week_4/myapp.py | 1,450 | 4 | 4 | """
This script is used for course notes.
Author: Erick Marin
Date: 12/21/2020
"""
import os
import subprocess
# This script is modifying the contents of the path environment variable by
# adding a directory to it. We then call the myapp command with that modified
# variable. Doing it this way, the command will run... |
76b5fc4dfe0b3ab6dd348c377823f9a559d051cd | gpastor3/Google-ITAutomation-Python | /Course_1/Week_1/other_languages.py | 538 | 3.5625 | 4 | """
This script is used for course notes.
Author: Erick Marin
Date: 10/05/2020
"""
# To explore some of the similarities and differences between various
# scripting languages, let's take a look at a simple program that prints the
# words hello world ten times in three different languages, Python, Bash, and
# PowerShe... |
aa96e9acb44032b35e1b53784b117d989af43758 | gpastor3/Google-ITAutomation-Python | /Course_1/Week_4/iterating_over_lists_and_tuples.py | 2,405 | 4.59375 | 5 | """
This script is used for course notes.
Author: Erick Marin
Date: 10/20/2020
"""
animals = ["Lion", "Zebra", "Dolphin", "Monkey"]
chars = 0
for animal in animals:
chars += len(animal)
print("Total characters: {}, Average length: {}".format(chars, chars/len(animals)))
# The 'enumerate' function returns a tuple... |
23f65736ca32043ad2e175282c79f1ff1e47bfb1 | gpastor3/Google-ITAutomation-Python | /Course_1/Week_2/branching_with_if_statements.py | 578 | 4.09375 | 4 | """
This script is used for course notes.
Author: Erick Marin
Date: 10/09/2020
"""
def hint_username(username):
""" If username is less than than 3 characters, print message """
if len(username) < 3:
print("Invalid username. Must be at least 3 characters long")
hint_username("I")
def is_positive... |
b0570c87b7a5d7389973b315aca7d79de585a452 | gpastor3/Google-ITAutomation-Python | /Course_1/Week_2/defining_functions.py | 919 | 4.125 | 4 | """
This script is used for course notes.
Author: Erick Marin
Date: 10/08/2020
"""
def greeting(name, department):
""" Print out a greeting with provided `name` and department
parameters. """
print("Welcome, " + name)
print("Your are part of " + department)
# Flesh out the body of the print_second... |
123187441133b573b5058569e0a972964d11221b | gpastor3/Google-ITAutomation-Python | /Course_1/Week_4/the_parts_of_a_string.py | 1,668 | 4.34375 | 4 | """
This script is used for course notes.
Author: Erick Marin
Date: 10/11/2020
"""
# String indexing
name = "Jaylen"
print(name[1])
# Python starts counting indices from 0 and not 1
print(name[0])
# The last index of a string will always be the one less than the length of
# the string.
print(name[5])
# If we tr... |
6b5bf4bac33edff1c2213500d859e73d6b483c00 | wangsanshi123/test1 | /long_test.py | 275 | 3.640625 | 4 | # -*- coding:utf-8 -*-
def fun1():
pass
def fab(max):
n, a, b = 0, 0, 1
L = []
while n < max:
L.append(b)
a, b = b, a + b
n = n + 1
return L
if __name__ == '__main__':
for i in fab(5):
print i
print fab(5)
pass |
e492c2f4b33385f59edbc612a1adfffc18158aae | douglasfreire/aprendizagem_python | /Manipulação de arquivos/usando_bloco_with.py | 315 | 3.5625 | 4 | #!/usr/bin/python3
'''
Usando o with garante o fechamento do recurso alocado dentro
do bloco
'''
with open('arquivo.csv') as arquivo:
for registro in arquivo:
print('Nome: {}, idade: {}'.format(*registro.strip().split(',')))
if arquivo.closed:
print("Verificando se o arquivo foi fechado mesmo") |
5f6102a34a5f562d1f3738d87b767a7e0a1d9a11 | douglasfreire/aprendizagem_python | /estruturas_controle/for_4.py | 331 | 3.796875 | 4 | '''
Dessa forma ele executará o else normalmente
'''
for i in range(1, 10):
print(i)
else:
print('Finished')
print('##########################################')
'''
Quando ele encontra um break, o 'else' não será executado
'''
for i in range(1, 10):
if i == 6:
break
print(i)
else:
print('Fi... |
c978f67729adccef51116afae6235149677ede2f | jorda262/Python | /Assignment 06/hw6pr3.py | 705 | 4.09375 | 4 | #This program utilizes a dictionary of names and associated
#values and utilizes key-word arguments to go through all
#of the items and search for the highest score and return
#that score and the student associated with that score
def main():
highScore(ann=100,bob=90,carol=80,dave=70)
highScore(ann=100,bob=90,c... |
5f4125b03dec22c6ce7e4459bf21e50c55ae4288 | molssi-seamm/read_structure_step | /read_structure_step/utils.py | 1,821 | 3.828125 | 4 | from pathlib import Path
from . import formats
import re
def guess_extension(file_name, use_file_name=False):
"""
Returns the file format. It can either use the file name extension or
guess based on signatures found in the file.
Correctly handles .gz and .bz2 files.
Parameters
----------
... |
2487882c93374b6f83cb1cdcefb0819bcb7d8d00 | jmaffett/Comp141-Final | /get_suggestion.py | 714 | 3.71875 | 4 | import json
import sys
def main():
weather_file = sys.argv[1]
print(f'Reading data from: {weather_file}')
with open(weather_file, 'r') as f:
data = json.load(f)
print(f'API response: {data}')
print()
# convert Kelvin to Fahrenheit
temp = round((data['main']['feels_like'] - 273.15)... |
d38cc7af1e683c610eabfb2c149ba71b5d1729a7 | eljlee/hb-hw-melon-raffle | /version2/raffle.py | 721 | 3.5 | 4 | """Randomly pick customer and print customer info"""
from random import choice
from customers import get_customers_from_file
from sys import argv
def random_winner(customers):
"""Call random winner using the list generated by customers program"""
chosen_customer = choice(customers)
print "Tell {} at {} that th... |
6f06c85bb75b03200e4751f83e65bbb009296b0c | jkafrouni/association_rules_extractor | /association_rules_extractor/helpers.py | 5,785 | 4.15625 | 4 | import csv
# --------------------- Functions used in main() --------------------- #
def load_csv(filename):
"""Loads a csv of transactions and returns a list of transactions represented as sets"""
transactions = []
with open('data/INTEGRATED-DATASET.csv', 'r', newline='') as csvfile:
reader = csv.... |
9e56e6ba16fc99f960de9f09a75709103505025b | ahmed-techno/GIZ-pass-python | /python-pass.py | 399 | 3.5625 | 4 |
class Solution:
@staticmethod
def longest_palindromic(s: str) -> str:
longest_str = ''
for i in range(len(s)):
for j in range(len(s), i, -1):
if len(longest_str) >= j-i:
break
elif s[i:j] == s[i:j][::-1]:
... |
8e4dce0b94215b565784b4f091ecfaa911945cee | NimaVahdat/Bio-Inspired-Computation_algorithms | /Ant/mainANT.py | 585 | 3.5 | 4 | import numpy as np
from SAC import AntColony
# Importing the data
data = open('Data1.txt', 'r')
distances = []
for i in range(23):
line = data.readline()
if i > 2:
distances.append([int(x) for x in line.strip().split()])
for i in range(len(distances)):
for j in range(len(distances)):... |
564cda486786fee48f0ddc6541beff8c1281e6bf | daeon/Fragscapy | /fragscapy/packetlist.py | 6,713 | 3.5 | 4 | """A list of wrappers around Scapy packets and metadata (e.g. delay)."""
import time
import scapy.sendrecv
# The minimum time (in seconds) a packet will be delayed
MIN_TIME_DELAY = 0.01
def _safe_delay(delay):
"""Checks that `delay` is a positive float number else raises a
ValueError."""
try:
... |
3566e2849486cccbf0526250ac7a038a69e9c966 | cpsln/learning-challenge-season-3 | /insert_data.py | 928 | 3.71875 | 4 | import pymongo
# connect to mongodb
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
# create database
mydb = myclient["mydatabase"]
# create collection of database(mydatabase)
mycol = mydb["customers"]
mydict = { "name": "John", "address": "Highway 37" }
# insert data into customer collec... |
9b71a4b6957c1cae6c277748ab9ca838f1ebcfc7 | cpsln/learning-challenge-season-3 | /bank_application.py | 1,157 | 4.03125 | 4 |
import sys
class Customer:
'''Customer class with bank related '''
bankname='Punjab national bank'
def __init__(self, name,balance=0):
self.name=name
self.balance=balance
def deposit(self,atm):
self.balance=self.balance+atm
print('After deposit the balanced:'... |
cc5c1fbd85f48af0aac76cfae1b582b474aeab85 | maruichen2004/LintCode | /Check_Power_of_2.py | 129 | 3.59375 | 4 | class Solution:
def checkPowerOf2(self, n):
if n <= 0: return False
return True if n & (n-1) == 0 else False
|
2397cfd6558c5641bdbab152a5bc50fd282ef918 | jyothiesai/guvij | /anagramplay.py | 175 | 3.515625 | 4 | #jyothi
n=int(raw_input())
li=[]
for i in range(0,n):
str=raw_input()
li.append(str)
c='kabali'
count=0
for i in li:
if(sorted(i)==sorted(c)):
count=count+1
print(count)
|
629e4a85aab4475bb088e663e144b83d4882a997 | jyothiesai/guvij | /binary.py | 136 | 3.6875 | 4 | #jyothi
b=raw_input()
flag=0
for c in b:
if((c == '0') or (c == '1')):
flag+=1
if(flag==(len(b))):
print("yes")
else:
print("no")
|
cc477a7ec767e67f36e12a7ed6edc2ff1f61c394 | jyothiesai/guvij | /max.py | 97 | 3.6875 | 4 | a=input()
b=input()
c=input()
if(a>b):
if(a>c):
print(a)
elif(b>c):
print(b)
else:
print(c)
|
ce31f508c8a134a7d3b160e7706dc6252507b756 | jyothiesai/guvij | /enco.py | 353 | 3.65625 | 4 | #jyothi
s=raw_input()
s=list(s)
a=[]
for i in s:
if i=="x":
a.append("a")
elif i=="y":
a.append("b")
elif i=="z":
a.append("c")
elif i=="X":
a.append("A")
elif i=="Y":
a.append("B")
elif i=="Z":
a.append("C")
else:
c=ord(i)
a.ap... |
8a450c968ba9a9e48f0aa963596378e75cc9fe0e | jyothiesai/guvij | /alphabet.py | 136 | 3.78125 | 4 | #jyothi
r=raw_input()
if(r>='a' and r<='z'):
print("Alphabet")
elif(r>='A' and r<='Z'):
print("Alphabet")
else:
print("no")
|
2eb52a42c37125937cbffd68468398956aa7d575 | foofaev/python-project-lvl1 | /brain_games/games/brain_progression.py | 1,454 | 4.25 | 4 | """
Mini-game "arithmetic progression".
Player should find missing element of provided progression.
"""
from random import randint
OBJECTIVE = 'What number is missing in the progression?'
PROGESSION_SIZE = 10
MIN_STEP = 1
MAX_STEP = 10
def generate_question(first_element: int, step: int, index_of_missing: int):
... |
abd3c335f31b3b5b847aca01e765b2ba0f6a75b1 | abrahamq/interviewStudy | /strings/reverseString.py | 458 | 4.0625 | 4 | #Reverse a String iteratively and recursively
def reverseIt(string):
newString = ""
backCounter = len(string)-1
for index, each in enumerate(string):
newString += string[backCounter]
backCounter -= 1
return newString
print reverseIt("abcd")
def reverseRecursive(string):
if len... |
d7ec50c692fa4b6d8269b6b47b7d93f7d3423878 | vzhernov/challenge101-python | /parse.py | 1,546 | 3.875 | 4 | #!/usr/bin/env python
#-*- encoding: utf-8
"""
Parse file with random data separated by comma.
Data contains alphabetical strings, integer numbers,
alphanumerics strings with spaces and real numbers in every row.
"""
import re
def parse(file="out.data"):
"""
Parse file with random data separated ... |
62b8553cd99274b0f0e48d38a5210e3f57bb1ef4 | Kevson102/Password-Locker | /credentials.py | 2,860 | 3.8125 | 4 | import string
import random
class Credentials:
'''
Class that generates a new instance of login credentials
'''
credential_list = []
def __init__(self, platform, login_username, login_password):
'''
__init__ method that helps use define the properties for a credential object.
... |
c64ccadc805d3ff5b521f693753605d98cecb416 | swapnilt/data_visualiser | /bg_jobs/csv_parser.py | 2,023 | 3.625 | 4 | import csv
import re
HEADERS = ['Year',
'JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN',
'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC']
DELIMITER = " "
class CSVParser(object):
def __init__(self):
self.result = []
def parse(self, file):
''' Accepts an open file object an... |
f872324d21334bbd9b7d6fff2d697e493a6b5481 | sridharreddy7/Algorithms-and-Data-Structures | /nextpermutation.py | 871 | 3.96875 | 4 | #!/usr/bin/python
# Author : Rajat Khanduja
# Finding the next permutation of a given number, i.e. using the same digits construct the permutation that it is the smallest number greater than
# the given number using only those digits.
def nextpermutation(n):
nString = str(n)
if len (nString) == 1:
return nS... |
5f1d89b45c61f68d2b23aa01bfb4c83d6e88fd1b | Sungmin-Joo/Python | /Matrix_multiplication_algorithm/Matrix_multiplication_algorithm.py | 1,284 | 4.1875 | 4 | # -*- coding: utf-8 -*-
import numpy as np
if __name__ == '__main__':
print("Func_called - main")
A = np.array([[5,7,-3,4],[2,-5,3,6]])
B = np.array([[3,0,8],[-5,1,-1],[7,4,4],[2,4,3]])
len_row_A = A.shape[0]
len_col_A = A.shape[1]
len_col_B = B.shape[1]
result = np.zeros((len_row_A,len_col_... |
90e42fac601b760a9c6755e359f7941a5b6bad50 | mtnekros/TeenPatti | /main.py | 732 | 3.65625 | 4 | import Hand
import Deck
def gameRound():
deck = Deck.Deck()
deck.shuffle()
hands =[]
# adding 5 player or hands of player in hand
for i in range(5):
hands.append([])
# distributing cards to player
for i in range(3):
for hand in hands:
hand.append(deck.drawCard())
for i,hand in enumerate(hands):
pr... |
0367c0c43eb41143ee1e79cc8df7995ab12c8e28 | andyly25/Python-Practice | /p12_favorite_languages.py | 446 | 3.5625 | 4 | from collections import OrderedDict
#This allows us to always get responses in order they were added
favorite_languages = OrderedDict()
favorite_languages['bob'] = 'python'
favorite_languages['bill'] = 'c'
favorite_languages['sarah'] = 'ruby'
favorite_languages['chris'] = 'python'
favorite_languages['mall'] = 'java'
... |
fbc118082a9af3f73ab1f86cfb95f2c65df13ee7 | andyly25/Python-Practice | /AlgorithmsAndChallenges/a012_sudokuChecker.py | 5,674 | 4.40625 | 4 | '''
Sudoku is a number-placement puzzle. The objective is to fill a 9 × 9 grid with
numbers in such a way that each column, each row, and each of the nine 3 × 3
sub-grids that compose the grid all contain all of the numbers from 1 to 9 one time.
Implement an algorithm that will check whether the given grid of number... |
1d55378e7153785bce2259c9218a83f6ef479ac3 | andyly25/Python-Practice | /AlgorithmsAndChallenges/a007_Queue.py | 1,432 | 4.03125 | 4 | class Queue:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def enqueue(self, item):
self.items.insert(0, item)
def dequeue(self):
return self.items.pop()
def size(self):
return len(self.items)
# Uncomment below if you wan... |
73d9af8a966990d3c06060b56516c7e22e637fda | andyly25/Python-Practice | /data visualization/e01_simplePlot.py | 761 | 4.34375 | 4 | '''
1. import pyplot module and using alias plt to make life easier.
2. create a lit to hold some numerical data.
3. pass into plot() function to try plot nums in meaningful way.
4. after launching, shows you simple graph that you can navigate through.
'''
# 1
import matplotlib.pyplot as plt
# input values will help ... |
bc1eff8bb9a9458b256853493b2efe8d70787abc | andyly25/Python-Practice | /AlgorithmsAndChallenges/a008_printingQueue.py | 5,688 | 4.25 | 4 | '''
From: http://interactivepython.org/runestone/static/pythonds/BasicDS/SimulationPrintingTasks.html
On any average day about 10 students are working in the lab at any given hour.
These students typically print up to twice during that time, and the length of
these tasks ranges from 1 to 20 pages. The printer in the... |
ca90a1f3a0461fddb1d5c55804beb0ffc58d5c1e | andyly25/Python-Practice | /p28_cityCountryFunction.py | 445 | 4.09375 | 4 | def getName(city, country):
cityCountryName = city + ", " + country
return cityCountryName.title()
def cityCountryFunction():
while True:
city = input("Please enter a city: ")
if city == 'q':
break
country = input("Please enter a country: ")
if country == 'q':
... |
69681798f10be785c5e6d247222832f32e7fcf91 | andyly25/Python-Practice | /AlgorithmsAndChallenges/a001_isEven.py | 1,008 | 4.34375 | 4 | '''
I've noticed the question of determining if a number is an even number
often, and it seems easy as you can just use modulo 2 and see if 0 or some
other methods with multiplication or division.
But here's the catch, I've seen a problem that states:
You cannot use multiplication, modulo, or divi... |
7eb1e5bf20db7776153f158af398397cae4a8402 | AyiTheDeer/GU_BigData_675 | /l6_task_1.py | 523 | 3.546875 | 4 | import time
class TrafficLight:
__colors = ['Red', 'Yellow', 'Green']
def running(self):
for i in TrafficLight.__colors:
if i == 'Red':
print('Режим Красный')
time.sleep(7)
elif i == 'Yellow':
print('Режим Желтый')
... |
d30bdd2fd19dc61d7328c4fca060d404de9d04da | AyiTheDeer/GU_BigData_675 | /23102020_task_5.py | 262 | 4 | 4 | my_list = [7, 5, 3, 3, 2]
new_number = 1
while new_number != 0:
new_number = int(input('Введите новое число рейтинга или 0 для отмены: '))
my_list.append(new_number)
my_list.sort(reverse=True)
print(my_list)
|
60bbe0185f49c88a91ed853ecc0f55ddafbf71a6 | igrekus/fiddle | /solutions_old/phone_one_liner.py | 274 | 3.609375 | 4 | def format_numbers(phone_number: str) -> str:
return ''.join([
one.replace(' ', '') + two.replace(' ', '')
for one, two
in zip(
'+7( ) - - ',
' ' + ''.join([c for c in phone_number if c.isdigit()])[1:]
)
])
|
e9bbeb487c2c17f12ecda5de0f3593eb5277945d | rahberisafi/python_learn | /11.py | 413 | 3.734375 | 4 | # import random
#
# game_over = False
# score = 0
#
# while not game_over:
# score += random.randint(1,10)
# print(score)
#
# if score < 50:
# continue
#
# if score > 100:
# game_over = True
# break
#
# print("You are getting close to winning")
# print("You Win!")
nums =... |
5f79b1c23fd43bdcf0fb45ce5780e8e9815537e5 | jkiyak/CS355-Probability-and-Statistics-in-Computer-Science- | /SP2019 CS 355_555-2E Probability/statsprogram5.py | 902 | 3.796875 | 4 | import matplotlib.pyplot as plt
import numpy as np
def math_formula(j):
math_formula = (1/3) * (j-1)**2
return math_formula
a = 0
b = 3
results = []
for value in range(a, b):
print ('For f(',(value),')', 'the number is:' , math_formula(value))
results.append(math_formula(value))
print... |
72a2f85eb49e733076fbf806bfda09ff8a3e4727 | marie-yau/Graph-Algorithms | /Kruskals.py | 2,110 | 3.75 | 4 | import networkx
"""
Finds minimum spanning tree of graph using Kruskal's Algorithm.
Arguments: G - reference to networkx graph
Return: minimumSpanningTreeEdges - list of edges of MST
Note: G
- can't have self loops (because of union-find algorithm)
- be undirected (because of union-find algorithm)
"""... |
3a9218ad81b17ba6ab6e3091c1912e66843a4fce | marie-yau/Graph-Algorithms | /Prims.py | 1,433 | 3.828125 | 4 | import networkx as nx
import math
"""
Finds minimum spanning tree of graph using Prim's Algorithm.
Arguments: G - reference to networkx graph
Return: minimumSpanningTreeEdges - list of edges of MST
Note: G
- can't have self loops
"""
def primsAlgorithm(G):
# create mstNodes and mstEdges that keeps track of... |
1a3689681b252e87b0c323aa73b32166bb3e8469 | oktaran/LPTHW | /exercises.py | 1,367 | 4.21875 | 4 |
"""
Some func problems
~~~~~~~~~~~~~~~~~~
Provide your solutions and run this module.
"""
import math
def add(a, b):
"""Returns sum of two numbers."""
return a + b
def cube(n):
"""Returns cube (n^3) of the given number."""
# return n * n * n
# return n**3
return math.pow(n, 3)
def is_od... |
8cfa65233bf2f593780ee1fadc13baa08ce9c2f7 | daiweili/google-games-2012 | /fp_util.py | 1,064 | 4 | 4 | import sys
def read_int():
return int(sys.stdin.readline())
def read_float():
return float(sys.stdin.readline())
def read_line():
return sys.stdin.readline()
def read_lines(n=1, func=None):
"""Reads n lines. Also applies the argument func to each line."""
result = []
for line in xrange(n):
... |
50694c9183859515472d50ac5eaba372c78be0a3 | HarshRathi1/Even_in_list | /main.py | 90 | 3.515625 | 4 | list=[32,56,18,11,47,92,2,90,55,71]
for i in list:
if i%2==0:
print(i,end=" ") |
7574b73273ffd790f50a79a16b222efe50d8186f | Lazy-yin/LeetCode-practice | /Questions/q0009Palindrome_Number/BruteForce.py | 182 | 3.625 | 4 | def isPalindrome(x):
if x >= 0:
num = str(x)
re_num = num[::-1]
return True if num == re_num else False
elif x > 2**31-1 or x<0:
return False |
c41c5999d0caa22932cd300dc30375aea4f48294 | Lazy-yin/LeetCode-practice | /Questions/q0007ReverseInteger/BruteForce.py | 529 | 3.5625 | 4 | def reverse(x):
if x==0:
return 0
if x > 0:
num = str(x)
ans = ""
for i in range(len(num)):
re_num = num[len(num) - i - 1]
ans = ans + re_num
ans = ans.lstrip("0")
return ans if int(ans) < 2**31 else 0
if x < 0:
num = str(x*(-1)... |
f5d37a7ba9f5aff3f421a4380564843b4727b1a1 | CoderMP/PythonPassGen | /PassGen.py | 3,661 | 3.75 | 4 | ####### REQUIRED IMPORTS #######
import os
import sys
import click
import random
import string
from time import sleep
####### FUNCTIONS ######
def displayHeader():
"""
() -> ()
Function that is responsible for printing the application header
and menu
"""
# Clear the console window
os.syste... |
658f6455321e714ce7902dc5facfdda2130b2172 | zafodB/aoc2020 | /aoc12.1.py | 1,302 | 3.5625 | 4 | def open_file(location:str='12.1.input.txt') -> list:
with open(location, 'r', encoding='utf8') as f:
input_lines = f.readlines()
return input_lines
def process_input(lines: list) -> list:
processed_input = []
for line in lines:
processed_input.append((line[0], int(line[1:].replace('\n... |
418c50fcf727eb4de23215290427dc5bc36a303e | zafodB/aoc2020 | /aoc10.2b.py | 1,177 | 3.65625 | 4 | def open_file(location:str='10.1.input.test.txt') -> list:
with open(location, 'r', encoding='utf8') as f:
input_lines = f.readlines()
return input_lines
def process_input(lines: dict) -> dict:
processed_input = []
for line in lines:
processed_input.append(int(line.strip(), base=10))
... |
e47421af33c62a9e2e81e0a84054de1abb763639 | zafodB/aoc2020 | /aoc12.2.py | 1,410 | 3.515625 | 4 | def open_file(location:str='12.1.input.txt') -> list:
with open(location, 'r', encoding='utf8') as f:
input_lines = f.readlines()
return input_lines
def process_input(lines: list) -> list:
processed_input = []
for line in lines:
processed_input.append((line[0], int(line[1:].replace('\n... |
89cd8a2e36b129a705836170fb6a0a48e4b6bbbb | ParthikB/Data-Structures | /Data Structures/quickSort.py | 1,428 | 4.125 | 4 | class Sort:
def __init__(self, list_):
self.list = list_
def quickSort(self):
pivot = -1
arr = self.list
def quickSortRecurse(arr):
l, r = 0, len(arr) - 2
# print("recursing :::::::::::::::::::::", arr)
... |
cd95a4699d0abb415eeb54459eb9bfc0c0ed6f54 | adatechschool/Matin | /alphabet/Del/alphabet.py | 204 | 3.546875 | 4 | import string
# -*- coding: utf-8 -*-
def minus(a="") :
return string.ascii_lowercase
def maj(b="") :
return string.ascii_uppercase
print(string.ascii_lowercase)
print(string.ascii_uppercase)
|
a7c29d07ecaff79c7890dc20d201dabd2c2c0213 | MksYi/Python3-NPCTU-TQC-Example | /Problem2/PYD02.py | 525 | 4.1875 | 4 | #-*- codeing: utf-8 -*-
import sys
"""
input
55
36
92
15
output
55 is a multiple of 5.
36 is a multiple of 3.
92 is not a multiple of 3 or 5.
15 is a multiple of 3 and 5.
"""
number = int(input())
anwser = 0
if not number % 3:
anwser += 3
if not number % 5:
anwser += 5
if anwser == 3:
print('%d is a multiple... |
e74cae08f43598373f80eaa7d1c096275be9f0ed | Xabierland/PB-Python | /Practica 4/Ejercicio7.py | 281 | 3.765625 | 4 | #inicializaciones
num=int(input("Introduce un numero binario que comience en 1: "))
exp=0
suma=0
#descomponer el numero binario y crear el decimal
while(num>0):
suma=suma + (num % 10)*2**(exp)
exp=exp+1
num=num//10
print("el numero en decimal es: ", + suma) |
21e85e2ab9a5e27ec98ecbd10b9b0b9b4fea3803 | Xabierland/PB-Python | /Practica 6/Ej8_posicion_en_matriz.py | 3,649 | 3.90625 | 4 | def posicion_en_matriz(M,num):
#entrada:una matriz M
#pre: M tiene al menos una fila y al menos una columna llena de enteros
#salida: dos enteros PosF y PosC
#post: si num esta en la matriz entonces PosF contiene el valor de la fila en la que est�
# y PosC la posici�n de la columna. Si Num aparece varias veces, se... |
4776c7c4664e109786151f825f59317cf33a1fb9 | mamege/SMI | /codegen/topology_file_generator.py | 1,389 | 3.703125 | 4 | '''
This program generates a dummy topology file. This can be used for testing or skeleton for topology files.
It takes in input the number of FPGAs, a list of program names, and the output file.
Programs are associated randomly to FPGAs, and FPGAs are connected in a bus.
'''
import json
import argparse
if __name... |
96f6627d4ab1fb86b797864a48c8d4cbc4388eb5 | nochemargarita/word_count | /wordcount.py | 555 | 3.828125 | 4 | def get_word_count(file): # initialize function that takes 1 arg as file
"""return word count from file"""
word_count = {}
with open(file) as txt_file:
for line in txt_file:
# line = line.strip()
words = line.split()
for word in words:
word_count[... |
fb013a2c05a4435c16a736270108bd89422dc3d8 | rw2409/LeetCode | /algo/src/wr/leetcode/algo/balanced_binary_tree/Solution.py | 578 | 3.6875 | 4 |
class Solution:
# @param root, a tree node
# @return a boolean
def isBalanced(self, root):
return self.balanceTree(root)[0]
def balanceTree(self, root):
if root is None:
balanced = True
height = 0
else:
(lb, lh) = self.balanceTree(root.left... |
bcb369678e7debc40c1ce49ab3e9d409f5e13d19 | vaibhavyesalwad/Basic-Python-and-Data-Structure | /Python Data Structure/Tuple/03_Unpacking.py | 351 | 4.4375 | 4 | """program to unpack a tuple in several variables"""
a, b, c = (4, 'hello', [1, 2, 3]) # unpacking of in several variables
print(a, b, c)
'''
x = (4, 'hello', [1, 2, 3]) # packing
(a, b, c) = x # unpacking
print(a, b, c)
a, _, c = x # ignoring 2nd item '_' holds 2nd item '_' used a... |
3a097f2425a884b0869818f8bf2646854f2ef6af | vaibhavyesalwad/Basic-Python-and-Data-Structure | /Basic Programs/Factorial.py | 556 | 4.25 | 4 | """Find factorial of given number"""
def fact(num):
if num < 0:
return 'factorial of negative number not possible'
elif num == 0:
return 1
else:
factorial= 1
for i in range(1, num+1):
factorial *= i
return factorial
def recurse_fact(num):
if num < ... |
7aa66e034df46248f0a8cc6d12617137533fc4ab | vaibhavyesalwad/Basic-Python-and-Data-Structure | /Python Data Structure/Strings/03_ReplaceChar.py | 377 | 4.1875 | 4 | """program to get a string from a given string where all occurrences of its first char have been
changed to '$', except the first char itself"""
string = 'restart'
ch = 'r'
i = string.index(ch) # using str.replace() method returns new string with all replacements
print(string[:i+1]+string[i+1:].replace(c... |
95d80104eebaad74f0a50ec4988336711279df4b | vaibhavyesalwad/Basic-Python-and-Data-Structure | /Basic Python/11_CheckFileExistence.py | 314 | 3.828125 | 4 | """Program to check whether a file exists"""
import os # using os module
if os.path.exists('01_FirstLastName.py'): # checks existence of given file
print('exists') # alternatively os.path.isfile('filename')
else:
print("doesn't exist")
|
1e2a001ae19935fad4a2272ec592ee8f1dbf9756 | vaibhavyesalwad/Basic-Python-and-Data-Structure | /Python Data Structure/Tuple/08_RemoveItem.py | 326 | 4.03125 | 4 | """Program to remove an item from a tuple"""
# Tuple is immutable data type cannot be changed once created
tuple1 = (1, 'abc', [1, 2, 3], 4.5) # however we can edit mutable items in tuple but cannot delete them
tuple1[2].clear()
print(tuple1) # we cannot add or remove from tuple so no no methods for addition or del... |
546f755653d647de1c8afec21f7b630aab5ef626 | vaibhavyesalwad/Basic-Python-and-Data-Structure | /Python Data Structure/Dictionary/13_CountValuesAsList.py | 343 | 4.125 | 4 | """Program to count number of items in a dictionary value that is a list"""
dict1 = {'a': [1, 2, 3, 4], 'b': [2, 3, 4, 5], 'c': 1, 'd': 'z', 'e': (1,)}
# if value is list added True i.e. 1 else False i.e. 0
count = sum(isinstance(value, list) for value in dict1.values()) # sum fn & generator expression
print(f'{co... |
cc78b9eb895b92a82487d4ac4c6961a23fe98222 | vaibhavyesalwad/Basic-Python-and-Data-Structure | /Pattern Programs/PascalTriangle.py | 460 | 4.03125 | 4 | """Print Pascal triangle"""
lines = int(input('Enter number of lines:'))
num = [1]
for i in range(1, lines+1):
spaces = ' '*(lines-i)
print(spaces, end='')
for j in num:
print(j, end=' ')
print()
numbers = []
numbers.append(num[0]) # Creating list of numbers for next line
... |
25778e07eadbe6059b64b6d79cc384bc7150525c | vaibhavyesalwad/Basic-Python-and-Data-Structure | /Python Data Structure/Dictionary/01_SortByValue.py | 418 | 4.4375 | 4 | """Sort (ascending and descending) a dictionary by value"""
d = {'a': 26, 'b': 25, 'y': 2, 'z': 1}
# to access and map key value pairs dict.item gives list of tuples of key, value pairs
print(f'Ascending order by value {dict(sorted(d.items(),key=lambda x: x[1]))}') # using second element of tuple
print(f'Descending or... |
dcca3f992e91118ce37e7bb14a2942cef6ea431c | vaibhavyesalwad/Basic-Python-and-Data-Structure | /Sorting Algorithms/InsertionSort.py | 488 | 4.15625 | 4 | """Sort numbers in list using Insertion sort algorithm"""
numbers = [int(i) for i in input('Enter list of numbers:').split()]
print(numbers)
for i in range(1, len(numbers)): # first element already sorted
j = i # insert element at j index in left part of array at it's appr... |
f1e12f47cef4461772af1874a120adba05fc2315 | vaibhavyesalwad/Basic-Python-and-Data-Structure | /Python Data Structure/Strings/01_LengthOfStr.py | 152 | 4.28125 | 4 | """Program to calculate the length of a string"""
string = 'BridgeLabz'
print(f'Length of {string}: {len(string)}') # using len fn for iterables
|
3f5fb3bf42152fcc6dad000d5870f6c4e9a8522d | vaibhavyesalwad/Basic-Python-and-Data-Structure | /Python Data Structure/List/01_SumList.py | 185 | 4.1875 | 4 | """Program to sum all the items in a list"""
numbers = [10, 11, 12, 13, 14] # created list
print(f'Sum: {sum(numbers)}') # sum fn takes iterables & return sum of elements
|
bd82d68d4b74dcfa8a03e9d9b8a2242ebf443ee8 | vaibhavyesalwad/Basic-Python-and-Data-Structure | /Basic Python/34_FileProperties.py | 449 | 3.796875 | 4 | """Program to retrieve file properties"""
import os, time
print('05_PrintCalendar.py') # file of which properties are to be displayed
print(f'Access time: {time.ctime(os.path.getatime("05_PrintCalendar.py"))}')
print(f'Modified time: {time.ctime(os.path.getmtime("05_PrintCalendar.py"))}')
print(f'Change time: ... |
2127b4a4cfb2f88561608be17b515940515974bb | vaibhavyesalwad/Basic-Python-and-Data-Structure | /Basic Python/41_IntToBinary.py | 212 | 3.984375 | 4 | """Program to convert an integer to binary keep leading zeros"""
num = 50
print(format(num, "010b")) # using format function
print(format(num, "012b")) # total digits 10 & 12 these are right aligned
|
33bb259270a1bc8fd006b9f441a6b3267cff63b5 | vaibhavyesalwad/Basic-Python-and-Data-Structure | /Python Data Structure/List/06_RemoveDuplication.py | 205 | 4.15625 | 4 | """Program to remove duplicates from a list"""
numbers = [10, 15, 15, 20, 50, 55, 65, 20, 30, 50]
print(f'Unique elements: {set(numbers)}') # set accepts only unique elements so typecasting to set
|
b694f5622bda25f61b37ec3c3cb4d88bb9458b25 | vaibhavyesalwad/Basic-Python-and-Data-Structure | /Basic Programs/LeapYear.py | 295 | 4.09375 | 4 | """Check whether input year is Leap year or not"""
year = input('Enter year:')
y = int(year)
if len(year) != 4:
print('Invalid year')
elif y % 4 == 0:
if y % 100 == 0 and y % 400 != 0:
print('Not leap year')
else:
print('Leap Year')
else:
print('Not leap year')
|
fbc4a8343b2d4d08da11b0b7b0deea955c74730d | ayatjamhour/python_stack2 | /_python/python_fundamentals/forloop python/countdown4.py | 85 | 3.671875 | 4 | x=2018
while x>0 :
print(x)
x-=4
#or
for i in range(2018,0,-4):
print(i) |
4535da93f29b98f1b24f7c14558e5841bf1d9f6a | andreskask/taller-recursividad | /4. potencia.py | 256 | 3.6875 | 4 | def inicio():
print potencia(int(input("potencia:\ningrese base: ")), int(input("ingrese exponente: ")))
raw_input("enter para salir")
def potencia(base, exp):
if exp == 0:
return 1
else:
return base * potencia(base, exp - 1)
inicio() |
dc71d4e5f227279b612b7e472d2286ac5f694554 | andreskask/taller-recursividad | /5. producto.py | 292 | 3.8125 | 4 | def inicio():
print producto(int(input("producto:\ningrese primer factor: ")), int(input("ingrese segundo factor: " )))
raw_input("enter para salir")
def producto(numero1, numero2):
if numero2 == 0:
return 0
else:
return numero1 + producto(numero1, numero2 - 1)
inicio() |
684000bf2d4099a0e122b61c0d87e92de3e8455c | ilyaaltshteyn/abstracts | /Analysis/gender studies/5_sexism_over_time_chisq.py | 13,349 | 4.21875 | 4 | # This script separates out the columns of data that have the author genders
# and names, as well as the columns for years and author counts.
# It then runs a chi squared test on the proportions of male and female
# authors who are first auth vs second vs third vs last.
# Here's a link to an explanation of how to d... |
206f4b24f191fa2d8ba51e80200d41182b33e0c5 | ashishraste/leetcode | /hackerrank/tree/preorder_traversal.py | 316 | 3.515625 | 4 | from tree import *
def preOrder(root):
print(root.info, end=' ')
if root.left != None: preOrder(root.left)
if root.right != None: preOrder(root.right)
tree = BinarySearchTree()
t = int(input())
arr = list(map(int, input().split()))
for i in range(t):
tree.create(arr[i])
preOrder(tree.root) |
d05c9f26087bb9d5f65dfdb377b616458b3b0eda | ashishraste/leetcode | /hackerrank/tree/height.py | 298 | 3.75 | 4 | from tree import BinarSearchTree
def height(root):
if not root:
return 0
return 1 + max(height(root.left), height(root.right))
tree = BinarySearchTree()
t = int(input())
arr = list(map(int, input().split()))
for i in range(t):
tree.create(arr[i])
print(height(tree.root)) |
bd9d960042a43cc5656f14d23783e77e363d45c3 | tozuka/python_de_asobo | /wavelet/onde009.py | 2,516 | 3.78125 | 4 | # -*- coding: utf-8 -*-
import math
import numpy as np
#import matplotlib.pyplot as plt
from pylab import *
# 1.1 簡単な近似
def phi(lower,upper):
def fn(r):
if lower <= r < upper:
return 1
else:
return 0
return fn
def data2fn(data):
m = len(data)
lower = data[0][0]
unit = data[1][0] - data[... |
79cd83079e88f7d62fc64f5398d00bb70cabf4f7 | Bakalavr163/Alexander_Donskoy | /Easy_homework 6.py | 2,992 | 4.46875 | 4 | # Задача-1:
# Следующая программа написана верно, однако содержит места потенциальных ошибок.
# используя конструкцию try добавьте в код обработку соответствующих исключений.
# Пример.
# Исходная программа:
def avg(a, b):
"""Вернуть среднее геометрическое чисел 'a' и 'b'.
Параметры:
- a, b (in... |
dbee0178d9f3fd4bd13a653f102b94e1ec8a99b7 | iOSGonzo/CS2.2 | /tests/test_graph_adt.py | 6,758 | 3.625 | 4 | import unittest
from graphs.graph import Graph
from util.file_reader import read_graph_from_file
class TestGraph(unittest.TestCase):
def test_create_directed_graph(self):
"""Create a graph."""
graph = Graph(is_directed=True)
vertex_a = graph.add_vertex('A')
vertex_b = graph.add_ve... |
2c29f555bd6e6376a8b7a7325c8eb5eefdd7b85f | akashjain15/hackerrankpythonpractice | /tw.py | 379 | 3.703125 | 4 | import textwrap3
def wrap(string, max_width):
wraper = textwrap3.TextWrapper(width=4)
word_list = wraper.wrap(text=string)
a =''
for i in range(len(word_list)):
a += word_list[i]
a += '\n'
return a
if __name__ == '__main__':
string, max_width = input(), int(input(... |
97f56c1b9ba3ab9c211e3b1961773e391e1b7431 | davidshato/gitTest | /exes/grep.py | 518 | 3.875 | 4 | #!/usr/bin/python3
import sys
import os
def USAGE():
print(os.path.basename(sys.argv[0])+" USAGE: <WORD> <PATH>");
sys.exit(1)
if(len(sys.argv) != 3):
USAGE()
if(not os.path.isfile(sys.argv[2])):
USAGE()
fileName = open(sys.argv[2],"r")
searchWord = sys.argv[1]
found = False
linesList = fileName.r... |
acc0372f334ce798481ae829854ef76d41b8ffc5 | Imperial-iGEM/Intro-to-Modelling-Code | /CCh_Binding.py | 3,019 | 3.75 | 4 | #Example code for Introduction to Mathematical Modelling in Synthetic Biology Package
#Written by Gabriel Swallow, Imperial College London
#####
#Import the modules and submodules necessary for the code
#####
import scipy as sp #Fundamental module for science
import matplotlib.pyplot as plt #Module... |
3a8f69f325380b1fbeac1b91dc7f6e3f1e70eb16 | AntonVopilov/EPAM_VacuumCleaner | /robot.py | 6,945 | 3.71875 | 4 | from curses import KEY_RIGHT, KEY_LEFT, KEY_DOWN, KEY_UP, KEY_F1, KEY_F2
import body
class Robot:
"""
Возвращает объект роботы
x, y - начальное положение
width - ширина робота
length - длинная робота
"""
def __init__(self, x, y, width, length):
if any(not isinstance(arg, int) for ... |
74207f09ecbe9354d93ace2c3d0edd34613997fb | thesayraj/DSA-Udacity-Part-II | /Project-Show Me Data Structures/problem_2.py | 863 | 4.21875 | 4 | import os
def find_files(suffix = "", path = "."):
"""
Find all files beneath path with file name suffix.
Note that a path may contain further subdirectories
and those subdirectories may also contain further subdirectories.
There are no limit to the depth of the subdirectories can be.
... |
14badb5a4ae1aa7e0180f90671e8ea1c2b972f75 | HowardOhMyGod/Python_Learning_Resource | /decorator/setter.py | 570 | 3.671875 | 4 | class Employ:
def __init__(self, first, second):
self.first = first
self.second = second
@property
def fullname(self):
return '{} {}'.format(self.first, self.second)
@property
def email(self):
return f'{self.first}.{self.second}@example.com'
@fulln... |
013e5bf72775480c60f3468d8a91be448b3ec264 | atiffaiz1/Coursework_Git | /Algo_design_analysis_part1/PA1/PA1.py | 1,019 | 3.59375 | 4 | # -*- coding: utf-8 -*-
def sort_n_count(A,length):
if length==1:
return A,0
else:
L=A[:length/2]
R=A[length/2:]
L_len=length/2
R_len=length-L_len
sorted_L, X = sort_n_count(L,L_len)
sorted_R, Y = sort_n_count(R,R_len)
sorted_A, Z = merge_n_coun... |
f74e8815aa8dc489cd0cd6e93f6cf6eafb5bf7d8 | jaredbriskman/ComputationalArt | /recursive_art.py | 4,772 | 4.0625 | 4 | """ Without 'art', 'earth' is just 'eh' """
import random
from PIL import Image
import math
import numpy
def build_random_function(min_depth, max_depth):
""" Builds a random function of depth at least min_depth and depth
at most max_depth (see assignment writeup for definition of depth
in this con... |
e5ede95b3363e864762c13cea5faa77908c3ca92 | VhI3/THBSplines | /THBSplines/src/abstract_space.py | 801 | 3.53125 | 4 | from abc import ABC, abstractmethod
from typing import List, Union
import numpy as np
class Space(ABC):
@abstractmethod
def cell_to_basis(self, cell_indices: Union[np.ndarray, List[int]]) -> np.ndarray:
"""
Given a list of N cell-indices, return a list of N lists, such that the i'th list giv... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.