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 |
|---|---|---|---|---|---|---|
5b849c1bb9cb4c4a8267c20266b29d70209ec896 | yolanda7975/cs1 | /code/python/example.py | 434 | 3.90625 | 4 | # assignment commands
# {}
x=5
#{(x,5)}
y=6
#{(x,5),(x,6)}
#conditions
if (True):
x = 0
z = 10
else:
x = 1
z = 11
#{(x,0),(y,6),(z,10)}
if (x>0 or y==x): #x > 0 or y=x; v=or
x = 0
z = 10
else:
x = 1
z = 11
# iteration
times = 10
while (times > 0):
print ("hello")
time... |
154245edb4b3af080ca00814300052f46d757bf3 | arpandhakal/python_powerworkshop | /jan 19/functions/14.py | 218 | 3.828125 | 4 | def digit_sum(x):
t=0
for i in range(0,len(str(x))):
t=t+(x%10)
x=x//10
if x ==0:
break
return t
a=int(input("number"))
print("sum of the digits",digit_sum(a))
|
a13889344aadadd277384472646633db71007bcf | arpandhakal/python_powerworkshop | /assignment-python/4.py | 123 | 3.9375 | 4 | name = input ("enter first name")
surname= input ("enter last name")
print ("Hello! {0} {1}.".format(name,surname))
|
5000d8bba3d5d1722d42c0cc9fe80d49ef6de9d0 | arpandhakal/python_powerworkshop | /assignment-python/3.py | 134 | 3.703125 | 4 | print ("given v= 25m/s, u=0m/s, t=10, a=?")
v=25
u=0
t=10
a= (v-u)/t
print ("25= 0+a*10")
print ("a= 25/10")
print ("a=",a)
|
859a9663643bbc151faef36842865eb92a40dabf | Mak3yrM0v3/awesome-hacktoberfest | /Sasso_Carta_Forbice/game.py | 782 | 3.84375 | 4 | import random
def getUserChoice():
userChoice = str(input("sasso carta o forbici? (s, c, f)"))
if userChoice == 's' :
print("hai scelto: sasso")
return 1
elif userChoice == 'c':
print("hai scelto: carta")
return 2
elif userChoice == 'f':
print("hai scelto: forbici")
return 3
else:
print ("solo s, c... |
eac6bded499f5d733fb31160cdbf695e9d22ee4c | yemaa/First-Python | /bubbleSort.py | 382 | 3.8125 | 4 | #Input variabili
x = float(input("Dimmi un numero: "))
y = float(input("Dimmene un altro: "))
z = float(input("Dimmene un altro ancora: "))
#Controllo ordine numeri
if y > z:
a = y
y = z
z = a
if x > y:
b = x
x = y
y = b
if z < y:
c = y
y = z
z = c
#Stampa a schermo dei numeri
p... |
009d9d860a53f27ea8e6835a76790c5608797b1e | H-H2648/Hangman | /Hangman.py | 2,971 | 4.09375 | 4 | import turtle
import random
def draw(hanger, check):
if check == 0:
hanger.left(90)
hanger.forward(200)
hanger.right(90)
hanger.forward(50)
hanger.right(90)
hanger.forward(10)
if check == 1:
hanger.right(90)
hanger.circle(30)
... |
9f204b51f1fa854ee67580a4418c1bcfb1b2ec16 | masakiaota/cythonbook | /02-compiling/distutils/fib_py.py | 130 | 3.8125 | 4 | def fib(n):
'''Returns the nth Fibonacci number.'''
a=0; b=1;
for i in range(n):
a, b = a + b, a
return a
|
8c93713fd7b702fccc6a44b85e4a4a139e45b35f | akarsh033/ANN_for_classification | /artificial_neural_network_for_classification.py | 5,460 | 3.6875 | 4 | # -*- coding: utf-8 -*-
### Importing the libraries
"""
#Google Colab already comes installed with tensorflow but we must import it
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#To check if tensorflow library is loaded
tf.__version__
"""## Part 1 - Data Preprocessin... |
2cf44544416695b9b76de51c2ea21396e0001ba2 | haruspring-jokt/practice-udemy-python3 | /sec_4/tuple_2.py | 263 | 3.625 | 4 | # coding: utf-8
# d = {'x': 10, 'y': 20}
# print(type(d))
#
# print(d['x'])
# print(d['y'])
#
# d['x'] = 100
#
# print(d)
chose_from_two = ('A', 'B', 'C')
answer = []
answer.append('A')
answer.append('C')
print(chose_from_two)
print(answer) |
71ceda8b62f003757a62896be33d630cdb926c7d | haruspring-jokt/practice-udemy-python3 | /sec_5/func.py | 1,196 | 3.96875 | 4 | # def say_something():
# s = 'hi'
# return s
#
#
# f = say_something()
# print(f)
# def what_is_this(color):
# if color == 'red':
# return 'tomato'
# elif color == 'green':
# return 'green pepper'
# else:
# return "I don't know"
# # print(color)
#
#
#... |
657059694c02b9c1716622c22102994455de1637 | haruspring-jokt/practice-udemy-python3 | /sec_5/error_handling.py | 672 | 3.609375 | 4 | # l = [1, 2, 3]
# i = 5
# # del l
#
# try:
# l[0]
# except IndexError as exc:
# print("don't worry {}".format(exc))
# except NameError as exc:
# print(exc)
# except Exception as exc:
# print('other: {}'.format(exc))
# else:
# print('done')
# finally:
# print('clean up')
#
# # pr... |
3e76205093c85d217a145d8939b0b3fdf8d1c64f | rchicoli/dnsupdate | /config/__init__.py | 1,074 | 3.640625 | 4 | import json
class Config(object):
"""
Config loads JSON config file to config variable
Args:
config_file: /tmp/config.json
config: {
"key": {
"rndc-key": {
"algorithm": "hmac-md5",
"secret": "63fT/4K3NrA0I9S... |
ed5a43afc29711ee2417a2d8b29f594edbb3155d | dominiqueacuna/PHYS-243 | /Appendix B Final Project | 2,380 | 3.625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 22 21:18:14 2019
@author: dominiquecacuna
Find the simplest Neural network for the following set of inputs:
1. {X3,X4}
2. {X3,X5}
3. {X3,X4,X5}
4. {X1,X2,X3,X4,X5}
"""
from keras.layers import Dense
from keras.models import Sequential
from keras.... |
43a496b8ad53a4aac72bed19df3331e8e865b04d | harveymei/learnpython3 | /ex24.py | 2,255 | 3.578125 | 4 | # -*- coding: utf-8 -*-
#打印,使用转义字符\‘转义单引号,\\转义一个斜线,\n换行,\t制表符
print "Let's practice everything."
print 'You\'d need to know \'about escapes with \\ that do \n newlines and \t tabs.'
#定义一个变量,使用三引号中的内容进行赋值
poem = """
\tThe lovely world
with logic so firmly palanted
cannot discern \n the needs of love
nor comprehend pass... |
6dcb69e476c545f96dde68f540945086819c8cda | WinnerLEEQQ/PythonSourceCode | /untitled0.py | 429 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jul 16 15:58:48 2021
@author: winner
"""
column, row = 3, 5
array2D = [[0 for _ in range(row)] for _ in range(column)]
print(array2D)
'''
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
'''
array2D = [[0 for _ in range(row)]]
print(array2D)
'''
[[0,... |
ace805408ea3e8d9a8818aba1e81003cb42a9109 | jarretraim/euler_py | /1-10/05.py | 458 | 3.828125 | 4 | #!/usr/bin/env python
import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
TOP = 20
def check_divisible(num):
for i in range(2, TOP):
if num % i != 0:
return False
return True
def main():
current = TOP
pager = 0
while True:
if (check_divisible(current)):
print ("Smallest %d" % current)
... |
83512d9a772fc65d22c190eba13fb05eea635de4 | jarretraim/euler_py | /21-30/30.py | 517 | 3.625 | 4 | #!/usr/bin/env python
from __future__ import print_function
import sys
# MAYBE DONE
# [4150, 4151, 54748, 92727, 93084, 194979]
# Sum: 443839
def power_sum(num, power):
s = str(num)
sum = 0
for i in s:
sum += (int(i) ** power)
return sum
def main():
print("1634 = %d" % power_sum(1634, 4))
print("8208 = ... |
2dc5666229f3fae65543fe7e8a61d18af3b5f87d | buba329/qwerty | /treogolniktwo.py | 250 | 3.875 | 4 | a=2
while a%2==0:
a=int(input("Введите число: "))
for i in range(1,a+1):
for q in range(1,a+1):
if (q>=i and q>a-i) or (q<=i and q-1<=a-i):
print("*",end="")
else:
print(end=" ")
print() |
ad90bd668f65d8ca224250768e1d281153af9f43 | buba329/qwerty | /factorial.py | 152 | 3.765625 | 4 | a=int(input("Введите число: "))
x=1
print(f"Факторисал числа {a} равен: ",end="")
while a!=0:
x*=a
a-=1
print(x) |
d33d0d59a47ec975f34949c52fb253eb47c30ae7 | buba329/qwerty | /massivtwo.py | 782 | 3.65625 | 4 | import random
arr=[]
def search(arr,n):
res=[]
for i in range(len(arr)):
if arr[i]==n:
res.append(i)
return res
x=int(input("Сколько элементов должно быть в массиве? "))
for i in range(x+1):
a=random. randint(1,100)
arr.append(a)
def print_arr(arr)
for i in range(x):
... |
c193e5c3fe3cd66e64c2ccf22dc566b01a25ce4c | Ekpreet-kaur/python-files | /venv/python19.py | 132 | 4.0625 | 4 | # sets in python
students = {"john","jack","joe"}
print(students,type(students))
# 1. concatenation
print(students + {"ok","bye"}) |
234fd73fe7facee859d6545a424d1ffcfb5fb4d0 | Ekpreet-kaur/python-files | /venv/python9.py | 216 | 4.1875 | 4 | #assignment operators
num1 = 10 #write operation/ update operation
num1 = 5
num2 = num1 #copy operation |refernce copy
#num1 = num1 + 10
num1 += 5
#print(num1)
# *=,/=,//=,*=,**=
num1 **= 2
num1 //= 2
print(num1) |
4611cf496cce260adc1c2c86889da4584e7f03dd | Ekpreet-kaur/python-files | /venv/python23.py | 173 | 3.5 | 4 | # list
names = ["john","fionna","kia"]
names[0] = "watson"
print(names)
"""
# tuple // # immutable
names = ("john","fionna","kia")
names[0] = "watson"
print(names)
""" |
a36ba54b9756a6e30d8566d590e468ce8fd72793 | CowieBunga/RealWordSearch | /1.1 File I/AOL Unit 1.py | 7,916 | 4.46875 | 4 | import random
'''
#######################################################
####################---Functions---####################
#######################################################
'''
'''
this function displays the board. see comments/code below for details
'''
def display(wordsearch, size):
for row in ra... |
7561e8c26d3366bb10f4b7927efa56f07e3d6a96 | SunshinePalahang/Assignment-2 | /program2.py | 257 | 3.953125 | 4 | apple = int(input("How many apples? "))
orange = int(input("How many oranges? "))
apple_price = 20
orange_price = 25
apple_total = apple*apple_price
orange_total= orange*orange_price
total= apple_total+orange_total
print(f"The total amount is {total}.")
|
357105435cab6cc4a1303825d62461e0774528db | Knorax/Lennyfuck_interpreter | /Python/interpreter.py | 1,022 | 3.8125 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
import sys
from CodeManager import *
import copy
# Interprets the Lenny code and converts it to python
def interpret(path):
# Open file to read the code from
f = open(path, "r")
# Read content
code = f.read()
# Print the code as is
#print(code)
... |
b11ddc742daa3e6275b7ddec32fc4c89f34efce6 | 19pa1a05g5/Ml-designchatbot | /project_1.py | 3,990 | 4.375 | 4 |
#This a program for a chatbot(seven wonders for children)
#Step_1:The bot will start with a greeting and self introduction and ask for the user(child) information like name , age and class etc..
#Step_2:The bot will greet and welcome the user(child)
#Step_3:Bot will ask what a child want to know about the seven ... |
ba57b2742a652a01ac79b8fc5ca4987d68fe0daa | kendrasteitz/Python138 | /CircleButton.py | 3,200 | 4.1875 | 4 | # Exercise No. 3
# File Name: CircleButton.py
# Programmer: Kendra Steitz
# Date: November 5, 2016
#
# Problem Statement:
# Do everything the same as project one, but change the buttons used
# from rectangles to circle. Use the CButton class created.
#
# Overall Plan:
# 1. Create a window and s... |
646d9a52f472c85a39353da67de016c0a27a58df | kendrasteitz/Python138 | /BaseConversion.py | 1,316 | 4.09375 | 4 | # Exercise No. Extra Credit
# File Name: BaseConversion.py
# Programmer: Kendra Steitz
# Date: November 25, 2016
#
# Problem Statement:
# Allow user to enter a number and a base for it.
# Using recursion output the digits of that number using the base given
#
# Overall Plan:
# 1. ask user for nu... |
dbb88fee57d6fd90ee3cf19b5cbff5ad55bd89da | kendrasteitz/Python138 | /cbutton.py | 1,456 | 3.8125 | 4 | # Exercise No. 2
# File Name: cbutton.py
# Programmer: Kendra Steitz
# Date: November 5, 2016
#
# Problem Statement:
# Create a CBottun class that create circular buttons
# rather than rectangle ones.
#
# Overall Plan:
# 1. Used the Button class provided as the general setup
# 2. Change the wi... |
47fd010ee758f642740d76f7cfd3c5d879406967 | SamirIngley/Spaceman | /spaceman.py | 5,716 | 4.3125 | 4 |
from random import choice
def load_word():
'''
Fn reads text file of words and selects one randomly (secret word).
Returns:
string: the secret word to be used in the game
'''
f = open('words.txt', 'r') # opens words.txt and returns as file. r = read
words_list = f.readlines() ... |
e1a0aa46e9698f6ec3aee9ff4e837c3ba667a841 | botaoap/python_db_proway_2021 | /aula3/getter_setter/getter_setter.py | 546 | 3.5625 | 4 | class Escritor:
def __init__(self, nome, livros ) -> None:
self.__nome = nome
self.__livros = livros
def get_nome(self):
return self.__nome
def get_livros(self):
# for list comprehension
return [livro for livro in self.__livros]
def set_nome(self, valo... |
666f8bb05281aa9bf11fbf8d909d7e58ce0c3961 | botaoap/python_db_proway_2021 | /aula5/revisao/exercicio/exerc_4.py | 1,390 | 3.875 | 4 | # Crie uma classe de produto e uma classe que de categoria
# Essa classe de cateogria devera ser passada para um metodo
# de registro de produto da classe Produto
# Exemplo
# >>>> produto = Produto()
# >>>> categoria = Categoria("Limpeza")
#
# >>>> produto.registrar_produto("Sabao em pó", 17.50, categoria)
# >>>> prin... |
8d9d40f748d8351017fe52bef8296c45a8bbea76 | botaoap/python_db_proway_2021 | /aula2/class/classes.py | 943 | 4.15625 | 4 | """
classmethod - staticmethod - dcorators
"""
class MinhaClasse:
def __init__(self, nome, idade) -> None:
self.nome = nome
self.idade = idade
def __repr__(self) -> str:
return f"{self.nome}, {self.idade}"
def metodo_de_instancia(self):
print(f"Eu sou uma classe {s... |
77181ee32df9fc60121bcdb41aca5717c4245405 | HarrietLLowe/python_turtle-racing | /turtle_race.py | 1,278 | 4.28125 | 4 | from turtle import Turtle, Screen
import random
is_race_on = False
screen = Screen()
screen.setup(width=500, height=400)
user_bet = screen.textinput(title="Make your bet", prompt="Which turtle will win the race? Enter a colour: ")
colors = ["red", "orange", "yellow", "green", "blue", "purple"]
turtles = []
for x in r... |
54eb346a971ed9109a0858d71edc04d66203c3bb | lamsnakesgit/42bootcamppython | /ex02/whois.py | 531 | 3.78125 | 4 | import sys
import re
# isinstance might be used
if len(sys.argv) < 2:
exit()
if len(sys.argv) > 2:
print('ERROR')
exit()
else:
result = re.match("[-+]?\d+$", sys.argv[1])
#if sys.argv[1].isdigit() == 0:
# if sys.argv[1].isnumeric() == 0: # fails
if result == 0:
print('ERROR')
... |
2e4e5a00bae8c7be7fe5dd601ba4fa21193ea564 | sittipongkogkaew123/python101 | /test.py | 505 | 3.9375 | 4 | def check_temp():
if t < 15:
return("So cold!")
elif t < 30:
return("It's a good day.")
elif t < 40:
return("So hot!!")
if __name__ == '__main__':
t = input("Enter your temperture :")
while t !='q':
if t.isnumeric():
t = int(t)
print(check_te... |
4f108c73e20dc971a1c613a1fb611421159bdaa9 | paulthomas2107/PythonCourseWork | /Exceptions.py | 948 | 4.09375 | 4 | # Exceptions
"""
x = -5
if x < 0:
raise Exception('X should be positive')
print('-' * 100)
x = -1
assert (x > 200), 'x is not positive'
print('-' * 100)
"""
try:
a = 5 / 0
b = 10 / 2
b = b + 1
except ZeroDivisionError as e:
print('Error found:', e)
except TypeError as e:
print('Error found... |
e842657194d0c5c8fe20011a691e8ee0cd231101 | paulthomas2107/PythonCourseWork | /strings.py | 2,445 | 3.78125 | 4 | # Immutable (cant be changed)
import timeit
m1 = 'Paul'
# or double quotes
m2 = "Paul Thomas is my name"
print(m2)
charPos = m2[1] # a
print(charPos)
charPos = m2[-1] # s
print(charPos)
chunk = m2[2:8] # from 2 to 8
print(m2[1:]) # from 1
print(m2[:8]) # to 8
print(m2[::2]) # every 2nd char
print(m2[3::2]) # e... |
73a593e1c0b4bfbe4d24c56b56a08586e2d25783 | Arcane2801/DukeTip | /Hangman.py | 1,122 | 3.78125 | 4 | #Code for Hangman:)
import numpy
return True
def input_answer(answer):
if len(answer) == 1:
answer= answer.lower()
exit= False
return answer
else:
print "Try again, only one letter at a time"
exit= True
word_list=["bomb","jelly","desktop","mangosteen"]#Later
#raw_in... |
becb831554b3c8e678f0450b7db618e008270fb7 | JohnRamonetti/Election_Analysis | /python_practice.py | 1,576 | 4.125 | 4 | # print("Hello World")
# print("Hello world")
# counties = ["A","B","C"]
# # print(counties[1])
# print(len(counties))
voting_data = []
voting_data.append({"county":"Arapahoe", "registered_voters":422829})
voting_data.append({"county":"Denver", "registered_voters":463353})
voting_data.append({"county":"Jefferson","r... |
28d4c117c564ad0926fafd890f182ec7c3938c22 | Deepu14/python | /cows_bulls.py | 1,637 | 4.28125 | 4 | """ Create a program that will play the “cows and bulls” game with the user. The game works like this:
Randomly generate a 4-digit number. Ask the user to guess a 4-digit number.
For every digit that the user guessed correctly in the correct place, they have a “cow”.
For every digit the user guessed correctly in the ... |
cf57b231429de69c5d05f681212c3edccae09bad | Oking123/LeetcodeContest | /L0004.py | 333 | 3.546875 | 4 | from typing import List
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
def divide(nums1, nums2):
if not nums1:
nums1 = nums2
return
sl = Solution()
A = [1,2,4,6,7,8]
B = []
print(sl.findMedianSorted... |
afc8de31941c10390ec77bbbee9c19c5da64a00e | tchvsps/python_learn | /ex21.py | 693 | 4.0625 | 4 | def add(a,b):
print "ADDING %d + %d" % (a,b)
return a+b
def substract(a,b):
print "SUBSTRACT %d - %d" % (a,b)
return a-b
def multiply(a, b):
print "MULTIPLY %d * %d" % (a, b)
return a*b
def divide(a, b):
print "DIVIDE %d / %d" % (a, b)
return a/b
print "Let's do some math with just f... |
71d71441cb2f237faccc316ee81e0dee02f45f2c | angelabanko/Python-Challenge | /PyBank/Main.py | 1,748 | 4 | 4 | # import os and csv to be able to read csv files
import os
import csv
dirname = os.path.dirname(__file__)
csvpath = os.path.join(dirname,'Resources', 'budget_data.csv')
with open(csvpath) as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
# number of months in the csv
csv_header = next(csvreader)
... |
25697204d6da732977cef03994324d00368ce1cb | hari1811/Python-exercises | /Quiz App/common.py | 685 | 4.15625 | 4 |
def get_int_input(prompt, high):
while(1):
print()
try:
UserChoice = int(input(prompt))
except(ValueError):
print("Error: Expected an integer input!")
continue
if(UserChoice > high or UserChoice < 1):
print("Error: Please e... |
5b0ea4f7425bc0e6a3a2a7063bd7245dbe6568cb | acheval/python | /ATBSWP/Chapter 7/strip_regex_version.py | 586 | 4.21875 | 4 | #!/bin/python3
import re
def strip_string(context, strip_character):
if strip_character == "":
regex_strip_whitespace = re.compile(r"^\s+|\s+$")
stripped_context = regex_strip_whitespace.sub("", context)
print(stripped_context)
else:
regex_strip_character = re.compile(r"[" + ... |
325f8eb8bbf520ac69cc480213e81bc50a4dc37c | acheval/python | /ATBSWP/Chapter 8/02_pyinputplus.py | 196 | 3.609375 | 4 | response = input('Enter a number: ')
print(response)
import pyinputplus as pyip
response = pyip.inputNum()
print(response)
response = pyip.inputInt(prompt = 'Enter a number: ')
print(response)
|
8072045ceb604ca4ad9b09e9467e656458f14ac7 | acheval/python | /python_exercices/exercice27.py | 142 | 4.0625 | 4 | #!/bin/python3
# 27. Write a Python program to change a given string to a new string where the
# first and last chars have been exchanged.
|
0fe7b9a76610823db9894b6dbdd43bfb996d84b8 | acheval/python | /ATBSWP/Chapter 8/09_multiplication_quizz.py | 1,007 | 3.609375 | 4 | import pyinputplus as pyip
import random, time
number_of_questions = 10
correct_answers = 0
for question_number in range(number_of_questions):
#Pick two random numbers:
num1 = random.randint(0,9)
num2 = random.randint(0,9)
prompt = '#%s: %s x %s = ' %(question_number, num1, num2)
try:
#Rig... |
a20fc079740a8d7ff9b022fe5e491b3218b2559a | acheval/python | /python_exercices/exercice06.py | 402 | 4.3125 | 4 | #!/bin/python3
# 6. Write a Python program to count the number of characters in a string.
# Sample String : 'google.com' Expected Result : {'o': 3, 'g': 2, '.': 1, 'e':
# 1, 'l': 1, 'm': 1, 'c': 1}
string = 'google.com'
d = dict()
for letter in string:
if letter in d:
d[letter] = d[letter]+1
else:... |
358cb695ab1430599eba277be1d2873ae862ccb8 | pranavchandran/redtheme_v13b | /chapter_2_strings_and_text/numbers_dates_times/rounding_numerical_values.py | 1,408 | 4.125 | 4 | # rounding numerical values
# simple rounding
print(round(1.23, 1))
print(round(1.27, 1))
print(round(1.25362, 3))
a = 1627731
print(round(a, -1))
print(round(a, -2))
print(round(a, -3))
x = 1.23456
print(format(x, '0.2f'))
print(format(x, '0.3f'))
print('value is {:0.3f}'.format(x))
a = 2.1
b = 4.2
c = a + b
# c = ... |
0f8d2c2b3ded0a9bf3e44ea7eea2a80131da1c07 | pranavchandran/redtheme_v13b | /ordering_the_data.py | 1,059 | 3.78125 | 4 | # using ordered dict
from collections import OrderedDict
d = OrderedDict()
d['foo'] = 1
d['bar'] = 2
d['spam'] = 3
d['grok'] = 4
print(d)
for key in d:
print(key, d[key])
import sys
print(sys.getsizeof(d))
import json
print(json.dumps(d))
prices = {
'ACME': 45.23,
'AAPL': 612.78,
'IBM': 205.55,
... |
963563dd55c0134bf7e6523a474607ef8c39fd7d | pranavchandran/redtheme_v13b | /chapter_2_strings_and_text/binary_octal_hexadecimal/infinity_and_nans.py | 603 | 4.03125 | 4 | # floating point values of infinity,negative infinity or NaN
a = float('inf')
b = float('-inf')
c = float('nan')
print(a, b, c)
# test for the presence of these values use the math.isinf() and math.isnan()
import math
print(math.isinf(a))
print(math.isnan(c))
a = float('inf')
print(a + 45)
print(a * 10)
print(10 / a... |
91e3e9bade179a93e27cbfd2bf6b442a5fa89760 | pranavchandran/redtheme_v13b | /c5_files_and_io/5_2_printing_to_a_file.py | 182 | 3.9375 | 4 | # you want to redirect the output of the print() to a file
# use the file keyword argument to print(), like this
with open('hello.txt', 'wt')as f:
print('hello pranav', file=f)
|
483f64e990a7afa4c50e113f8567aeeaf1a6bfbd | pranavchandran/redtheme_v13b | /start_dictionaries.py | 518 | 3.703125 | 4 | from collections import defaultdict
d = defaultdict(list)
d['a'].append(1)
d['a'].append(2)
d['b'].append(4)
print(d)
e = {}
e.setdefault('a', []).append(1)
e.setdefault('a', []).append(2)
e.setdefault('b', []).append(4)
print(e)
pairs = e
f = {}
for key, value in pairs.items():
if key not in f:
f[key]... |
f8d026245e19a202915e9cdc57dd0e9e4949760a | pranavchandran/redtheme_v13b | /chapter_2_strings_and_text/matching_string_using_shell_wild_cards/aligning _text_strings.py | 718 | 4.3125 | 4 | # Aligning of strings the ljust(), rjust() and center()
text = 'Hello World'
print(text.ljust(20))
print(text.rjust(20))
print(text.center(20))
print(text.rjust(20, '='))
print(text.center(20,'*'))
# format() function can also be used to align things
print(format(text, '>20'))
print(format(text, '<20'))
print(format... |
f0160c7b605ae60391516cba9f2701614f73a2b6 | AshutoshMaleti/problem-solving | /Palindrome Number.py | 305 | 3.5 | 4 | class Solution:
def isPalindrome(self, x: int) -> bool:
s=str(x)
length=len(s)
mid=length//2
if length%2!=0 and s[0:mid]==s[length:mid:-1]:
return True
elif s[0:mid]==s[length:mid-1:-1]:
return True
return False |
c791668713d4909d8c20592e729deb879e5fad38 | Alicepeach/plisplis3 | /godofredo.py | 1,100 | 4.15625 | 4 | # Calculadora
ejecutar = 1
while ejecutar == 1:
print("Este programa permite hacer una operación básica con dos números")
print("Para realizar esto, es necesario que me indiques el tipo de operación que deseas:")
print("1) Suma ")
print("2) Resta ")
print("3) Multiplicación ")
print("4) División ")
opcion = in... |
db86bf1f1eb6c9fc4557f6c10e58009a1fced04b | alextmacri/game-of-life | /src/game_of_life/ui/Button.py | 3,659 | 3.609375 | 4 | import pyglet
from game_of_life.assets import button_pressed_image, button_unpressed_image
class Button:
"""
Represents a button in the pyglet window of the game.
is_pressed: bool, the state of the button being pressed or not
x_cor: int, the x coordinates of the left of the button when drawn in the
... |
b4560cda481e3d8a3e4fb876adf0bfa166165204 | HaileyBaek/Algorithms | /respacing.py | 3,330 | 4.09375 | 4 | # Your name, Cornell NetID
# Haomiao Han (hh696)
# Your Partner's name, Cornell NetID
# Hyein Baek (hb437)
# DO NOT CHANGE THIS CLASS
class RespaceTableCell:
def __init__(self, value, index):
self.value = value
self.index = index
self.validate()
# This function allows Python to print a... |
dac386736a2c765ebaa29c4a0731f204a0aa8859 | tecmobowl64/TasklistProject | /mainmenu.py | 1,100 | 3.75 | 4 | import sys
import tasklist
def main():
def menu():
print("********************")
print("DoIt! Main Menu")
#time.sleep(1)
print("********************")
msg = "A: View All Incomplete Tasks\n"
msg += "B: Add a New Task\n"
msg += "C: Complete a Task\n"
msg... |
8054f63b7e5e110f56e3efff60b43f3c39babe66 | ArcDM/CodinGame-Hard-TAN-Network | /TAN Network.py | 4,389 | 4.15625 | 4 | import math
"""
This program takes several inputs about a number of
transportation stops and uses Dijkstra's algorithm to
determine the shortest path from one specified stop to
another specified stop.
This is the first python program that I've made that uses
classes. I would have ... |
2815b180c88bab2a680f7ff2334a93f6afdeb998 | csdms/standard_names | /standard_names/utilities/decorators.py | 5,891 | 3.828125 | 4 | #! /usr/bin/env python
"""Some decorators for the CmtStandardNames package."""
import os
from six import string_types
def format_as_wiki(func):
"""
Decoratate a function that reads lines from a file. Put some wiki
formatting around each line of the file and add a header, and
footer.
Examples
... |
4971f221a850884d40e54176029f3b7ec73c1d13 | Huang-chi/face_classification | /src/Marquee.py | 1,435 | 3.890625 | 4 | import tkinter as tk
class Marquee(tk.Canvas):
def __init__(self, parent, text, margin=2, borderwidth=1, relief='flat', fps=30):
tk.Canvas.__init__(self, parent, borderwidth=borderwidth, relief=relief)
self.fps = fps
# start by drawing the text off screen, then asking the canvas
# ... |
e3de573f7b991459f2bc27162422fb2abf1d4e66 | xjz1994/LeetCodeSolution | /Solution/Python/897. Increasing Order Search Tree.py | 1,027 | 3.78125 | 4 | def getHelperPath():
path = __file__.split("\\")[0:-1]
path[-2] = "Helper"
return "\\".join(path)
import sys
sys.path.append(getHelperPath())
from Tree import *
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# ... |
155967e50ee438bb61ba33ca9676406a1b0d9b4f | xjz1994/LeetCodeSolution | /Solution/Python/766. Toeplitz Matrix.py | 801 | 3.53125 | 4 | class Solution:
def isToeplitzMatrix(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: bool
"""
if not matrix or not matrix[0]:
return False
rowNum = max(0, len(matrix) - 1)
colNum = max(0, len(matrix[0]) - 1)
if rowNum is 0 or col... |
9a5c346f6bc209a252f31bb8d9dc72a891824470 | xjz1994/LeetCodeSolution | /Helper/Python/Tree.py | 3,823 | 3.671875 | 4 | # coding:utf-8
from enum import Enum
class TreeWalkType(Enum):
Pre = 0
In = 1
Post = 2
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Tree(object):
# 创建节点
@staticmethod
def CreateNode(val):
"""
... |
c3e53b9e82bfb00d48451e4c25d94e36a4c21148 | xjz1994/LeetCodeSolution | /Solution/Python/704. Binary Search.py | 561 | 3.65625 | 4 | class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
left = 0
right = len(nums) - 1
while left <= right:
idx = (left + right)//2
if nums[idx] < target:
... |
6d7caa2d400e29346d11e62374bec2b33ebe7776 | xjz1994/LeetCodeSolution | /Solution/Python/836. Rectangle Overlap.py | 411 | 4 | 4 | class Solution:
def isRectangleOverlap(self, rec1, rec2):
"""
:type rec1: List[int]
:type rec2: List[int]
:rtype: bool
"""
return rec1[0] < rec2[2] and rec2[0] < rec1[2] and rec1[1] < rec2[3] and rec2[1] < rec1[3]
rec1 = [0, 0, 2, 2]
rec2 = [1, 1, 3, 3]
# rec1 = [0,... |
a6acadc06095f4daa125a343eb282dd428a220ca | xjz1994/LeetCodeSolution | /Solution/Python/53. Maximum Subarray.py | 524 | 3.609375 | 4 | class Solution:
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
res, curSum = nums[0], 0
for i in nums:
if curSum < 0:
curSum = i
else:
curSum += i... |
8aaa3c1143a12a1d5aafb48d207aa854dd18f339 | xjz1994/LeetCodeSolution | /Solution/Python/820. Short Encoding of Words.py | 627 | 3.5 | 4 | class Solution:
def minimumLengthEncoding(self, words):
"""
:type words: List[str]
:rtype: int
"""
root = dict()
leaves = []
for word in set(words):
cur = root
for i in word[::-1]:
cur[i] = cur = cur.get(i, dict())
... |
c0465c9db420793e5d3bb4843eba73bb86f5a7ca | xjz1994/LeetCodeSolution | /Solution/Python/925. Long Pressed Name.py | 655 | 3.5 | 4 | class Solution(object):
def isLongPressedName(self, name, typed):
"""
:type name: str
:type typed: str
:rtype: bool
"""
i, j = 0, 0
while i < len(name) and j < len(typed):
if name[i] == typed[j]:
i += 1
elif j == 0 or ty... |
8c24c0caa11fe94e2c7c8e7374e6881a4f3d9d6f | xjz1994/LeetCodeSolution | /Solution/Python/112. Path Sum.py | 919 | 3.703125 | 4 | def getHelperPath():
path = __file__.split("\\")[0:-1]
path[-2] = "Helper"
return "\\".join(path)
import sys
sys.path.append(getHelperPath())
from Tree import *
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# ... |
2c61e525972257eb3a4c21e92c5f5ecf873e6f81 | xjz1994/LeetCodeSolution | /Solution/Python/92. Reverse Linked List II.py | 1,108 | 3.78125 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseBetween(self, head, m, n):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
"""
start = end = head
for i in range(1... |
02dcafb3f82485951cec209c1ae7548e8e3d9b2b | xjz1994/LeetCodeSolution | /Solution/Python/867. Transpose Matrix.py | 542 | 3.5625 | 4 | class Solution(object):
def transpose(self, A):
"""
:type A: List[List[int]]
:rtype: List[List[int]]
"""
rowNum = len(A)
colNum = len(A[0])
B = []
for i in range(colNum):
newRow = []
for j in range(rowNum):
newRo... |
401dd96339e2fabe9312791c2f719607975c36a9 | xjz1994/LeetCodeSolution | /Solution/Python/814. Binary Tree Pruning.py | 1,141 | 3.71875 | 4 | def getHelperPath():
path = __file__.split("\\")[0:-1]
path[-2] = "Helper"
return "\\".join(path)
import sys
sys.path.append(getHelperPath())
from Tree import *
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# ... |
60dcd0aeae3db7f50151ef5104717801953a3cbc | crouchr/learnage | /environments/dev/br2020-slack15/app/crudeTld.py | 991 | 3.640625 | 4 | #!/usr/bin/python
# Crude code to extract TLD from a hostname since none of the proper libararies work on python 2.5
def getTLD(hostname) :
tld = "NO_INFO"
if "." not in hostname :
return "NO_INFO"
print "-----------------"
fields = hostname.split('.')
numFields = len(fields)
... |
92f22e9ccf94fdf8ca477558ee003a7bba0a0d63 | crouchr/learnage | /environments/dev/metcrouch/apache/src/julian.py | 519 | 3.515625 | 4 | # https://stackoverflow.com/questions/13943062/extract-day-of-year-and-julian-day-from-a-string-date
import datetime
def get_julian_date(datetime_str):
"""
:param date_str: e.g. 2012-11-7 18:00:00
:return:
"""
date_part = datetime_str.split(' ')[0]
date_parts = date_part.split('-')
year =... |
b534e7cebb0800baf0b4f4e62da9fe3a522607a9 | Vamicc/OP | /LAB2/LAB2OP.py | 773 | 4.21875 | 4 | print("Enter the x coordinate: ")
x = int(input())
print("Enter the y coordinate: ")
y = int(input()) # просимо ввести координати точки
if x > 0 and y > 0:
result = "The point belongs to the first quadrant."
elif x > 0 and y < 0:
result = "The point belongs to the forth quadrant."
elif x < 0 and y > 0:
result... |
fa8ed48213af070d1a58b7c209064aeb99c7bdb6 | DrQuestion/PoCS2 | /Strings 6.py | 459 | 3.984375 | 4 | if __name__ == '__main__':
s = raw_input()
l=list(s)
print any (str.isalnum() for str in l) #these ones following 'any' are generators which return every time the result of the validation methods, and 'any' is used because one single occurrance is sufficient for our purposes
print any (str.isalpha() for... |
5678067dfd8dfc101bb1fb6ea8b867a432277fac | DrQuestion/PoCS2 | /Strings 12.py | 189 | 3.875 | 4 | def capitalize(string):
l=list(string)
l[0]=l[0].upper()
for i in range(1,len(l)):
if l[i-1]== ' ':
l[i]=l[i].upper()
string=''.join(l)
return string |
a79f3a15c4a4e48e3a932d5758bb3657226702f3 | jsmith321123/DataStructures | /fifoStack.py | 713 | 3.890625 | 4 | class Stack:
#Last in first out stack
def __init__(self):
self.maxSize = 10
self.stack = []
def push(self, item):
if not self.isFull():
self.stack.append(item)
return True
return False
def pop(self):
item = self.peek()
self.stack = self.stack[1:]
return item
def isFull(self):
if len(sel... |
570b39242fc618cea05c78f3079f8b65f59d6a8c | akhilavemuganti/HelloWorld | /CSV.py | 1,299 | 3.984375 | 4 | import csv
# Display all the Column Names
#
# with open("School_Nutrition.csv") as csv_file:
# csv_reader=csv.reader(csv_file)
# print("Column names are")
# i=next(csv_reader)
# print(i)
column_names=['ProgramYear', 'ReportType', 'CEID', 'CEName', 'CECounty', 'ESC']
# Display first 10 column names i... |
1d34800f127f69e26a9622e5e42407420657a055 | akhilavemuganti/HelloWorld | /Exercises.py | 2,984 | 4.1875 | 4 | #Exercises
#bdfbdv ncbgjfv cvbdggjb
"""
Exercise 1: Create a List of your favorite songs. Then create a list of your
favorite movies. Join the two lists together (Hint: List1 + List2). Finally,
append your favorite book to the end of the list and print it.
"""
listSongs=["song1","song2","song3","song4"]
listMovies=["... |
2def5040881869ea578139c429f81a805d4a31ac | jaan1708/dbSQLite | /dbConnector.py | 2,149 | 3.953125 | 4 | #!/usr/bin/python
import sqlite3
class database(object):
def __init__(self):
self.__dbConn = None
# connection settings - these might change
# to a mysql or postgress database
# these would really be in an external file
self.__databaseName = 'SQLite_Python.db' # this is nam... |
032a661000f8d68acfcbfdb8155a3ce022f27e06 | iambillmccann/ProjectEulerPython | /main.py | 2,412 | 4.0625 | 4 | import time
from projecteuler.mathlibrary import utilities
from projecteuler.problems import ProblemFactory
LASTPROBLEM = 13
QUITSTRING = 'Q'
def get_user_input():
""" Get user input from the console
getUserInput is a simple method for reading from the console.
Returns:
A string that represents... |
d09f714bf5003e6c2b5846c959727447a72ff017 | OlyaIvanovs/python_cookbook | /chapter0/comprehensions.py | 2,803 | 3.609375 | 4 | """Effective Python: 90 Specific Ways to write Better Python."""
from types import prepare_class
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squares = [x*x for x in a if x % 2 == 0]
# print(squares)
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [x for row in matrix for x in row]
# print(flat)
a = [1, 2, 3, 4, 5, 6, 7,... |
afd0e9e65a58aa1481e357f31afbc5bd32e33401 | optionalg/Practising-Python | /Basics/Day-1/calendar.py | 656 | 3.875 | 4 | """
Program to print the calander of a month and year
"""
import time
from calendar import *
#import sys, builtins
'''
month=int(input())
year=int(input())
obj=calendar.Calendar()
print(dir(calendar))
print(calendar.__doc__)
print(calendar.__name__)
print(calendar.__package__)
print(dir(sys))
'''
... |
17d97e7639af2095e93d255e5035932afd8763ca | optionalg/Practising-Python | /Basics/Day-3/nString.py | 72 | 3.5 | 4 | """
Copies of a string.
"""
s=input()
n=int(input())
print(s*n)
|
8dc8a5a9e478b7fd2ad11a2e973ab607a186120e | optionalg/Practising-Python | /Lists/Day-0/SmallestInList.py | 578 | 4.0625 | 4 | """
Print smallest number in list.
"""
def smallest(l):
flag=0
small=l.pop()
try :
while(small<l.pop()) :
flag=small
except IndexError :
print("")
return(flag)
l=[]
print("Take input ? y/n : ")
ch=str(input())
while(ch=='y') :
print("enter a n... |
b3f4e63f07c858ac053f76d161ef4ccd4263db70 | optionalg/Practising-Python | /Basics/Day-5/Sum_Diff_Equality_5.py | 246 | 4.09375 | 4 | """
To check the sum or difference or equality of two numebrs is 5.
"""
def check(x,y):
if x==y or x+y==5 or abs(x-y)==5 :
return True
else :
return False
x=int(input())
y=int(input())
print(check(x,y))
|
47682810b53a8046253df596019488f6fa78838e | optionalg/Practising-Python | /Basics/Day-5/x+y_square.py | 196 | 3.703125 | 4 | """
Compute (x+y)^2.
"""
def x_plus_y_square(x,y) :
print((x+y)*(x+y))
return 1
x=int(input())
y=int(input())
try :
x_plus_y_square(x,y)
except :
print("Failed")
|
4834f4616f90efc5345bd069ed2b85e3a5f442d0 | KumarAmbuj/BINARY-TREE-CHECKING-AND-PRINTING | /36.PRINT LEFTMOST AND RIGHTMOST NODE.py | 691 | 3.71875 | 4 | class Node:
def __init__(self,val):
self.val=val
self.left=None
self.right=None
def storenode(node,hash,d):
if node==None:
return
if d not in hash:
hash[d]=node.val
storenode(node.left,hash,d-1)
storenode(node.right,hash,d+1)
def lrnode... |
76e880c7a78f76e8796b24230bd6e26751c1088d | KumarAmbuj/BINARY-TREE-CHECKING-AND-PRINTING | /40.RIGHT VIEW.py | 743 | 3.921875 | 4 | class Node:
def __init__(self,val):
self.val=val
self.left=None
self.right=None
def printnode(node,l,d):
if node==None:
return
if d not in l:
print(node.val,end=' ')
l.append(d)
printnode(node.right,l,d+1)
printnode(node.left,l,d+1)
... |
fc7a1db3debe9640c8ab3418bafc9e9725710a23 | KumarAmbuj/BINARY-TREE-CHECKING-AND-PRINTING | /12.check is subtree or not.py | 1,163 | 3.75 | 4 | class Node:
def __init__(self,val):
self.val=val
self.left=None
self.right=None
def checkwhole(node1,node2):
if node1==None and node2==None:
return True
if node1 and node2:
return (node1.val == node2.val) and checkwhole(node1.left, node2.left) and checkwhole(... |
2a078378c353eec3a5a87fb4387dac48c55630c6 | 03escape/mpg-run-off | /cal.pi | 921 | 3.96875 | 4 | Python 3.6.8 (default, Jan 14 2019, 11:02:34)
[GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux
Type "help", "copyright", "credits" or "license()" for more information.
>>> number_1 = int(input('enter your first number: '))
enter your first number: 3
>>> number_1 = int(input('enter your first number... |
face8ec4bbcd7bd0f69eecb2cc1899951501f992 | sarzar/Coding-Projects | /Python Projects/mario.py | 626 | 4 | 4 | from cs50 import get_int
#Gets input from user on loop until correct input is given
while True:
h = get_int("Height: ")
if h >= 1 and h <= 8:
break;
#Creates half-pyramids
i = 0
for i in range(h):
#Spaces
j=0
for j in range(h-i):
print(" ", end = "")
j+=1
#Has... |
f613037e4ebcb6596c116660e7dc516dc10ffeb3 | turner-white/python-code | /HW09p2.py | 3,654 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Oct 29 18:40:25 2020
@author: turne
"""
import numpy as np
from matplotlib import pyplot as plt
def CreateSystem(kvec,mvec): #Define our function as specified
n = len(mvec) #Calculate the length of the matrix
ret = np.zeros((n,n)) #Create a nxn storage mat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.