blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
716372e3033009476d2e08c1142b39cbca07d554 | AnhQuanTrl/kqueens | /queen_multi_constraint.py | 1,201 | 3.515625 | 4 | from typing import Dict, List
from constraint import Constraint, V, D
class QueenMultiConstraint(Constraint[int, int]):
def __init__(self, columns: List[int]) -> None:
super().__init__(columns)
self.columns: List[int] = columns
def is_satisfied(self, assignment: Dict[int, int]) -> bool:
... |
0017822b7071426624b33945d2ce1cdc75c07464 | golden-garage/PyGameWorkshop | /displayscr.py | 525 | 3.5 | 4 |
import pygame #This is to import the pygame library
pygame.init() #we need to initialise all the modules in pygame
gameDisplay = pygame.display.set_mode((1280,1024)) #gameDisplay is the name of the surface we create. The resolution of the screen is 1280x1024.
pygame.display.set_caption('Hello Wormy') #We want to s... |
9be0edba00fa13ea1f5eefbe785aa6cfc37c7f9a | benscruton/python_fundamentals | /coding_dojo_assignments/fundamentals/fun_ctions.py | 1,262 | 4.59375 | 5 | # Odd/Even:
# Create a function called odd_even that counts from 1 to 2000. As your loop executes have your program print the number of that iteration and specify whether it's an odd or even number.
def odd_even(max):
for i in range(1, max + 1):
quality = "odd" if i % 2 else "even"
print(f"Number: {i}. This... |
834f02c26737e97e99cddf2d07934e0c9d38b80d | toufiq007/Python-Tutorial-For-Beginners | /OOP/instance_method.py | 530 | 3.859375 | 4 |
# instance method
class Person:
def __init__(self,first_name,last_name,age):
self.first_name = first_name
self.last_name = last_name
self.age = age
def full_name(self):
full_name = self.first_name+ ' ' + self.last_name
return full_name
def is_avobe(self):
... |
efed3649aecb7e9b3ef667a3f2aba21540a1e070 | senel-study/kosmo-3rd | /s.yoon/kakao_2019_1/kakao4_proto.py | 564 | 3.5 | 4 | def muji(k, food_times):
tmp = 0
flag = True
if k >= sum(food_times):
food = -1
return food
while flag:
for i, _ in enumerate(food_times):
if food_times[i] is not 0:
food_times[i] -= 1
tmp+=1
if tmp == k+1:
i... |
370d077e96fae1268e4dd7756d8c9c2faa28abc1 | iancwwong/Text-Based-Adventure-Game | /src/FloodFillNode.py | 311 | 3.75 | 4 | # This class represents a node when using the flood fill algorithm
class FloodFillNode(object):
# Attributes
pos = {} # Position of node in the format {'x': X, 'y': Y}
items = [] # List of items possessed at this node
def __init__(self, nodePos, itemlist):
self.pos = nodePos
self.items = itemlist |
7bb5c2a83b9b1ddebaf097f5c511fc2c0c163380 | wezil/algorithmic-thinking | /1p-graph-degree-dist.py | 2,292 | 3.828125 | 4 | """
Degree distribution for graphs
Project 1, Algorithmic Thinking (Part 1)
This is a simple set of methods to analyze
the degree distribution of directed graphs
Author: Weikang Sun
Date: 6/4/15
Codeskulptor source:
http://www.codeskulptor.org/#user40_jdtGmYLlQ1_4.py
"""
# project 1 example directed graphs
EX_GRAPH... |
0b4b1a5261237823c6f066ae770ad0e2f411fa35 | sdbarnes/R1 | /3.2.1_nested_elif.py | 830 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Aug 4 10:31:43 2019
@author: Scott
"""
# - If you've been dating for at least 4 years, give them a
# dog ("dog").
# - If you've been dating for at least 1 year but less than
# 4 years, give them a watch ("watch").
# - If you've been dating for at least 6 months... |
d3cdbbea323c316d2be106f50b114b170a7e6340 | mhtehrani/Algorithms | /Knapsack_DynamicProgramming.py | 792 | 3.65625 | 4 | """
Knapsack without Repetitions (Dynamic Programming)
==================================================
@author: mhtehrani
September 17, 2021
https://github.com/mhtehrani
"""
def optimal_weight(W, w):
value = [0]*(len(w)+1)
for i in range(len(w)+1):
value[i] = [0]*(W+1)
#end
for i in r... |
a44931c323483e383c1969b69c62b2593fd049e3 | Carolusian/leetcode | /p1_add_two.py | 211 | 3.734375 | 4 | def two_sum(nums, target):
for k1, v1 in enumerate(nums):
for k2, v2 in enumerate(nums):
if v1 + v2 == target and k1 != k2:
return [k1, k2]
print(two_sum([3, 2, 4], 6))
|
f7c3f9d79a44402d2c45e16405789e82c1a2950c | dnknown1/okaj | /pygame/aisearchtools.py | 2,661 | 3.984375 | 4 | class Node:
"""
Base Node class: every states of actual problem to be converted into
this datastructure. A node representes each point in the problem set
"""
def __init__(self, state+None, action+None, cost+None):
self.state = state
self.action = action
self.parent = parent
self.cos... |
b37fbaa5a7fca0bef6d76332d8b69e5d05b1a37e | HOPExxp/QZ | /daya爬虫/8-18/bs4_test.py | 2,214 | 3.90625 | 4 | html = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1"><!-- Elsie --></a>
<a href="http:... |
f6b407bba48460f485a1d4f74f31bf87c86390c4 | kmurphy/coderdojo | /01-Guess_my_Number/code/Storing_Information.py | 58 | 3.640625 | 4 | x = 5
print(x)
print(x * 4)
x = "5"
print(x)
print(x * 4) |
504aa625dc6fdd7e415c3956390319f0ffaa4656 | starswap/WBGSAlgorithms | /Algorithms/Day 2 Bubble Sort/bubble sort.py | 819 | 4.21875 | 4 | #Python implementation of Bubble Sort by James
#array = [2,83,6,6,88,97,5,154,3,4,35,7,8,2,5,10,7,8,18]
sorted = False
def bubble_sort (array,sorted):
while sorted == False:
#sorted = False
changed = False # sets changed back to false
for i in range (len (array)-1):
if array[i]... |
8e0af157a922e32db42224e62987ccbbf9fc5069 | gimdongwon/Coding_Test | /Dongwon/Test_question/PriviousTest_Kakao/2020/Internship/keypad/keypad.py | 1,122 | 3.796875 | 4 | def solution(numbers, hand):
answer = ''
position = [[3,1], [0,0],[0,1],[0,2],[1,0],[1,1],[1,2],[2,0],[2,1],[2,2]]
left, right = [3,0], [3,2]
for number in numbers:
if number in [1,4,7]:
answer += "L"
left = position[number]
elif number in [3,6,9]:
ans... |
281958c094306433b35814ac89a8fb449b5a0952 | tahmid-tanzim/problem-solving | /Stacks_and_Queues/Min-Max-Stack-Construction.py | 1,665 | 4.15625 | 4 | #!/usr/bin/python3
# https://www.algoexpert.io/questions/Min%20Max%20Stack%20Construction
"""
Write a MinMaxStack class for a Min Max Stack. The class should
support:
1. Pushing and popping values on and off the stack.
2. Peeking at the value at the top of the stack.
3. Getting both the minimum and the maxim... |
9de4ef74ed3e7d2bb116c2433768aeb1a252b98b | JormanWell/exercicios | /Range exercice.py | 307 | 3.875 | 4 | # [1, 2, 3] --> 6
count = 0
for number in range(1, 4):
count = count + number # nova contagem + a velha contagem
print(count)
# outro modo de fazer
def sum_list(my_list):
count = 0
for number in my_list:
count = count + number
print(my_list)
print(count)
|
8a033b947cffe225b5ad6c2a4a990a9e32230948 | AJayTheProgrammer/developing-journey | /FindBirthdayDay.py | 223 | 3.828125 | 4 | import datetime
import calendar
def findDay(date):
born = datetime.datetime.strptime(date, '%m %d %Y')
day = born.weekday()
return calendar.day_name[day]
date = '01 02 1999'
print(findDay(date))
|
3ed341a5c740470e34ccbbe91add4ef8b1523d8a | DanielPravitz/DesignPatterns | /taxes.py | 2,026 | 3.59375 | 4 | from abc import ABCMeta, abstractmethod
from budget import Budget
class Tax(object):
def __init__(self, tax= None) -> None:
super().__init__()
self.__tax = tax
def calculate_another_tax(self, budget: Budget) -> float:
if self.__tax is None:
return 0
return self._... |
5558ec47e4fa41a2d38043069a0d933024cbebb0 | poszy/UdacityDA | /Week 10 - Sorting Algorithms/BubbleSort.py | 2,037 | 4.5 | 4 | # In-place : an algorithm that sorts the data inside the data structure without having to copy over the data to a new datastructure
# Naive Approach: whatever comes to mind to solve the problem, there will always be a better way.
# ITs important to know the time complexity of sorting algorithms.
# Bubble sort
# Give... |
9cd467c15625206ce18e3022ddb764aa191e2934 | cielliyuanpeng/learn_Python_in_hard_way | /ex31.py | 1,850 | 3.890625 | 4 | while True:
door = input("""
你从黑暗中醒来
此时,你身处一个幽暗的房间之中,你的面前有两扇门。\n
一扇门上是白底黑字的生,另一扇门上是黑底白字的死\n
请问您选择进入哪一间?\n
1.生门 2.死门
""")
if door == "1":
print("""
你推开生门,进入其中
发现是一片阳光明媚的草地
草地上鲜花盛开,阳光和煦,微风习习
不远处仿佛有一口水井,一位朴素打扮的妇人正在打水
此时,她也看到了你
请问要和他打招呼吗?
1. 打招呼 2.视而不见
... |
ca2ebf61520ac779a77e0a11642064836c805a3e | Sbarj130917/Implementing_Algorithms---Python | /inplace_quicksort.py | 1,097 | 4.125 | 4 | # array_to_be_sorted[] = Array which is to be sorted,
# low = Starting index of the array,
# high = Ending index of the array
def array_partition(array_to_be_sorted,low,high):
pivot = array_to_be_sorted[high] # last element of the array is being taken as pivot
x = ( low-1 )
for y in range(low , h... |
2ddfd43fb293816cb720943766c2e718bd0e029f | pxz97/AlgorithmsByPython | /BasicAlgorithms/Tree/InorderTraversal.py | 453 | 3.71875 | 4 | def inorderTraversal_recur(root):
if not root:
return []
return inorderTraversal_recur(root.left) + [root.val] + inorderTraversal_recur(root.right)
def inorderTraversal(root):
stack = []
res = []
cur = root
while stack or cur:
if cur:
stack.append(cur)
c... |
8c4c454418f227b26a07a4f5687a513c3eb3f6e4 | anucoder/Python-Codes | /02_Strings.py | 837 | 4.25 | 4 |
mystring = 'Hello world'
print(mystring)
#indexing
print(mystring[0])
#negative indexing
print(mystring[-1])
#slicing
print(mystring[2:]) #strat at index 2 and print all the way to end
print(mystring[:3]) #strat at index 0 atill the index 2 (not including 3)
print(mystring[2:5]) #strat at index 2 and till 4
print(m... |
2b69fa88dc67644b1ac8ad890c8db3994157fdef | digrawal/python_lover | /healf_man_sys.py | 4,752 | 3.90625 | 4 | def getdate():
import datetime
return datetime.datetime.now()
"""print("enter the name of the person among rahul ,lokesh and pappu you want operate\n")
s=input()
if s== "rahul":
print("write,what do u want log or retrive\n")
lg=input()
if lg=="log":
print("write exercise or food to ... |
3bf2c2d2f805fa388e175413c58556a0ba984a3e | astikanand/Interview-Preparation | /Data Structures/11. Advanced Data Structures/2_avl_tree.py | 5,111 | 3.984375 | 4 | class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
self.height = 1
def insert(root, key):
###### Step-1: Perform Normal BST insertion.
if not root:
return Node(key)
elif key < root.val:
root.left = insert(root.left,... |
361335629a6e686797a8c5805f67e1f10a9b3b99 | endrepapp/quadratic_solver | /Egyenlet1.0/python1.py | 969 | 3.75 | 4 | from math import *
print ("Equation: ax^2 - bx + c = 0. Press ENTER to start")
def szam_beker(betu):
return int(input("Kerem adja meg az {} - erteket: ".format(betu)))
def neg_szamolas(a,b,c):
if (a == 0 & b == 0 & c == 0):
print ("nem angolozok , ilyen ertek nincs ")
else:
... |
36399265d984fe1c54f6da90585ae64668d3304a | Divisekara/Python-Codes-First-sem | /PA1/PA1 2013/PA1/PA1-13/2013 - PA1 - 13 - Triangular Matrix.py | 834 | 3.96875 | 4 | #PA1 - 13 - Triangular Matrix
a = 1
while (a):
try:
N = int(raw_input("Enter N (where 1<N<10 for size NxN square matrix) = "))
print "Enter the matrix row by row, seperating the elements with spaces."
matrix = []
if N>=10 or N<2:
print "Invalid Input! Enter N in corr... |
e784030323fbe3b54b47858032fc826c35e2643a | gguillamon/PYTHON-BASICOS | /python_ejercicios basicos_III/listas/ejercicio2.py | 340 | 4.34375 | 4 | # Crea una lista e inicializala con 5 cadenas de caracteres leídas por teclado.
# Copia los elementos de la lista en otra lista pero en orden inverso,
# y muestra sus elementos por la pantalla.
lista=[]
for x in range(5):
palabras=input("Introduce una palabra: ")
lista.append(palabras)
lista2=[]
lista2=lista
... |
7c27a19bc69f5621e480fc3f42f85b93cb99d612 | paa-coder/geek_dev_ops | /python/base/hw_7.py | 2,141 | 3.796875 | 4 | import random
import math
separator_task = "*"*100
def separete(something,separator):
print()
print(separator,something,separator)
print()
separete("task №1",separator_task)
fruits = [
"яблоко","банан","апельсин",
"ананас","персик","лимон",
"мандарин","груша","киви"
]
def get_random_fr... |
c4d5de9a77014f8277bda5a2fd2060b217d6142e | swl5571147a/stone | /notes/example/guess.py | 393 | 3.875 | 4 | #!/usr/bin/python
#coding:utf8
import random
num = random.randint(1,20)
for i in '123456':
guess = input('Please enter your guess number:')
if guess == num:
print 'you are right!'
break
else:
if i == '6':
print 'you are so .....'
break
if guess > num:
print 'your enter number is large'
continu... |
9918272a5907caf7e55b77fa190ca5392e7c337d | david8388/Python-100-Days | /Project/LeetCode/singleNumber1.py | 567 | 3.5625 | 4 | from typing import List
# Runtime: 8900 ms
# Memory Usage: 16.2 MB
#class Solution:
# def singleNumber(self, nums: List[int]) -> int:
# for i in range(len(nums)):
# newNums = nums[:i] + nums[i+1:]
# if nums[i] not in newNums:
# return nums[i]
# Runtime: 80 ms
# Memory ... |
8ad5453b925ae4a840ba8a58523d7eac816ce737 | reinderien/pyais | /pyais/util.py | 1,895 | 3.890625 | 4 | from bitstring import BitArray
from math import ceil
def split_str(string, chunk_size=6):
"""
Split a string into equal sized chunks and return these as a list.
The last substring may not have chunk_size chars,
if len(string) is not a multiple of chunk_size.
:param string: arbitrary string
:p... |
672721c17dbf40311d0489e93a8f413c5b7d0e58 | Omar7102/fundamentos | /NumeroPar.py | 189 | 4 | 4 | #Programa que muestra si un numero es par
print('Digite el numero')
n=int(input())
if (n % 2) == 0 :
print ('el numero', n, 'es par')
else:
print ( 'el numero', n,'no es par') |
5ad72e3d56246bc745fb208eb7e8a74860c66a3d | srgiola/UniversidadPyton_Udemy | /Fundamentos Python/Manejo de Archivos.py | 1,214 | 3.78125 | 4 | #Abre un archivo
# open() tiene dos parametros, el primero el archivo y el segundo lo que se desea hacer
# r - Read the default value. Da error si no existe el archivo
# a - Agrega info al archivo. Si no existe lo crea
# w - Escribir en un archivo. Si no existe lo crea. Sobreescribe el archivo
# x - Crea un archivo. Re... |
ca47529e8a6d7f4d3ee7ac77e6fc1771ac86be49 | sigudi-kevin/Python_Coursework | /MS-Python-Pre-work/Input/input_demo.py | 2,231 | 4.03125 | 4 | import sys
name = sys.argv[1]
age = sys.argv[2]
# print("How old are you?"))#Comment out to run and vice versa
# age = int(input())
print(name)
print(age) #Prints name and age if initiated with both name and age
list_a = list(range(0,5))#Comment out to run and vice versa
print(list_a)#Displays list from 0 to 5
#
#... |
91318b684dd0048957a405293d1c53b8978350db | friesia/simple-one | /smp.py | 3,532 | 4.28125 | 4 | #!/usr/bin/python
# a selection of simple Python code to give you a taste of the language ...
#
# Just a few notes about Python:
# Python has a very efficient built-in memory manager.
# Python does not need variable types declared, it is smart enough to figure that out!
# Python uses whitespaces to group statements, t... |
dbf04ba79765e0f081ea5e542337bbac872a373b | linzowo/GAME_PRACTICE | /bullet.py | 1,011 | 3.796875 | 4 | #_*_ coding: utf_8 _*_
import pygame
from pygame.sprite import Sprite
class Bullet(Sprite):
"""子弹类"""
def __init__(self,ai_seting,screen,ship):
"""在飞船所在的位置创建一个子弹"""
super(Bullet,self).__init__()
self.screen = screen
#在(0,0)处创建一个表示子弹的矩形,再设置正确的位置
self.rect = pygame.Rect... |
01db9994201559853877b178796bdc90fd899852 | UWPCE-PythonCert-ClassRepos/Self_Paced-Online | /students/alexLaws/lesson03/mailroom.py | 3,484 | 3.796875 | 4 | #!/usr/bin/env python3
donor_list = []
donor_list.append({'Name': 'Ryan Moore', 'Donation': 500})
donor_list.append({'Name': 'Ryan Moore', 'Donation': 250})
donor_list.append({'Name': 'Ted Laws', 'Donation': 1000})
donor_list.append({'Name': 'Ted Laws', 'Donation': 100})
donor_list.append({'Name': 'Ben Snell', 'Donati... |
cca8b31e57912b86d8ccb58fc48cfa4835ceb7ae | Prashambhuta/learn-python | /learnpython.org/decorators-understanding-day17.py | 1,613 | 4.03125 | 4 | @decorator
def function(arg):
return "value"
# # is same as
def function(arg):
return "value"
function = decorator(function)
#repeater function
@repeater
def multiply(num1, num2):
print(num1 * num2)
multiply(22,2)
# To change the output
def double_out(old_function):
def new_function(*args, **kwd... |
287c342c34b79cc82231195306a25bdd7e9c8233 | chriswolfdesign/MIT600OCW | /master/psets/pset2/ps2_hangman.py | 2,780 | 4.09375 | 4 | # 6.00 Problem Set 3
# Name: Chris Wolf
# E-mail: chriswolfdesign@gmail.com
# Time: 1:30
# Hangman
#
GUESSES_MAX = 8
# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
import random
import string
WORDLIST_FILENAME = "words.txt"
def load_words():
"""
Returns a lis... |
749764584851352a9b75bea122be980208f29f44 | exapde/Exasim | /src/Python/Preprocessing/testing.py | 642 | 3.609375 | 4 |
# a = 1;
# b = a + 1;
# d = a+b*3;
# print("hello")
# print("here")
# print(d)
# import matplotlib
# matplotlib.use('Qt5Agg')
# # This should be done before `import matplotlib.pyplot`
# # 'Qt4Agg' for PyQt4 or PySide, 'Qt5Agg' for PyQt5
# import matplotlib.pyplot as plt
# import numpy as np
#
# t = np.linspace(0, 20... |
91fe757fe0b7980dc5cc820f64172fdb000c4119 | Saswati08/Data-Structures-and-Algorithms | /Trees/leaves_to_DLL.py | 1,537 | 3.84375 | 4 | class Node:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def convDLL(root):
if root == None:
return
elif root.left == None and root.right == None:
root.right = convDLL.hd
... |
04384c0addb3f96c5c0794cea200a1bbcc135bf6 | Psychotechnopath/timeit | /timeitchallenge.py | 1,190 | 4.59375 | 5 | # In the section on Functions, we looked at 2 different ways to calculate the factorial
# of a number. We used an iterative approach, and also used a recursive function.
#
# This challenge is to use the timeit module to see which performs better.
#
# The two functions appear below.
#
# Hint: change the number o... |
d2c3fa601d2de8ddb377c69c20ea7a9a9cf508f1 | franklingu/leetcode-solutions | /questions/find-if-path-exists-in-graph/Solution.py | 2,044 | 4.09375 | 4 | """
There is a bi-directional graph with n vertices, where each vertex is labeled from 0 to n - 1 (inclusive). The edges in the graph are represented as a 2D integer array edges, where each edges[i] = [ui, vi] denotes a bi-directional edge between vertex ui and vertex vi. Every vertex pair is connected by at most one ... |
70652b567c13f74a6aba2944b421fe213b7926c7 | dataholicguy/how-to-think-like-a-cs | /chap08/ex04.py | 431 | 4.28125 | 4 | def count_letters(strng, letter):
""" return the number of a character in a string. """
count = 0
start = 0
while start < len(strng):
if strng.find(letter, start) != -1:
count += 1
start = strng.find(letter, start) + 1
else:
start += 1
return count... |
485197a8519d157d53f03fcbcb6d08440fbe1a93 | RibhuProPower/python_classes | /week_04/hw1.py | 141 | 4.1875 | 4 | n = int(input("enter a number"))
if ((n%2) == 0) :
print (str(n)+" is divisible by 2")
else :
print(str(n) + " isn't divisible by 2") |
631944dfacfd30cae33471f2909d6cd03be271bf | ddsha441981/Python-Sample-Code | /chapter_04_Lists_Tuples/practice_04/practice_02.py | 602 | 3.796875 | 4 | # Author: Deendayal Kumawat
""" Date: 11/12/19
Descriptions: List And Tuples """
# List is a just like container which store set of value of any data type
# Create a list using []
print("*********List and Tupples*********")
std1 = input("Enter marks of student 1 \n")
std2 = input("Enter marks of student 2 \n")
std3 = i... |
32c7a56faa4532ef3a808c25c0cdfd73947f00e6 | ryoman81/Leetcode-challenge | /LeetCode Pattern/8. LinkedList/234_easy_palindrome_linked_list.py | 1,540 | 4 | 4 | '''
Given a singly linked list, determine if it is a palindrome.
Example 1:
Input: 1->2
Output: false
Example 2:
Input: 1->2->2->1
Output: true
Follow up:
Could you do it in O(n) time and O(1) space?
'''
# Import helper class ListNode in this folder
# It is the same as LeetCode one with additional methods show() and... |
9dfe4469688c6a636a0801bef87e898825a3242c | fangzli/Leetcode | /src/RecursiveFibonacci.py | 1,602 | 4.40625 | 4 | # Method 1: recursive, slow, no memory of previously calculated value
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
# print(fib(5))
# Method 2: iterative
def fibi(n):
a, b = 0, 1
for i in range(n):
a, b = b, a + b
return a... |
97048cf96b8646be37ebc8df972cf0df6040434e | Jonathan-Nuno/Assignments | /week_1/d1-a2.py | 192 | 4.4375 | 4 | ### Assignment 2 - Even Odd
print("Is your number even or odd?")
num = int(input("Please enter your number: "))
if (num % 2) == 0:
print(f"{num} is Even")
else:
print(f"{num} is Odd") |
17958210b05b01a4dcca948fc9193bbea88fb35c | lrana-227/RBootCamp | /cw/0-3Python/7/08-Stu_RockPaperScissors/Unsolved/RPS_Unsolved.py | 1,520 | 4.40625 | 4 | # Incorporate the random library
import random
# Print Title
print("Let's Play Rock Paper Scissors! There are three trys!")
# Specify the three options
options = ["r", "p", "s"]
# Computer Selection
for x in range(3):
computer_choice = random.choice(options)
# User Selection
user_choice = input("Make your C... |
8ec5896d68b345602822883958da1dcc5c4da926 | moamen-ahmed-93/hackerrank_sol | /python3/re-group-groups.py | 155 | 3.65625 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import re
r = re.search(r'([a-zA-Z0-9])\1+',input())
print(r.group(1) if r else -1)
|
48fc5c88c16d5fec9bfe5c7382c0a650879c166d | Caioseal/Python | /Aulas/aula16a.py | 551 | 3.96875 | 4 | #Variaveis compostas no Python: Tuplas, Listas e Dicionários
#Tupla = variável que cabem 4 valores. Até agora, variável só recebia 1 valor.
#Tuplas são imutáveis
# lanche = [hamburguer, suco, pizza, pudim]
#print(lanche[2]) - pizza
#print(lanche[0:2]) - hamburguer e suco - o fatiamento exclui o último
#print(lanc... |
aa4bc52016ad5fdc4b4350ccbcd981b2018e2917 | techkang/wordCloudZn | /deleteSingleWord.py | 1,441 | 4.0625 | 4 | # -*- coding:utf-8 -*-
'''
This python file is used to delete auxiliary words in freq.txt.
'''
class DeleteSingleWord():
def __init__(self, srcfile='src.txt', desfile='notionFreq.txt', cutlen=50, enconding='utf-8'):
self.srcfile = srcfile
self.desfile = desfile
self.cutlen = cutl... |
a6b4490784f51efcdffe80bd02764e20b16af249 | lilsweetcaligula/sandbox-codewars | /solutions/python/209.py | 293 | 3.59375 | 4 | def two_sum(values, result):
from collections import OrderedDict
lookup = OrderedDict({ value: index for index, value in enumerate(values) })
for index, x in enumerate(values):
y = result - x
if y in lookup:
return [index, lookup[y]]
return [-1, -1] |
a9e161b6d590f8bfc9694e8ba9bded44c881f142 | JeromeLefebvre/ProjectEuler | /Python/Problem058.py | 1,297 | 3.5 | 4 |
'''
Problem 58
Starting with 1 and spiralling anticlockwise in the following way, a square spiral with side length 7 is formed.
37 36 35 34 33 32 31
38 17 16 15 14 13 30
39 18 5 4 3 12 29
40 19 6 1 2 11 28
41 20 7 8 9 10 27
42 21 22 23 24 25 26
43 44 45 46 47 48 49
It is interesting to note that the odd sq... |
18bbb23d04c94705145c4ac20b0966a016c007ea | lxr0804/pythonProject | /条件语句/列表推导式.py | 241 | 3.5625 | 4 | girls = ['alice', 'elena', 'crelin']
boys = ['alark', 'ckjjfa', 'eamon']
letterGirls = {}
for girl in girls:
letterGirls.setdefault(girl[0], []).append(girl)
print letterGirls
print [b + "+" + g for b in boys for g in letterGirls[b[0]]]
|
4c5acd7a9505090b8a92aae3cbb6abe64d9a55f2 | renanstn/exercicios-uri-online-judge | /1143.py | 231 | 3.515625 | 4 | # Exercicio referente ao problema numero 1143 do URI ONLINE JUDGE.
# https://www.urionlinejudge.com.br/judge/pt/problems/view/1143
# Por: Renan Santana Desiderio
n=input()
for i in range(n+1):
if i!=0:
print "%i %i %i" %(i, i**2, i**3) |
742add3de321d0b9be299faee3106625504ae7c3 | sarahkorb/PythonProjects | /Lab3_Dartmouth_Map/load_graph.py | 2,492 | 4 | 4 | #CHECKPOINT
#function to load the data and create a graph data structure and a dictionary of vertices
#Author: Sarah Korb
#Oct. 31 2018
#Professor Cormen- CS1
from vertex import *
def load_graph (file):
vertex_dict = {} #create a dictionary
in_file = open(file, "r")
for line in i... |
dd1a193019ef68796bd5f024784fa6c597ebd9f5 | shivanikarnwal/Python-Programming-Essentials-Rice-University | /week3/comparisons.py | 628 | 4.0625 | 4 | """
Demonstration of arithmetic comparisons
"""
# Six different arithmetic comparison operators
print("Comparisons")
print("===========")
print(7 > 3)
print(7 < 3)
print(7 >= 3)
print(7 <= 3)
print(7 == 3)
print(7 != 3)
print("")
# Using comparisons to get a boolean value
print("Comparing Variables"... |
4e825688a2d20922739b7a681e2262049cc53831 | jasmintey/pythonLab6 | /hello.py | 1,660 | 3.90625 | 4 | """
a=10
b=12
print('a > b is', a>b)
a = True
b = False
print('Combine result of a and b is', a and b)
a = [1,2,3]
b = [1,2,3]
c = b
print(a is b)
print(c is b)
import math
print(math.pi)
x = "python" + " exercise"
str.title(x)
print(x)
mark1 = float(input("Please enter mark "))
mark2 = float(input("Please enter ... |
cf235ec047ded3018968233914a6d5e4b3cea404 | ivy2350442/Leetcode_challenge | /876_Middle_of_the_Linked_List.py | 487 | 3.765625 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def middleNode(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
s, f = head, head
... |
1c52cabacf6958d664ea9d4803faa7109f4ce2ea | Ynjxsjmh/PracticeMakesPerfect | /LeetCode/p0239/I/sliding-window-maximum.py | 2,175 | 3.875 | 4 | # -*- coding: utf-8 -*-
# ********************************************************************************
# Copyright © 2022 Ynjxsjmh
# File Name: sliding-window-maximum.py
# Author: Ynjxsjmh
# Email: ynjxsjmh@gmail.com
# Created: 2022-06-28 10:03:33
# Last Updated:
# By: Ynjxsjmh
# Description: You are giv... |
91d63545f1869326d26d904eea4f84234fba3524 | Giby666566/programacioncursos | /integralpolinomio.py | 626 | 3.921875 | 4 | #Pedimos los limites de nuestra integral a y b
a=int(input("Dame el limite inferior de la integral\n"))
b=int(input("Dame el limite superior de la integral\n"))
#Calculamos b-a porque es la evaluacion de x de la integral definida de un polinomio de grado n
grado=0
integral=0
coeficiente=0
#Hacemos un ciclo mientras el ... |
d9d4a4dce516cb9309e54b4bc987c0ff0587254d | bakcoder/study_deepLearning | /loss_function.py | 1,228 | 3.640625 | 4 | import numpy as np
from study_deepLearning.dataset.mnist import load_mnist
# 평균 제곱 오차
def mean_squared_error(y, t):
return .5 * np.sum((y-t)**2)
# 예1 : '2'일 확률이 가장 높다고 추정
t = [0, 0, 1, 0, 0, 0, 0, 0, 0, 0]
y = [.1, .05, .6, .0, .05, .1, .0, .1, .0, .0]
print(mean_squared_error(np.array(y), np.array(t)))
# 예2 : ... |
536f1a9799c80113d38b2208b9a0664f87547a96 | kmboese/machine-learning | /k-means-clustering/k_means.py | 3,090 | 4.03125 | 4 | #Program that performs k-means clustering on a set of tuples
from math import sqrt
from collections import defaultdict
import random
centroid_count = 3
#Returns the distance between two 2-value tuples
def distance(p1, p2):
return(sqrt((p1[0]-p2[0])**2 + (p1[1]-p2[1])**2))
#Randomly chooses k points from a dictio... |
a456a46b2cafd639cb2dece778dd12ec8b910e79 | MhmDSmdi/Classical-Search | /SearchAlgorithms/graph/state.py | 599 | 3.59375 | 4 | class State:
def __init__(self, state_name, total_cost, parent_state, action_description, distance):
self.total_cost = total_cost
self.parent_state = parent_state
self.action_desc = action_description
self.state_name = state_name
if distance is not 0:
self.root_di... |
90dd0e84d740f28ce82ea483746e9ca079d33377 | jdf/processing.py | /mode/examples/Basics/Image/LoadDisplayImage/LoadDisplayImage.pyde | 570 | 3.671875 | 4 | """
Load and Display
Images can be loaded and displayed to the screen at their actual size
or any other size.
"""
def setup():
size(640, 360)
# The image file must be in the data folder of the current sketch
# to load successfully
global img
img = loadImage("moonwalk.jpg") # Load the image int... |
3519dc260e65c7d3b23aa3728523149dd9a16deb | Moris-Zhan/Udemy_Course | /Python/Complete Course/Spyder/MatPlotlib/MatPlotLib_Introduce.py | 269 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 9 15:08:13 2017
@author: Leyan
"""
import matplotlib
import matplotlib.pyplot as pt
rotal_x = [1,2,3,4]
rotal_y = [3,8,10,25]
pt.title('figure1')
pt.xlabel('Label_x')
pt.ylabel('Label_y')
pt.plot(rotal_x,rotal_y)
|
648852ebb2e4442d003e3e796bb3133a71b2ec51 | RyujiOdaJP/python_practice | /ryuji.oda19/week02/c30_int_list.py | 243 | 3.578125 | 4 | def int_list(L):
if len(L) == 0:
return False
else:
try:
X = [isinstance(L[i],int) for i in range(len(L))]
print(X)
return all(X)
except TypeError:
return False
|
1d6054781b795d6164e98486f3b23df2d1e4a2d0 | Touchfl0w/python_practices | /advanced_grammer/practice1-10/practice7/p1.py | 584 | 3.671875 | 4 | s = 'ab;cd|efg|hi,jkl|mn\topq;rst,uvw\txyz'
a = s.split(';')
print(a)
t = []
XXX = 'xxx'
def test(x):
y = x.split(',')
#作为参数的函数与普通函数并无区别,可以访问到全局变量XXX以及t
y.append(XXX)
return t.extend(y)
x = map(test,a)
#打印出t的结果并未改变值,不是因为作为参数的test()不能访问全变量,而是因为Python3中的机制
#执行map()后仅返回map object,并未进行完整的映射计算
print(t)
#对map object 执... |
dcf12d6d45d3555cd2adec8c62d5ece59aa87280 | MarcosQiu/beauty-of-algorithm | /python/binary_tree/tree_traversal.py | 1,193 | 3.75 | 4 | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def pre_order_traversal(node):
if node is None:
return []
left_subtree_traversal = pre_order_traversal(node.left)
right_subtree_traversal = pre_order_traversal(node.right)
return [node.val... |
498f5ee8600470f43c7bdadb6179cdb5064e6bba | rajib-nh/demo1 | /calculator.py | 5,101 | 4 | 4 | #!/usr/bin/python
from tkinter import *
import math
from PIL import ImageTk, Image
import os
root = Tk()
root.title("Simple Calculator")
root.resizable(0,0) ## Disable maximize button
## set window icon
root.iconphoto(False, PhotoImage(file='/home/rajib/PYTHON-programme/gui-tkinter/calculator-project/icon-calculator.... |
befcb2f45a076b695fac24a3c6bb4b52302285b0 | stanislasveronical/Python | /20170309_Arithméthique/Division successives par 2 (EX 1 et 3).py | 527 | 3.890625 | 4 | #EXERCICE 1
n= int(input("Entrer l'entier à convertir : "))
bin , q = [ ],n
while q//2 !=0:
bin = [q%2] + bin
q = q//2
bin = [q%2] + bin
print("L'écriture binaire de l'entier",n,"est ")
for k in range(len(bin)):
print(bin[k],end=' ')
#EXERCICE 3 : Conversion Inverse
print("\n")
bin ... |
7a5f3c872aba432bdadbac62a8915ad2f97e5a27 | KohsukeKubota/Atcoder-practice | /the_longest_distance.py | 339 | 3.53125 | 4 | from math import sqrt
N = int(input())
coordinate = [list(map(int, input().split())) for i in range(N)]
res = -1
for i in range(N):
for j in range(N):
a = coordinate[i]
b = coordinate[j]
dist = sqrt((a[0]-b[0])**2 + (a[1]-b[1])**2)
if res < dist:
res = dist
print('{:... |
d4673cb5494ea1e07474a9cc8504e2568c4f0c5d | jamilahhh21/PYTHON-PROGRAMS | /fieldarea.py | 311 | 3.84375 | 4 | '''AREA OF FIELD'''
l=float(input('Length of field in feet ='))
w=float(input('Width of field in feet ='))
area=l*w
print('''
Length of field in feet = %f feets
Width of field in feet = %f feets
Area of field in square feets = %f
Area of field in acres = %f
'''
%(l,w,area,area/43560)) |
c59ae0cb01e9e42a2a925f6b44aef08ddf5071ce | KatieStevenson/cp1404practicals | /prac_02/string_formatting_examples.py | 687 | 4.28125 | 4 | #STRING FORMATTING -----------------------------------------------------------------------------------------------------
# TODO (1): Use string formatting to produce the output: "1922 Gibson L-5 CES for about $16,035!". (Notice where the values go and also the float formatting / number of decimal places.)
name = "Gibs... |
95d35d1a7e9ae503a672b0937e0d8b4f9ec4b368 | EpicAdvt/options | /tests/test_conversion.py | 636 | 3.8125 | 4 | """
http://www.optiontradingpedia.com/conversion_reversal_arbitrage.htm
"""
from options import PutOption, CallOption
from options.conversion import ReverseConversion, Conversion
def test_conversion():
und_price = 51
strike = 51
c = CallOption(strike, bid=2.5, ask=2.5)
p = PutOption(strike, bid=1.50, ask=1.50... |
7871dd9b589f6e4f6981719824d23541fc656b7c | minahosam/python-examples | /92.py | 504 | 4.03125 | 4 | class employee:
empname=[]
empadress=[]
empid=[]
empsalary=[]
def empinfo(mine):
return mine.empname , mine.empadress ,mine.empid,mine.empsalary
def printd(mine):
print(mine.empinfo())
emp=employee()
for i in range(3):
emp.empname.extend(input('enter employe name'))
emp.... |
bfc5d0992415ca326371e1c163674f88d32bafb9 | gengwg/Python | /create_managed_properties.py | 1,095 | 4 | 4 | # add type checking to getting or setting of an instance attribute.
# only works in py3
class Person:
def __init__(self, first_name):
self.first_name = first_name
# getter function
@property
def first_name(self):
return self._first_name
# setter function
@first_name.setter
... |
18da5832df489204cc8df1d6e8600d8683b0bf3a | SaidTheCoder/Pr105 | /SD2.py | 789 | 3.890625 | 4 | import csv
import math
with open("data2.csv",newline='') as f:
reader=csv.reader(f)
file_data=list(reader)
data=file_data[0]
#step 1 Finding mean
def mean(data):
n=len(data)
total=0
for x in data :
total+=float(x)
mean= total/n
return mean
#step 2 squaring and... |
b77292d9885301d655573fe56b71079fdfe56e3c | szymon-m/playground | /hackerrank/25-03-2020/nested_functions.py | 882 | 3.765625 | 4 | def get_nested_scores(how_many_scores, name_scores_list):
db = []
[db.append([x[0], x[1]]) for x in name_scores_list]
return db
def sorted_by_score_ascending(how_many_scores, name_scores_list):
db = []
[db.append([x[0], x[1]]) for x in name_scores_list]
db = sorted(db, key=lambda x: x[1], reve... |
67816c8a79b5e822ce1c806967b2e42d5471e71c | BoWarburton/DS-Unit-3-Sprint-2-SQL-and-Databases | /sql/rpg_queries.py | 2,540 | 4.125 | 4 | #!/usr/bin/env Python
import sqlite3
# 1st connect to db
conn = sqlite3.connect('rpg_db.sqlite3')
# 2nd make a cursor
cursor = conn.cursor()
# 3rd execute SQL as Python string
# create_statement = "CREATE TABLE pizza (name varchar(30), size int, pepperoni int, pineapple int);"
# cursor.execute(create_statement)
# in... |
eda86af7f573ed46374bd5b998081c781d067be5 | maleckim/machine-learning | /svm-classifier.py | 1,476 | 3.875 | 4 | import pandas as pd
import numpy as np
from sklearn import svm, datasets
import matplotlib.pyplot as plt
# svm or supervised machine learning can be used for both regression and classification the idea behind SVM
# is to plot each data item as a point in n-dimensional space with the value of each feature being the val... |
e1e17d9692b5c60d82086c64a002951dd67ffb91 | MyoMyoCU/Python-Exercises | /ex5.py | 680 | 4.0625 | 4 | #More Variables and Printing
#exercise5 embedded variables in string
my_name = ' Myo Myo '
my_age = 22
my_height = 60 # inches
my_weight = 100 #lbs
my_eyes = 'Brown '
my_teeth = 'White'
my_hair = 'Long Black '
print (f"Let's talk about {my_name}." )
print (f"She's {my_height} inches tall.")
print (f"She's {my_w... |
1af8668fec45dbb1de80096be570c1eb706b7f88 | PhantomShift/pygame-platformer | /src/instance.py | 3,084 | 3.875 | 4 | from typing import Union
classes = {}
class Instance():
"""
Root class of all parent-child objects
"""
def __init_subclass__(cls, class_name, **kwargs):
super().__init_subclass__(**kwargs)
cls.class_name = class_name
classes[class_name] = cls
def __init__(self, parent=None)... |
a364bac47412c9c2b63ed60b17e1dbe29a4db3fd | surekhaw/jtc_class_code | /class_scripts/bootcamp_scripts/list_practice.py | 1,155 | 4.21875 | 4 | # make a grocery list
# lists have particular order
groceries = ['eggs', 'meat', 'pasta']
print(groceries)
print(type(groceries))
groceries = ['eggs', 'meat' 'pasta']
print(groceries)
# add items to end of list with .append
groceries.append(4.0)
groceries.append('kumquat')
groceries.append('potato')
groceries.append(... |
99adba8192a06d528c721560339cab06d52b1cb9 | JoseBieco/Emprestimo-por-RA | /BD/TesteBD.py | 1,152 | 3.5 | 4 | import sqlite3
# Teste Switch lambda
def opcoes(op, conn, cursor):
cases = {
1: lambda: cadastrar(conn, cursor),
2: lambda: listar(cursor),
}
cases.get(op, lambda: print("\nOpção inválida!\n"))()
def menuOpcoes():
print("\t--- Menu ---")
print("1 - Cadastrar")
print("2 - Lista... |
e273ddd854f5170c592d25abee145b90c799a713 | Lucas-HMSC/curso-python3 | /#083 - Validando expressões matemáticas.py | 416 | 4.03125 | 4 | expressao = list()
contA = contB = 0
conta = False
expressao.append(input('Digite uma expressão matemática: '))
for letra in expressao:
for l in letra:
if l in '+-*/':
conta = True
elif l in '(':
contA += 1
elif l in ')':
contB += 1
if contA == contB and ... |
0fb7e07da968ef830f3d88d3a195b53f4cee7ee8 | pedrovs16/PythonEx | /ex073.py | 409 | 3.828125 | 4 | tabela = ('Flamengo', 'Cruzeiro', 'Figueirense', 'Chapecoense', 'Fluminense', 'Avai', 'Santos', 'Bragantino', 'Gremio')
print(f'A ordem na tabela é {tabela}.')
print(f'A tabela em ordem alfabética é {sorted(tabela)}.' )
print(f'Os primerios 5 times da tabela são {tabela[:5]}.')
print(f'Os ultimos 4 times da tabela são... |
c9a528a238df192a7ef416fa03e6421c53a50316 | Mahay316/Python-Assignment | /Exercise/0325/copy_file.py | 486 | 3.84375 | 4 | # 练习:将一个文件夹下的文件复制到另一个文件夹中
import os
# 该函数将覆盖dst目录下的已有同名文件
def copy(src, dst):
fileList = os.listdir(src)
for f in fileList:
sf = os.path.join(src, f)
df = os.path.join(dst, f)
if os.path.isfile(sf):
with open(sf, 'rb') as f1, open(df, 'wb') as f2:
for line i... |
2877198745a30538c7cb0464e3c38b1e8131f717 | mocusez/XUTPracticals | /prac_01/Sequences.py | 1,189 | 3.96875 | 4 | MENU = """E - Show the even numbers from x to y
O - Show the odd numbers from x to y
S - Show the squares from x to y
Q - Quit"""
print(MENU)
choice = input(">>> ").upper()
while choice != "Q":
if choice == "E":
print("Input the number X and Y")
x, y = input().split()
x = int(x)
y =... |
56860e37d3e49356d240ec68504c6fc08aae388c | gittenberg/rosalind | /Rabbits and Recurrence Relations.py | 179 | 3.578125 | 4 | def LinearFibonacci(n, k):
fn = f1 = f2 = 1
for x in range(2, n):
fn = f1 + k * f2
f2, f1 = f1, fn
return fn
n = 31
k = 4
print(LinearFibonacci(n, k)) |
c5b204d597874106e91b508d7e4518b7a39b6c17 | sameer-h/ENGR102 | /Lab04bMathPractice.py | 1,060 | 3.859375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 22 17:59:59 2019
By submitting this assignment , I agree to the following :
"Aggies do not lie , cheat , or steal , or tolerate those who do ."
"I have not given or received any unauthorized aid on this assignment ."
Names: Sameer Hussain
ENGR 102... |
43c16f5ed756e175104f128b276762c76012fba7 | Mannuel25/ROCK_PAPER_SCISSORS_GAME_VERSION_2.0 | /get_player_username.py | 1,832 | 4 | 4 | import string
from number_of_players import numberOfPlayers
def PlayerUsername(serverRooms):
"""
Gets each player's username
:return : None
"""
no_of_players = numberOfPlayers()
print('\nEnter a valid username that conforms to the following rules:')
print('\t+ Minimum length is 5')
print('\t+ Maxim... |
95f9790babefb0f88534d199b0bd4757d8a42f11 | pratian-pyclub/task-1-c | /word_magic.py | 1,343 | 3.890625 | 4 | import re
WILDCARD = '?'
WILDCARD_PATTERN = '\\' + WILDCARD
class WordMagic():
def __init__(self, tile, word):
"""Initialize WordMagic object with tile and word values"""
self.tile = tile
self.word = word
def can_create(self):
"""Return a boolean value if given tile can create ... |
5f83fdd764f87cccec506c22cfe6afcc97cab0f5 | Nihilnia/100daysOfCodePy | /fibonacci Sequence.py | 473 | 4.1875 | 4 | #Fibonacci Sequence
# 1,1,2,3,5,8,13,...
# an example with 1 t0 20
fibonacciList = [0, 1]
key = 0
actualResult = 1
print(actualResult)
for f in range(1, 21):
actualResult = fibonacciList[key] + fibonacciList[key + 1]
print(actualResult)
fibonacciList.append(actualResult)
key += 1
#... |
d7db6fadcceb8694a6ac88e09d4ecba961147c4d | henrywallawalla/word_games | /word_games.py | 440 | 3.6875 | 4 | """
with open("scrabble.txt", 'r') as f:
count = 0
for line in f:
if count > 5:
break
print(line)
count += 1
"""
def value(word):
my_dict = {'a':1,"b":3,"c":3,"d":2,'e':1,'f':4,'g':2,'h':4,'i':1,'j':8 ,'k':5,'l':1,'m':3,'n':1,'o':1,'p':3,'q':10,'r':1,'s':1,'t': 1,'u':1,'v':4,'w':4,'x':8,'y':4,'z':10}
valu... |
e062601d80137d8915866b18dd92e6a6f5097e67 | zosopick/mathwithpython1 | /Excersises/Chapter 7/3. Area Between Two Curves.py | 1,358 | 4.28125 | 4 | '''
Your challenge is to write a program that will allow the user to input any two single-variable
functions of x and print the enclosed area between the two. The program should make it clear that
the first function entered should be the upper function and it should also asl for the values of
x between which to f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.