blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
18c02f7f7b334e60c9731474eb0ff13d750aec1b | drcsturm/project-euler | /p028.py | 997 | 3.625 | 4 |
# Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:
# 21 22 23 24 25
# 20 7 8 9 10
# 19 6 1 2 11
# 18 5 4 3 12
# 17 16 15 14 13
# It can be verified that the sum of the numbers on the diagonals is 101.
# What is the sum of the numbers on the d... |
79649b8391d4a804042b64155fe59ed010f7a877 | TomasArteaga/MCOC-NIVELACION | /21082019/000310.py | 148 | 3.859375 | 4 | a=[3,10,-1]
print (a)
a.append(1)
print(a)
a.append("hello")
print(a)
a.append([1,2])
print(a)
#3:10-4:10
a.pop()
print(a)
a.pop()
print(a)
|
0338d7a580795e77abc73b84f1bf28a729011e57 | erikhansen816/unit2 | /quiz2.py | 837 | 4.40625 | 4 | #Erik Hansen
#9/25/2017
#quiz2.py - Quiz program on unit 2
num1 = int(input('Enter a number: '))
num2 = int(input('Enter a second number: '))
#This part determines which number is the biggest
if num1>num2:
print('The first number is bigger')
elif num2>num1:
print('The second number is bigger')
else:
print(... |
348d320f762d784a9f54df8546104b6e3c5e7455 | AntonBrazouski/thinkcspy | /12_Dictionaries/lab_12_01b.py | 236 | 3.75 | 4 | # def countA(text):
# count = 0
# for c in text:
# if c == 'a':
# count = count + 1
# return count
#
# print(countA("banana"))
#
def countA(text):
return text.count("a")
print(countA('bananamama'))
|
3c1d91a5d1830f6f27cdf66bb42315d4c168ca61 | jithu7432/physics | /Mathematics/Polynomials/Chebyshev.py | 666 | 3.515625 | 4 | #JJ
from pandas import DataFrame
f = lambda v: v ** 4 - 8 * v + 3
df = lambda u:(f(u + h) - f(u)) / h
ddf = lambda z: (df(z + h) - df(z)) / h
fl, dfl, xl, xll, ddfl = ([] for _ in range(5))
epsilon = 1e-5
h = 1e-5
x = float(input("Enter initial guess: "))
while True:
xl.append(x), ddf... |
8998694693af206789c407f00936ad609f9625a3 | mariihespana/8ProjectsInPython | /Project_7_Adventure_Game.py | 2,951 | 3.796875 | 4 | # Projeto 7 - Jogo de Aventura (ADAPTADO - MINHA VERSÃO)
# Um jogo de decisões onde terão vários finais diferentes de acordo com cada resposta dada
Cenario1 = 'Você está em uma guerra entre duas nações. As nações são representadas por Gregos e Romanos.'
Cenario2 = 'Infelizmente, não se têm espadas para todos. Durante ... |
a9359143adf9c85f1c7df097b91662aa2f54696b | ioyy900205/.leetcode | /24.swap-nodes-in-pairs.py | 1,181 | 3.703125 | 4 | # @lc app=leetcode id=24 lang=python3
#
# [24] Swap Nodes in Pairs
#
# @lc tags=linked-list
# @lc imports=start
from imports import *
# @lc imports=end
# @lc idea=start
#
#
#
# @lc idea=end
# @lc group=
# @lc rank=
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self... |
69f1c9b1336ce6cb01ba58b0fa0301b961641bda | eloranta/Euler | /python/Problem60/main.py | 2,581 | 3.546875 | 4 | def generate_primes(limit):
primes = [True] * limit
primes[0] = False
primes[1] = False
for n, is_prime_number in enumerate(primes):
if is_prime_number:
yield n
for i in range(n * n, limit, n):
primes[i] = False
def create_primes(limit):
primes = []
... |
24e71a33e622cde6c82a638078fd85f7406f82b2 | daniel-reich/ubiquitous-fiesta | /bupEio82q8NMnovZx_15.py | 740 | 3.671875 | 4 |
def track_robot(instructions):
horizontal_movement = 0
vertical_movement = 0
final_instructions = []
for element in instructions:
specific_instructions = element.split()
if specific_instructions[0] == 'right':
horizontal_movement += int(specific_instructions[1])
elif... |
94fc2cc180624536668c6c57f3e3b9f5ec7d659a | kunal27071999/KunalAgrawal_week_1 | /Week_1_datastructure_part1_Q60.py | 262 | 4.3125 | 4 | """60. WAP to add list of elements to a given set
Input
set_1 = {"a", "b", "c"}
list_1 = ["b", "d", "e"]"""
sample_set = {"a", "b", "c"}
list_of_num = ["b", "d", "e"]
for elem in list_of_num:
sample_set.add(elem)
print('Modified Set: ')
print(sample_set)
|
2c056c332738a99c6b67e9ef3ddd3242a3161736 | arnabs542/DataStructures_Algorithms | /bitwise/Different_Bits_Sum_Pairwise.py | 1,119 | 3.546875 | 4 | '''
Different Bits Sum Pairwise
We define f(X, Y) as number of different corresponding bits in binary representation of X and Y.
For example, f(2, 7) = 2, since binary representation of 2 and 7 are 010 and 111, respectively. The first and the third bit differ, so f(2, 7) = 2.
You are given an array of N positive inte... |
5352a4b028c85879f963ee5367f0cad7feb18f03 | TingHuanClay/Python_Libraries_Practice | /src/Pandas/pandas_demo.py | 11,709 | 3.765625 | 4 | import pandas as pd
groceries = None
def pands_series_demo():
global groceries
groceries = pd.Series(data=[30, 6, 'Yes', 'No'], index=[
'eggs', 'apple', 'milk', 'bread'])
print(groceries)
"""
Output:
eggs 30
apple 6
milk Tes
bread No
... |
2ebcf2277f9a22e7f1236a03dfa85cff555159c6 | SouvikBhattacharji2020/My_Code | /Python/BasicPythonProgram/Class_8_CBSE/Loop_in_for_3.py | 247 | 4.125 | 4 | #
# homework 4/8/2020
#
# 1
# 2 3
# 4 5 6
# 7 8 9 10
#
a=int(input("Enter number of row : "))
b=1
print("#")
for i in range(1,a+1):
print("#",end=" ")
for j in range(1,i+1):
print(b,end=" ")
b+=1
print()
print("#") |
0bc2adfcc56a227f3609c01b5ac54748606e3970 | evennia/evennia | /evennia/contrib/rpg/health_bar/health_bar.py | 4,901 | 3.703125 | 4 | """
Health Bar
Contrib - Tim Ashley Jenkins 2017
The function provided in this module lets you easily display visual
bars or meters - "health bar" is merely the most obvious use for this,
though these bars are highly customizable and can be used for any sort
of appropriate data besides player health.
Today's players... |
6e3387e3489b1040b753b542f2e3f2d4edfec3dc | davidbezerra405/PytonExercicios | /ex023.py | 864 | 3.953125 | 4 | num = str(input('Informe um número entre 0 e 9999: ')).strip()
print('O número informado tem {} digito(s).'.format(len(num)))
numint = int(num)
print('')
#print('String')
#print('-'*10)
#print('Unidade: {}'.format(num[3]))
#print('Dezena: {}'.format(num[2]))
#print('Centena: {}'.format(num[1]))
#print('Milhar: {}'.for... |
ed142339bc35c7d15eeddb75643dfd588b0f9516 | karthik-siru/practice-simple | /strings/dsa_7.py | 1,173 | 3.984375 | 4 |
'''
Algorithm :
So , the longest palindrome , will start in the middle . So , the key idea is to
to find the longest palindrome , with ith index as center . and to cover the even
length strings we , run the expand fundtion with ith index and i+1 th index as center
Note :
This approach is... |
f657d093d2347d965c3a24032d4e3aa2067d8e48 | kpsimon/general-python | /beginner/gamesofchance.py | 5,214 | 3.9375 | 4 | import random
money = 100
num = random.randint(1, 10)
#Write your game of chance functions here
def coinflip(guess, bet, money):
flip = random.randint(1,2)
g_val = guess.upper()
while not (g_val == "HEADS" or g_val == "TAILS"):
g_val = input("Invalid guess. Heads or Tails:").upper()
while not (bet.isdigit() a... |
120db75cf67bb0111573e039d4aaf275588fea43 | Ojooh/SANS-SURVEY-WITH-tkinter | /survey.py | 9,774 | 3.5625 | 4 | import tkinter
from tkinter import *
#import Question
import time
#import Image
import random
#create the questions
#bcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
#ssssssssssssssssssssssssssssssssss'
question_prompts = [
"1. What is your position within the company?",
"2. Does your compa... |
c26cc47c30550ed0d2c408d77d4037d4dbf8ce4c | kiwi-33/Programming_1_practicals | /p4-5/p4-5p2.py | 359 | 4.28125 | 4 | length= float(input("Enter a number: "))
import math
square= length**2
cube= length**3
circle= (math.pi)*(length**2)
sphere = (4/3)*(math.pi)*(length**3)
cylinder = (math.pi)*(length**2)*(length)
if length < 0:
print ("Length must be >=0. Please try again")
else:
print (square)
print (cube)
... |
9c8bc69616e3e09c95dd47215b96e5809517e151 | bytezen/Game-AI-Summer-Short-Course-2018 | /new_steering_behaviors/util.py | 1,601 | 3.90625 | 4 | import pygame as pg
from pygame.math import Vector2
def _rotate(surface, angle, pivot, offset):
"""Rotate the surface around the pivot point
Args:
surface (pygame.Surface): The surface that is to be rotated
angle (float): Rotate by this angle
pivot (tuple, list, pygame.math.Vector2): ... |
03395c858b3ba4ad022b5db9b3504875b65d4ccf | rehoot/SBList | /SBLtest01.py | 1,464 | 3.5625 | 4 | from SBList import *
# The first test will ensure that the append function works properly.
# A prior version would insert before the last entry instead of appending
sb = SBList([])
sb.append(0)
sb.append(1)
sb.append(2)
sb.append(3)
assert(sb == [0,1,2,3])
sb.insert(4, 4)
assert(sb == [0,1,2,3,4])
sb.insert(4, 3.5)
as... |
c1cf328e10f7bd746b4398020232705a2a34bb32 | AaronCWacker/copycat | /main.py | 3,058 | 3.9375 | 4 | #!/usr/bin/env python3
"""
Main Copycat program.
To run it, type at the terminal:
> python main.py abc abd ppqqrr --interations 10
The script takes three to five arguments. The first two are a pair of strings
with some change, for example "abc" and "abd". The third is a string which the
script should try to chan... |
704b57e0ec9ee6144b65f7915c0ed0d414364084 | syurskyi/Algorithms_and_Data_Structure | /_algorithms_challenges/codeabbey/_CodeAbbey_Challenges-master/Problem5_MinOf3.py | 390 | 3.5 | 4 | infile = open("prob5.txt")
count = infile.readline()
ans = ""
for i in range(int(count)):
a,b,c = infile.readline().split(" ")
if int(a)>=int(b): #take b
if int(b)>int(c): #take c
ans += c +" "
else:
ans += b+" "
else: #take a
if int(a)>int(c): # take c
... |
6188d0fabd41646bd447583561508af05e2df9a5 | Mugisha-isaac/python | /list.py | 1,041 | 4.09375 | 4 | num=[1,2,3]
students=['mugisha',"isaac","byiringiro"]
print(students)
fruits = ["mango","apple","orange"]
# print('mango' in fruits)
# for fruit in fruits:
# print(fruit)
# print(len(fruits))
# print(range(4))
# for i in range(len(fruits)):
# print('at index',i,"element is",fruits[i]
#
animals =["cat","co... |
fed3d37d3dd6fe24bd8968d53dba61c95f2cf476 | SysSciAndHealth/crcsim | /bin/createLinks.py | 1,962 | 4.03125 | 4 | #!/usr/bin/env python3
""" createLinks.py: read a "renumbered" directory and make a link to every file in that directory in the
target directory. This has the effect of making the ordinary and renumbered directories look like
one directory. If you are wondering why sych a thing should be needed, see the REA... |
58500f48b8b218fab8fb42504a4d6d99d56f3257 | martinyordanov90/homework-hackBG | /6/1-List-Functions/COUNT ITEM.py | 199 | 3.953125 | 4 | def count_item(n, numbers):
count = 0
for number in numbers:
if n == number:
count += 1
return count
n = 2
numbers = [1,2,2,2,2,2,2,3,4,5]
print(count_item(n,numbers)) |
48c7323349ddc44be054d998390b932cd7b8c856 | elitewarri0r/project_euler | /Problem 4.py | 792 | 4.3125 | 4 |
'''
The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
'''
#problem 4
# built-in function for flipping str, x = x[::-1]
multiplier1 = int(input(" enter a number that's 3 dight : "))
multiplier2 = multiplier1
... |
ff33e5f009830122d3aa0f152053c1610b1566d8 | killswitchh/Leetcode-Problems | /Medium/LongestSubstringWithoutRepeatingCharacters.py | 524 | 3.59375 | 4 | """
https://leetcode.com/problems/longest-substring-without-repeating-characters/
"""
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
left=0
right=0
n=len(s)
l=[]
max=0
while(right < len(s)):
if(s[right] not in l):
l.app... |
f730af53259a6870135f89bd59ed0a7556065d13 | Tapsanchai/basic_pythom | /python_basic1.py | 4,060 | 3.8125 | 4 | # print & set variables
"""
คอมเม้นใหญ่
"""
print("hello")
v_str = "Parew"
v_flt = 5.456
v_num = 789
v_bool = True
v_array = [v_str, v_flt, v_num, v_bool]
print(v_array, "=" ,type(v_array))
print("v_array[1] * v_array[2] =", float(v_array[1] * v_array[2]), "\n")
# convert type variables
con_v = int(v_flt);
sum = con... |
b9e10a145429022614da4426e4d461b77cb12007 | Raolaksh/Python-programming | /If statement & comparision.py | 466 | 4.15625 | 4 |
def max_num(num1, num2, num3):
if num1 >= num2 and num1>= num3:
return num1
elif num2 >= num1 and num2 >= num3:
return num2
else:
return num3
print(max_num(300, 40, 5))
print("we can also compare strings or bulleans not only numbers")
print("these are comparision ope... |
09af988f89eca6949b836e1e7744748645c1e89f | Gborgman05/algs | /py/merge_trees.py | 725 | 4.0625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:
if... |
ff09c37531a98b3d4c344ffc1956f3fdc84a5bab | Eccie-K/pycharm-projects | /while loop.py | 172 | 3.609375 | 4 | age = 1
while age <= 10:
age += 1
print("you qualify", age)
while age > 0:
age -= 1
print(age)
a = ["foo", "bar", "joy"]
while a:
print(a.pop(-1))
|
4c04f9ccbf5051d6cb53c0a0ae1172b54b04f969 | harshildarji/Python-HackerRank | /Regex and Parsing/Group(), Groups() & Groupdict().py | 196 | 3.515625 | 4 | # Group(), Groups() & Groupdict()
# https://www.hackerrank.com/challenges/re-group-groups/problem
import re
s = re.search(r'(?!_)(\d|\w)\1', input())
print('-1' if s is None else s.group(0)[0])
|
89623e79bbcdd1896925b55fee663236346942eb | artem-aksenkin/nginx | /The biggest eve of 3.py | 352 | 4.0625 | 4 | x=int(input("type x value "))
y=int(input("type y value "))
z=int(input("type z value "))
if x>y and x>z and x%2==0:
print(x)
elif y>x and y>z and y%2==0:
print(y)
elif z>x and z>y and z%2==0:
print(z)
elif z==x and z==y and x%2==0 and y%2==0 and z%2==0:
print ("all numberes are equal")
else:
prin... |
21e786aa0546e020ead4a93bf9bda2fc4c3fb233 | candyer/leetcode | /2021 March LeetCoding Challenge/15_tinyURL.py | 1,867 | 4.34375 | 4 | # https://leetcode.com/explore/challenge/card/march-leetcoding-challenge-2021/590/week-3-march-15th-march-21st/3673/
# Encode and Decode TinyURL
# Note: This is a companion problem to the System Design problem: Design TinyURL.
# TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/p... |
363636278bdae82e2f79f1b55f8402f31f66bc7a | PMiskew/Year9DesignCS4-PythonPM | /General Techniques Python/ListsParallel.py | 509 | 4.4375 | 4 |
#Parallel lists are lists that are designed to share common information in an index
#Let's image a game where there are weapons that have damage and defense options
weapon = ["sword","gun","sheild"]
attack = [65,95,30]
defense = [65,10,95]
value = 1
while value != -1:
print("1: Sword")
print("2: Gun")
print("3: ... |
cc90012c15eaef0c750234a02676072d68e1e1cd | python-practice-b02-927/kuleshov | /lab2/ex5.py | 431 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 10 09:44:48 2019
@author: student
"""
import turtle
def square(a):
for i in range(4):
turtle.forward(a)
turtle.right(90)
n = 10
a = 30
c = 30
turtle.shape('turtle')
for i in range(n):
square(a)
turtle.penup()
turt... |
ff8f85d3d20208fc0b0b644da580caaad66973ea | cica-mica/zadaci_prva_zbirka | /1.1_vjezbe1.py | 384 | 3.65625 | 4 |
"""
Napravite program koji ce ispisati je li srednja cifra unesenog trocifrenog broja parna, neparna ili nula.
"""
x = int(input('Unesite zeljeni broj '))
srednja_cifra = (x//10)%10
print (srednja_cifra)
if srednja_cifra == 0:
print('Srednja cifra je 0')
elif srednja_cifra % 2 == 0:
print('Srednj... |
9f99ffadd38adf99ca2bfc7c483b324b96d183a6 | HACKunamatata1/finalProject | /Platform.py | 693 | 3.796875 | 4 |
class Platform:
"""THIS WIL DEFINE A PLATFORM. ATTENTION: A PLATFORM IS NOT A FLOOR.
PLATFORMS ONLY OCUPPY ONE CELL. FLOORS ARE GENERATED ON THE MAINGAME() CLASS"""
def __init__(self, platform_x, platform_y):
#position attributes
self.platform_x = platform_x
self.platform_y = pl... |
4f3740af3ece3ee2cf9f1646a2734d69709dd795 | NiteshMistry/Complex-Data-Structures-Codecademy | /02-trees/03-trees-node-ii.py | 334 | 3.78125 | 4 | # Define your "TreeNode" Python class below
class TreeNode:
def __init__(self, value):
self.value = value
self.children = []
def add_child(self, child_node):
print("Adding " + child_node.value)
self.children.append(child_node)
root = TreeNode("I am Root")
child = TreeNode("A wee sappling")
root.ad... |
4bc4fc5e88b9c2786b7374eaad8f85393220578a | dev-11/codility-solutions | /Solutions/Training/Lesson_07/stone_wall.py | 402 | 3.5625 | 4 | def solution(H):
wall = [None] * len(H)
wall_position = 0
used_blocks = 0
for height in H:
while wall_position > 0 and wall[wall_position - 1] > height:
wall_position -= 1
if wall_position < 1 or wall[wall_position - 1] != height:
wall[wall_position] = height
... |
74235da9ba73aea55e8dd6f62bebe8ca93e84b72 | Xiya01/python | /hangman.py | 1,871 | 3.921875 | 4 | import os, time
def game():
nb_of_tries = 3
word = input("Write your word: ")
list1= []
list2 =[]
for letters in word: #put letters into a list
list1.append(letters)
os.system('cls')
for a in list1: #display letter as "_" for players
a = "_"
list2.append(a) ... |
6e94a64fbead139373db2aad450cad28a1803587 | caojp123/data | /二叉树.py | 3,633 | 4.0625 | 4 | # coding: utf-8
class Node:
def __init__(self, item=None):
self.value = item
self.lchild = None
self.rchild = None
# 二叉树Binary tree
class BinaryTree:
def __init__(self, item=None):
self.__root = item
# 检测二叉树中是否有元素
def isEmpty(self):
return self.__root is None
... |
e31c8935b8516c9db70c275e996d22b9e8154b72 | Madisonjrc/csci127-assignments | /lab_01/program1.py | 905 | 3.6875 | 4 | def greeter(name):
return "hello"+name+"!"
print(greeter("stan"))
print(greeter("ollie"))
def make_abba(a, b):
return a+b+b+a
def hello_name(name):
return "Hello "+ name+"!"
def near_hundred(n):
return ((abs(100 - n) <= 10) or (abs(200 - n) <= 10))
def missing_char(str, n):
front= str[:n]
back=s... |
03d9e7258ac81a298aa6a6c5b8d377784f440def | torres1-23/holberton-system_engineering-devops | /0x15-api/2-export_to_JSON.py | 1,042 | 3.765625 | 4 | #!/usr/bin/python3
"""This modules gets information from {JSON} Placeholder
API to list information about an employee, and stores it on
a json format in a file.
Usage:
Accepts one argument, the id of the employee to list info.
Execute this module like this:
<python3 2-export_to_JSON.py <id of user>>
js... |
352d36799dc6abc14b6d3e790ac06360fb14816b | EduardoRosero/python | /curso python/paquete/TinyIntError/__init__.py | 374 | 3.625 | 4 | from .validate import validate_valor, validate_tiny_int
from .error import TinyIntError
#Definimos la funcion que me retorne su el numero comple o no con la condicion buscada e TinyInt
def tiny_int(valor):
try:
if validate_valor(valor) and validate_tiny_int(valor):
return True
else:
raise TinyIntE... |
c58b1e6ace2828fe7eebd1fa6a79597a3736fa60 | RhuanAlndr/CursoemVideo_Python | /ex026 - Aula 9.py | 298 | 3.796875 | 4 | f = input('Escreva uma frase qualquer: ').strip().lower()
print('A letra "a" aparece {} na sua frase.'.format(f.count('a')))
print('A letra "a" aparece a primeira vez na posição {}.'.format(f.find('a') + 1))
print('A letra "a" aparece pela última vez na posição {}.'.format(f.rfind('a') + 1))
|
54ab7c419cbf86b2ddf236d9e8e01bec296dda03 | butter-scotch/SameTree | /SameTree.py | 508 | 3.734375 | 4 | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def isSameTree(self, p, q):
if not p and not q:
return True
if not p or not q:
return False
if p.val != q.val:
return False
return self... |
7dd94b4b5d70dc3b9def902dc86af76b26b3a9ee | Yashkumar-Shinde/Python-programming-lab | /factorial.py | 146 | 3.59375 | 4 | #Yashkumar Shinde 11810825 M 53
a= int(input("Enter a number"))
i=1
fact=1
for j in range(0,a):
fact=fact*i
i=i+1
print ("Factorial is:", fact)
|
95b7f97e8312ac9787765bb444fd4179317ffc76 | sunjunee/Coding-Interview-Guide | /codes/T1-2.py | 1,527 | 4.3125 | 4 | # -*- coding: utf-8 -*-
"""
@ Author: Jun Sun {Python3}
@ E-mail: sunjunee@qq.com
@ Date: 2018-05-30 17:14:52
"""
# T1-2 由两个栈组成的队列
# 编写一个类,用两个栈实现一个队列,支持队列的基本操作
# add、poll、peek
# add:队尾添加,poll:队头删除,peek:返回队头
# 用两个栈保存队列中的数据,栈1用于存push的数据
# 栈2用于pop数据。如果栈2为空,则将栈1的元素全部
# 取出来放到栈2(先进后出 + 先进后出 => 先进先出)
class Queue():
d... |
acacc72d1c2171179fe92373a3e36834365cc5b6 | ramlaxman/cisco-feb2020 | /dictdiff.py | 1,073 | 4.1875 | 4 | #!/usr/bin/env python3
# dictdiff takes two dicts as arguments
# it returns a dict representing the difference between them
# if a key-value pair exists (identical) in both, ignore it in the output
# if a key exists in both, with different values, return
# a key-value pair with the key and a list as the value, with
... |
6ac8b15e4def29aea60f22a51347d55225d6e136 | cs50/cscip14315 | /2021-07-06/contacts5.py | 227 | 4.25 | 4 | people = [
{"name": "David", "email": "malan@harvard.edu"},
{"name": "Kareem", "email": "kzidane@cs50.harvard.edu"},
{"name": "Carter", "email": "carter@cs50.harvard.edu"}
]
for i in range(3):
print(f"Email {people[i]['name']} at {people[i]['email']}")
|
66b8472217e7fc3fc7197acf1af145020173ceb2 | rrothkopf/programming1.0 | /Labs/Ch4Lab.py | 4,576 | 3.84375 | 4 | '''
Chapter 4 Lab
Raven Rothkopf
9/30/19
'''
print("Welcome to Voyage! You are a sailor out on the sea in search of adventure. \nNot long ago, you saw a storm brewing far behind you and knew your boat was too small to survive it! \nChoose your actions wisely to get back to dry land, who knows what you might discover a... |
95cf5e0f5e52885fd607e6218cb79721fc31e87c | melike-eryilmaz/pythonProgrammingLanguageForBeginners | /inputs.py | 537 | 3.875 | 4 | #12/12/2020
#Kullanıcıdan veri almak için input() kullanırız ve input olarak alınan değerler string olarak alınır.
name = input('Please enter your name : ')
surname = input('Please enter your surname : ')
firstNumber = input('Please enter first number : ')
secondNumber = input('Please enter second number : ')
#inp... |
246db1cfcb31f7ba033febd460f483148afd8825 | matiek8/Python | /Horner_s_method.py | 1,116 | 3.859375 | 4 | """
Дан многочлен P(x)=a[n] xⁿ+a[n₋₁] xⁿ⁻¹+...+a[₁] x+a[₀] и число x. Вычислите значение этого многочлена, воспользовавшись схемой Горнера:
Формат ввода
Сначала программе подается на вход целое неотрицательное число n≤20, затем действительноечисло x, затем следует n+1 вещественное число — коэффициенты многочлена от ст... |
85c91709abafe50c918d184e5d872dc31b4ad0f8 | sphamv/fcc-python-projects-time-calculator | /time_calculator.py | 7,293 | 3.890625 | 4 | def add_time(*args):
MINUTES_DAY = 1440
MINUTES_WEEK = 10080
WEEKDAYS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
start = args[0]
duration = args[1]
try:
weekday = args[2].capitalize()
weekday_pos = WEEKDAYS.index(weekday)
except:
... |
788c103477b61d3e98ac05237573be6752fe9051 | Dwensdc/Upeu_practice1_FDP | /secuenciales/ejercicio3CLSS.py | 590 | 3.8125 | 4 | def muestraMenorEdad():
#Definir Variables y otros
pnombre=""
pedad=0
#Datos de entrada
p1nombre=input("Ingrese Nombre 1ra Persona:")
p1edad=int(input("Ingrese edad 1ra Persona:"))
p2nombre=input("Ingrese Nombre 2da Persona:")
p2edad=int(input("Ingrese edad 2da Persona:"))
p3nombre=input("Ingrese Nomb... |
163417296994290f4a1451ac8b1f1a2744fd5b1d | jrthorne/python_exercises | /Week2-questions/easy/draw_face.py | 2,913 | 4.53125 | 5 | # Draw a face by jason
#
# THE EXERCISE DESCRIPTION
#
# Use the 'turtle' package to draw a human face to the screen.
# Include as many features as you can - for example,
# start with a head and add eyes, eyebrows, mouth, ....
# A SOLUTION
#
# Problem solving strategy:
# 1. Import the turtle library
from ... |
f9bf9633d75bf991e9bc17eb1dcc3c3ed672c2a1 | donghL-dev/Info-Retrieval | /lecture-data/PythonBasics/003_list.py | 577 | 3.59375 | 4 | L=[]
L=['a','b','c','d']
print(L)
print(L[0])
print(L[-1])
print(len(L))
L.append('e')
del L[0]
s='-'.join(L)
print(s)
s='ZZZ ABC DEF GHI JKL'
print(s)
L=s.split()
print(L)
if 'ABC' in L: print('ABC is in L')
else: print('ABC is not in L')
for e in L:
print(e)
# end for
print()
for e in sorted(L):
print(e)
# end... |
9f113ee711350f75d8ad1cac6468a01265f900bb | xxpasswd/algorithms-and-data-structure | /other/binary_search_tree.py | 2,340 | 3.875 | 4 | """
二叉搜索树:
插入
查找
删除
"""
class BinaryTree:
def __init__(self, value=None):
self.value = value
self.right = None
self.left = None
@property
def root(self):
return self.value
def __str__(self):
return "{{{},{},{}}}".format(self.value, str(self.left), str(self.r... |
5cd43e3bd4e1f56f7832cb245d0c1d0d3f6bd7b2 | Sandhya-02/programming | /0 Python old/03_operators_rev.py | 658 | 4.15625 | 4 | # a = int(input("enter a number\n"))
a=int(input("enter a number\n"))
print("you have entered ",a)
print("enter a number")
a = int(input())
print("you have entered ",a)
a = "enter a number"
print(a)
num= int(input())
print("you have enteredd ",num)
#! =================================================
#* operators +... |
46bfc3a2574cb6235111f504071cbe6688d97a54 | Adriskk/sorting-algorithm-visualization | /algorithms/heap_sort.py | 847 | 4.125 | 4 | # => HEAP SORT ALGORITHM FILE
def heapify(arr, n, i, change):
largest = i
l = 2 * i + 1
r = 2 * i + 2
if l < n and arr[largest].size_Y < arr[l].size_Y:
largest = l
if r < n and arr[largest].size_Y < arr[r].size_Y:
largest = r
if largest != i:
arr[i], arr... |
e3550cdad749c05a9cb133dc531c503d4860cc77 | motasimmakki/Basic-Python-Programming | /SumUsingInput.py | 128 | 3.890625 | 4 | num1=input("Enter First Number")
num2=input("Enter Second Number")
sum=float(num1)+float(num2)
print("{0}".format(sum)) |
5c48518c70e85dc4aec7635bd7bfc98d1e5b8e5f | athelia/make-pairs | /make_pairs.py | 4,968 | 4.21875 | 4 | """
Script to make pairs. Requirements:
- Excluded pairs: never match this student with anyone in this list
- Tech levels: prefer to pair students who are within 3 levels
- Historical pairs: prefer to pair students who have not worked together
Data structure:
student_pairs = {
student_name: {
tech_level: ... |
c31560e204ecac5a01e50ca5efba0a908af77be8 | catlucht/learn-arcade-work | /Lab 12 - Final Lab/part_12.py | 22,067 | 4.3125 | 4 | class Room:
"""
This is the class for the room
"""
def __init__(self, description, north, south, east, west, up, down):
self.description = description
self.north = north
self.south = south
self.east = east
self.west = west
self.up = up
self.down = ... |
d42da86e51844053df950b6f890ef53c1c19fc28 | Th3Lourde/l33tcode | /563.py | 620 | 3.84375 | 4 | '''
Given the root of a binary tree, return the sum or
every node's tilt
The tilt of a tree node is the absolute difference between
the sum of all left subtree node values and all right subtree
node values
'''
from collections import deque
class Solution:
def findTilt(self, root):
self.treeTilt = 0
... |
0781721d53267a739e8f5bcd6638e13e27c54d57 | RutujaKaushike/DigitRecognitionMNIST | /DigitRecognition.py | 3,811 | 3.59375 | 4 | ##################
# Digit Recognizer
# Project by: Rutuja Kaushike (RNK170000)
# For Machine Learning : CS6375.502 F18 by Prof. Anurag Nagar
##################
#import packages keras
from keras import utils
from keras.layers import Dense, Reshape, Conv2D, Flatten,Dropout, MaxPool2D
from keras.models import Sequenti... |
8cfd11779e4b960b9624029650a159577a9219a6 | vskdtc/python-samples | /src/if.py | 569 | 4 | 4 | x = int(input("Gebe eine Zahl ein: "))
if x == 2:
print(x,'Ist eine Primezahl')
elif x == 3:
print(x,'Ist eine Primezahl')
elif x == 5:
print(x,'Ist eine Primezahl')
elif x == 7:
print(x,'Ist eine Primezahl')
elif x%2 == 0:
print(x,'Ist keine Primezahl, weil', x/2, 'A')
elif x%3 == 0:
... |
5b83db04a99f112dbe85931ffe4f58c5372e5ed7 | Fireaxxe/CSCU9YE | /Lab/Solutions/lab3.py | 5,045 | 3.71875 | 4 | # The knapsack problem
# Gabriela Ochoa
import os
import matplotlib.pyplot as plt
import random as rnd
# Single knapsack problem
# Read the instance data given a file name. Returns: n = no. items,
# c = capacity, vs: list of itmen values, ws: list of item weigths
def read_kfile(fname):
with open(fname, 'rU')... |
86f7b42c38a16e9134f85d312dd420d8c8739ac1 | NeSergeyNeMihailov436hdsgj/SummerP | /1A/15.py | 360 | 3.703125 | 4 | import datetime
def printTimeStamp(name):
print('Автор програми: ' + name)
print('Час компиляції: ' + str(datetime.datetime.now()))
a=list(map(int,input("Input numbers:").split(" ")))
if a[0]==int(0):
print("Error , first number can't be 0")
elif int(0) in a:
print(sum(a)/(len(a)-1))
printTimeSta... |
cdd8a90645d37b70a95c2389c891014053d9a4f2 | denis-belagro/skillfactory-module-6.10 | /B6.10/B6.10.2.py | 200 | 3.578125 | 4 | class Rectangle2:
def __init__(self, width, height):
self.width = width
self.height = height
p1 = Rectangle2(4, 7)
print("width = ", p1.width)
print("height = ", p1.height) |
b1c80eec5f77e068f2e7fb765ad225de3b84c102 | ProgFuncionalReactivaoct19-feb20/practica04-erickgjs99 | /practica.py | 1,232 | 3.734375 | 4 | """
autor = erickgjs_99
file = practica,py
"""
import codecs
import json
# para abrir el archivo
archivo = codecs.open("datos.txt", "r")
# para leer todas las lineas de cadenas del archivo
line_dic = archivo.readlines()
# para que se guarde todas las cadenas en una lista
line_dic = [json.loads(l) for l in line... |
89d74ea1d5e47a0f2f5bf4d95cd7dded36bd3f62 | sotirisnik/projecteuler | /prob45.py | 1,299 | 3.703125 | 4 | import math
def T( n ):
return ( 0.5 * n * ( n + 1 ) )
def P( n ):
return ( 0.5 * n * ( 3 * n - 1 ) )
def H( n ):
return ( n * ( 2*n - 1 ) )
def inverseT( x ):
"""
n * ( n + 1 ) - 2*x = 0
n^2 + n - 2*x = 0
D = b^2 - 4*a*g = 1 - 4*1*(-2*x) = 1 + 8*x
x1,2 = ( -b +- sqrt( D ) ) ... |
7cbd831519be43116a42b01129394c182d5413a8 | haedal-programming/teachYourKidsToCode | /function/clickKaleidoscope.py | 846 | 3.890625 | 4 | import random
import turtle
cursor = turtle.Pen()
cursor.speed(0)
cursor.hideturtle()
turtle.bgcolor("black")
colors = ["red","yellow","blue","green",
"orange","purple","white","gray"]
# 반사 효과를 만드는 만화경 함수
def draw_kaleido(x,y):
cursor.pencolor(random.choice(colors))
size = random.randint(10,40)
dr... |
67c5b04fc5d342b3cd72b6f250dee5016850309d | ggchangan/leetcodePython | /hamming_distance_461.py | 405 | 3.515625 | 4 | class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
return bin(x ^ y).count('1')
def main():
assert bin(7).count('1') == 3
assert bin(1).count('1') == 1
assert Solution().hammingDistance(1, 4) == 2
a... |
865113ad5dcefdfb86821ef0066aa4c472110e8d | makuznet/hse | /lesson-2_list_comprehension/lesson-2-hard-mode-1-while.py | 1,246 | 4.21875 | 4 | # Напишите код, который проверяет делимость числа на 5.
# Числа нужно выбрать из списка. Если число делится,
# алгоритм должен выйти из цикла и вывести на экран искомое число и строку "делится на 5".
# Если не делится, выводим на экран "это не делится на 5, продолжим поиск".
# Продолжаем пока не найдем такое, которое б... |
5f1fbacfab4c1c1a316c979426b377bbd936d7d2 | mandycrose/module-02 | /ch06_commandLine_Git/ch06_mandy.py | 1,328 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Dec 6 10:05:27 2018
@author: 612436112
"""
import sys
class Animal():
def __init__(self, name, age):
self.name = name
self.age = age
def eat(self):
print('yum')
class Dog(Animal):
def bark(self):
print('Woof!'... |
da75ed7c95a045281cc627e1afbc30aa460718e6 | AlanVenic/PythonExercicios | /ex040.py | 677 | 3.953125 | 4 | #crie um programa que leia duas notas de aluno e calcule sua media
#mostrando uma msg final de acordo com a media atingida
print('Verifique se você foi aprovado neste semestre.')
num1 = float(input('Digite sua primeira nota: '))
num2 = float(input('Digite sua segunda nota: '))
media = (num1 + num2)/2
if media < 5.0:... |
85adb749e77f514bb44c0227401ffd301b141e07 | runalb/Python-Problem-Statement | /PS-1/ps13.py | 337 | 4.09375 | 4 | # PS-12 WAP to check weather user inputted number is Armstrong or not
num = int(input("Enter no: "))
res = 0
no = num
len_no = len(str(num))
while(no!=0):
d = no%10
res = res + d ** len_no
no = no//10
if num == res:
print(num,"is a Armstrong Number ")
else:
print(num,"is not a Ar... |
534b0dd96d7a7838d5cfe6367866a7dc898c8d4c | mrinxx/Pycharm | /FUNCIONES/1.py | 941 | 4.03125 | 4 | def raices(a,b,c): #abro la funcion
discriminante=(b**2)-(4*a*c) #creo el discriminante para ver si es positivo o no (no puede ser menor que 0 una raiz)
if discriminante >= 0: #si el discriminante es mayor o igual a 0
r1=(-b + (discriminante ** 0.5)) / (2 * a) #raices positivas
r2=(-b - (discrim... |
e6e62a024f0ff8eba13c5ada89cc6b6ae96e9e6c | NIKsaurabh/python_programs1 | /programs/guessgame.py | 506 | 3.78125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 14 10:01:23 2019
@author: saurabh
"""
import random
cond=True
count=0
t=(random.randint(1,100))
while(cond):
user=int(input("Enter number : "))
if t>user:
print("enter greater number")
count+=1
elif t<user:
print... |
96c310134b9dd83b318c2c7617da1950200bbed2 | vxda7/end-to-end | /pre_learning/isitlower.py | 204 | 3.78125 | 4 | get = input()
cnt_upper=0
cnt_lower=0
for i in get:
if i.isupper():
cnt_upper+=1
elif i.islower():
cnt_lower+=1
print(f"UPPER CASE {cnt_upper}")
print(f"LOWER CASE {cnt_lower}")
|
9762d5ef31d70684a2a181e1567ff0fc0588b814 | sophialuo/CrackingTheCodingInterview_6thEdition | /1.1.py | 1,399 | 4.0625 | 4 | '''
Is Unique: Implement an algorithm to determine if a string has all unique characters. What if you cannot use a data structure?
'''
#with data structure
def is_unique(string):
count = {}
for char in string:
if char in count:
return False
else:
count[char] = 1
return True
#without data st... |
20ac1e597e23bd7a970e210ce798bcfa56bef21f | Cowboys21/python | /confusing.py | 205 | 3.984375 | 4 | name = 'Jennifer'
print(name [1:-1])
first = 'John'
last = 'Smith'
message = first + ' [' + last + '] is a coder'
msg = f'{first} [{last}] is a coder'
print(message)
print(msg)
print("python' in course")
|
f215130f504a80f7d62ffaf0ca949a25bc295536 | phaynes52/Code-Samples | /Game Design/hw1-game-loop-phaynes52/Argh Matey/Island.py | 10,750 | 3.625 | 4 | #Island.py
import Fight
import config
import Montauk
def landho():
raw_input("Pirate in the Crow's Nest: 'LAND HO!!!' ")
raw_input("Captain Blackbreath: 'All hands on deck! Head the masts toward the coast!' \nCaptain Blackbreath walks over to you.")
raw_input("Captain Blackbreath: 'Unfortunately this is wh... |
7ea001b9def2b51bb8473f008b06a31a48e85da8 | jjdblast/trafficLight | /trafficLight/geneticOptimization.py | 5,411 | 3.640625 | 4 | import random
import numpy as np
from trafficLight.visualization import showTrajectory
from trafficLight.evaluation import score
from trafficLight.simulation import Simulation
import trafficLight.constants as constants
import trafficLight.controller as controller
class GeneticOptimization(object):
"""
Conta... |
28f9b9756fd285ae633a792d48bb49a95e9ad43a | jeremyponto/ITP_Assignments | /Practice_Assorted_Problem_Number_ 13_Jeremy_Ponto.py | 475 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Nov 27 17:10:25 2019
@author: user
"""
verbs = ["try", "brush", "run", "fix"]
def makeForms(verbs):
new_verbs = []
for verb in verbs:
if verb[-1:] == 'y':
new_verbs.append(verb[:-1] + "ies")
elif verb[-1:] in ['o', 's', 'x', 'z'] or verb[-... |
b784e01c5b01a4193218e60ef87b4625fa4a92ff | GarvTambi/OpenCV-Beginners-to-Expert | /fetch_display_save.py | 897 | 3.609375 | 4 | import argparse # to pass the argument in the terminal
import cv2 # to import the library
# fetching the arguments and save in dictionary
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required = True, help = "Enter path to the image")
args = vars(ap.parse_args())
# loading and converting the i... |
bd53fc1b70a9efad6a0079f95ee760d0a1d78f0d | zilongxuan001/benpython | /ex19_0829.py | 669 | 3.53125 | 4 | def cheese_and_crackers(cheese_count, boxes_of_crackers):
print("You have %d cheeses!" % cheese_count)
print("You have %d boxes of crackers!" %boxes_of_crackers)
print("Man that's enough for a party!")
print("Get a blanket.\n")
print("We can just give the function numbers directly:")
cheese_and_crackers(20,30)
pr... |
75c26ef2a199981ccbb3ccb9db10429a2fff4dce | LesterTremens/Trivia | /test.py | 1,051 | 3.5625 | 4 | pygame.init() #Inciamos todos los modulos de pygame
pantalla = pygame.display.set_mode((0,0),pygame.FULLSCREEN) # Tamanio de la pantalla.
salir= False #Finaliza el evento principal.
reloj1 = pygame.time.Clock() #Reloj para actualizar los frames por segundo
blanco =(255,255,255) #Color en formato RGB
#Tipo de fuente a u... |
149dedafa32eac24e46908f55a0c8782ceba7b3f | aravindkoneru/Blackjack | /main.py | 2,193 | 3.75 | 4 | import dealer
import deck
import bank
import playerCommands
playingDeck = []
dealerHand = []
playerHand = []
totalAmount = 0
bet = 0
numDecks = 0
print "Welcome to blackjack. The ratio is 3:2"
#Allows the user to choose the number of decks that they will play with
while(numDecks == 0):
print "How many decks woul... |
842229b243012d225c94d70ff50fd8cabcae57f6 | ethanbar11/python_advanced_course1 | /lecture_3/examples.py | 375 | 3.640625 | 4 | # how to read from file
# file_stream = open('.\\text.txt', 'r')
# data_read = file_stream.readlines()
# print(data_read)
# file_stream.close()
# How to write to file
s = open('.\\text.txt', 'w')
s.writelines(['One\n', 'Two\n', 'Three'])
s.flush()
s.close()
# Sugar syntax of with
with open('.\\text.txt', 'r') as f:
... |
b6f4b1da9b05708856f0e61e3705bf68714ac3a1 | mag389/holbertonschool-machine_learning | /pipeline/0x00-pandas/0-from_numpy.py | 441 | 3.90625 | 4 | #!/usr/bin/env python3
""" creates pd dataframe from numpy """
import pandas as pd
def from_numpy(array):
""" creates pd.DataFrame from np.ndarray
array: np arr from which to create datafram
columns of pd.DataFrame labeled in alphabetical and capitalized
Returns: newly created pd.DataFrame... |
389eee775c643e3d7162be4d4af702c6c306b2f7 | amandamorris/hw6-sales-report | /sales_report.py | 1,896 | 3.640625 | 4 | """
sales_report.py - Generates sales report showing the total number
of melons each sales person sold.
"""
melon_sales = {}
melon_report = open("sales-report.txt")
for line in melon_report:
line = line.rstrip()
entries = line.split("|")
salesperson = entries[0]
dollars = entries[1]
... |
74fae66c32eaa98d357c3b2188c2b7707c0d3f7d | anilb0stanci/Solar | /satelite.py | 3,588 | 3.546875 | 4 | import math
import numpy as np
from numpy.linalg import norm
mass_sun = 1.989 * 10 ** 30
G = 6.674e-11
class Satelite(object):
def __init__(self, origin, target, color, size, mass, given_speed, angle,
radius_planet, planets):
self.color = color
self.size = size
self.mass ... |
1ee29032e3832aa3afa6ac5a7f84bd24c46fe327 | SirMatix/Python | /Sentdex/timeit tutorial.py | 322 | 3.53125 | 4 | import timeit
#print(timeit.timeit('1+3', number=50000))
input_list = range(100)
def div_by_five(num):
if num % 5 == 0:
return True
else:
return False
xyz = (i for i in input_list if div_by_five(i))
##xyz = [i for i in input_list if div_by_five(i)]
print(timeit.timeit('''''', number=5000)... |
42f9fb5933480956b867f4762411fea10a7e7e3f | midigo0411/Password-locker | /user.py | 494 | 3.96875 | 4 | class User:
'''
Class to create user accounts and save their information
'''
# Class Variables
# global users_list
users_list = []
def __init__(self,first_name,last_name,password):
'''
Method to define the properties for each user object will hold.
'''
# instance variables
self.first_name = first_name... |
28f2c73d5a9e194f591a27aaf2b46ed3786e36a6 | slideclick/pythonCode | /stackFrame.py | 1,726 | 3.75 | 4 | # -*- coding: UTF-8 -*-
# http://www.pythontutor.com/
# python.exe -m doctest stackFrame.py # stackFrame.py is argv to doctest.script
# from __future__ import print_function
import argparse
def foo():
""" simple funciton to demo LEGB and doctest
foo() won't out put at console.
To output you need prin... |
d5a9c6433d2390c541dafd49697014d6bf7f8d77 | kjjudy/BIOL5153 | /misc_lec/fib.py | 1,085 | 4.375 | 4 | #! /usr/bin/env python3
#import modules
import argparse
#define functions
def get_args():
#create an ArgumentParser object ('parser') thtat will hild all info necessary to parse command line
parser=argparse.ArgumentParser(description="This script returns the fibonacci number at a specified position in the fib... |
03e1dc04d3a31ec4815b4ee56e4abb1378b45aa0 | cybelewang/leetcode-python | /code944DeleteColumnsToMakeSorted.py | 1,829 | 4.15625 | 4 | """
944 Delete Columns to Make Sorted
We are given an array A of N lowercase letter strings, all of the same length.
Now, we may choose any set of deletion indices, and for each string, we delete all the characters in those indices.
For example, if we have an array A = ["abcdef","uvwxyz"] and deletion indices... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.