blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
473b2d32e7aca4f9b4f5850ce767331190f1ab47 | pcmason/Automate-the-Boring-Stuff-in-Python | /Chapter 7 - Pattern Matching with Regular Expressions/dateDetection.py | 2,067 | 4.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun May 2 17:27:33 2021
@author: paulmason
program that detects valid dates in the format of DD/MM/YYYY
"""
#first import the regex module
import re
#create the date regex
dateRegex = re.compile(r'(\d\d)/(\d\d)/(\d\d\d\d)')
#search for a regex object
mo ... | true |
27c529bd1c70f36cf550bf53b2333c05681c6b50 | sparkle6596/python-base | /pythonProject/function/calculator using function.py | 519 | 4.15625 | 4 | num1=float(input("enter number1"))
num2=float(input("enter number2"))
choice=(input("enter your choice"))
def add(num1,num2):
sum=num1+num2
print(sum)
def sub(num1,num2):
sub=num1-num2
print(sub)
def mul(num1,num2):
mul=num1*num2
print(mul)
def division(num1,num2):
division=num1/num2
pri... | false |
065bb60114d3f78139202df70c4e4ca23ddde974 | saikatsengupta89/PracPy | /BreakContinuePass.py | 667 | 4.125 | 4 | #to showcase break statement
x= int(input("How many candies you want? "))
available_candies=5
i=1
while (i<=x):
print ("Candy")
i=i+1
if (i>available_candies):
print("There were only 5 candies available")
break
print("Bye")
#print all values from 1 to 100 but skip those are divi... | true |
e4af094f69a9d508f26145e5d56913c88d8e86ad | saikatsengupta89/PracPy | /class_inherit_constructor.py | 1,420 | 4.46875 | 4 | # IF YOU CREATE OBJECT OF SUB CLASS IT EILL FIRST TRY TO FIND INIT OF SUB CLASS
# IF IT IS NOT FOUND THEN IT WILL CALL INIT OF SUPER CLASS
#
class A:
def __init__(self):
print ("This is from constructor A")
def feature1(self):
print ("Feature1A is working fine")
def feature2(se... | true |
90374fa7c243c334e5e8728a8a380f3d84ca1c99 | saikatsengupta89/PracPy | /HCK_Calender.py | 725 | 4.34375 | 4 | import calendar
def which_day(day_str):
month, day, year= day_str.split(" ")
if (int(year) < 2000 or int(year) > 3000):
print("INVALID")
else:
weekday= calendar.weekday(int(year), int(month), int(day))
if(weekday==0):
print("Monday")
elif (weekday==1):
... | false |
da1e1cf498dea793b77f216f80969d1dffbe4631 | handes2019/Python | /hm_08_综合案例_猜拳游戏.py | 649 | 4.28125 | 4 | """
1、出拳
玩家:手动输入
电脑:1、固定:剪刀;2、随机
2、判断输赢
2.1 玩家获胜
2.2 平局
2.3 电脑获胜
"""
# 1.出拳
import random
# 玩家
player = int(input('请出拳: 0 -- 拳头; 1 -- 剪刀; 2 -- 布; '))
# 电脑
computer = random.randint(0, 2)
print(computer)
# 2. 判断输赢
# 玩家获胜
if ((player == 0) and (computer == 1)) or ((player == 1) and (computer == 2))... | false |
8119dc127f1f9b1a05bb1890769527bb08f40d46 | m-tranter/cathedral | /python/Y8/hangman.py | 1,442 | 4.125 | 4 | # hangman.py - simple hangman game
from random import *
def main():
WORDS = ['acorn', 'apple', 'apricot', 'grape', 'grapefruit',
'kiwi', 'lemon', 'mango', 'melon', 'orange', 'peach',
'pear', 'pineapple', 'raspberry', 'satsuma']
# pick a word randomly
word = choice(WO... | true |
28572191a4f31cf43fd927dca3e721ce4aff03d6 | kevmo/pyalgo | /guttag/031.py | 618 | 4.21875 | 4 | # INSTRUCTIONS
# input: integer
# output: root and power such that 0 < pwr < 6 and
# root**pwr = integer
from sys import argv
user_number = int(argv[1])
def find_root_and_power(num):
"""
Input: num
Returns a root, power such that power is 2 and 5,
inclusive, and root**power = num.
"""
root ... | true |
4c5e94f7469efc1849249ab4c47050a2ff62bbf3 | moayadalhaj/data-structures-and-algorithms401 | /challenges/stack-queue-pseudo/stack_queue_pseudo/stack_queue_pseudo.py | 2,378 | 4.40625 | 4 | class Node:
def __init__(self, value):
self.value = value
self.next = None
class Stack:
"""
create a stack class that containes three methods
push: to add a new node at the top of stack
pop: to delete the top node in the stack
peek: to return the value of top node if it exist
... | true |
74e25d370002de7de1af58c8d519a445974211db | miklashevichaleksandr/lesson2 | /age.py | 413 | 4.125 | 4 | user_age = input('Введите ваш возраст: ')
user_age = int(user_age)
if user_age <= 6:
print ('Вам нужно учиться в детском саду')
elif 6 < user_age <= 17:
print('Вам нужно учиться в школе')
elif 17 < user_age <= 23:
print('Вам нужно учиться в ВУЗе')
elif user_age > 23:
print('Вам нужно работать') | false |
022ac59fc09a1e47b58038fc2b2c081da84ec48a | maniiii2/PSP-LAB-PYTHON- | /python/condition_demo.py | 367 | 4.1875 | 4 | #Conditional statements
#using if statement find the largest among two numbers
x=int(input("enter first number"))
print("x=",x)
print(type(x))
y=int(input("enter second number"))
print("y=",y)
print(type(y))
if x>y:
print("x is greater than y")
elif x==y:
print("x is equal to y")
else:
prin... | true |
ec9d5a106d1b21e409890b52b34f0c233f17c2e5 | thtay/Algorithms_and_DataStructure | /CrackingCodingInterview_Python/Arrays_and_Strings/stringComp.py | 1,251 | 4.1875 | 4 | '''
String compression: Implement a method to perform basic string compression using the
counts of repeated characters. For example, the string aabcccccaa would be a2b1c5a3.
If the "compressed" string would not become smaller than the orignal string, your
method should return the original string. You can assume the st... | true |
d74ddb75db7228a67bdab656e47e54523277ac5d | kagomesakura/palindrome | /pal.py | 291 | 4.21875 | 4 | def check_palindrome(string):
half_len = len(string) // 2 #loop through half the string
for i in range(half_len):
if string[i] != string[len(string)-1-i]:
return False
return True
user_input = input('what is your word? ')
print(check_palindrome(user_input))
| true |
0a60c23622abd6a9c4a6348054f54b08484719ef | chudichen/algorithm | /linked_list/reverse_list.py | 859 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
反转链表
解题思路将使用虚拟before指针,将head的值依次传递给before,最终形成反转链表。
https://leetcode.com/explore/featured/card/recursion-i/251/scenario-i-recurrence-relation/2378/
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Sol... | false |
23a92b7be84aea5b82f891cc5eb99f807c3f0e49 | dhilanb/snakifywork | /Unit 1 and 2 Quiz/Problem5.py | 280 | 4.125 | 4 | A= int(input("How many feet does a nail go up during the day? "))
B= int(input("How many feet does the snail fall at night? "))
H= int(input("How high would you like the snail to go up? "))
days= H/(A-B)
print("It will take the snail "+str(days)+" days to go up "+str(H)+" feet.") | true |
fe732b17a297b599562ad04b0f19832c1e2fdeaf | carlita98/MapReduce-Programming | /1.Distributed greed/P1_mapper.py | 569 | 4.1875 | 4 | #!/usr/bin/python
# Filtering parttern: It evaluates each line separately and decides,
# based on whether or not it contains a given word if it should stay or go.
# In particular this is the Distributed Grep example.
# Mapper: print a line only if it contains a given word
import sys
import re
searchedWo... | true |
0b070f64a2cb7dfa6e30f39dd56909c8161f7b85 | ajaymonga20/Projects2016-2017 | /question2.py | 1,698 | 4.53125 | 5 | # AJAY MONGA -- QUESTION 2 -- COM SCI TEST -- FEBRUARY 14, 2017
# imports
# Nothing to Import
# Functions
def caught_speeding(speed, birthday):
if (speed <= 60) and (birthday == False): # Returns 0 if the speed is less than 60
return 0
elif (speed >= 61) and (speed <= 80) and (birthday == False): # If the ... | true |
da0c154b6829240f2f583aac92f8d213b4802a78 | Rufaidah/TestBootcampArkademy9 | /PrintPattern.py | 558 | 4.25 | 4 | side = int(input("Masukkan sisi persegi : "))
def drawImage(side):
# row
for i in range(side):
# column
for j in range(side):
if (i == (side - 1) / 2) or (j == (side - 1) / 2) \
or (i | j == 0) or (i == 0 and j == side - 1) \
or (i == side - 1... | false |
f050bb18b1a8914af117e64b15d22d2e2b06a422 | nsatterfield2019/Notes | /Week 8_Plotting.py | 651 | 4.25 | 4 | # PLOTTING (withmathploitlib)
import matplotlib.pyplot as plt
plt.figure(1) # creates a new window
plt.plot([1, 2, 3, 4]) # if there is no x axis, it just gives index 0, 1, 2...
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.figure(2, facecolor ='limegreen') # opens up a new window/figure
x = [x for x in range(10)]
y ... | true |
da762ad4794c151ea8f9d3c9133d336b974da541 | matt-ankerson/ads | /queues/supermarket_model_1.py | 2,103 | 4.1875 | 4 | from queue import Queue
from customer import Customer
import random as r
# Author: Matt Ankerson
# Date: 15 August 2015
# This script models queue behaviour at a supermarket.
# The scenario is: 10 checkouts, a customer selects a checkout at random.
class SuperMarket(object):
def __init__(self):
r.se... | true |
e6eb97080ddf47dda39b56673e6d47b390fe705a | GiovanniSinosini/cycle_condictions | /area_peri.py | 269 | 4.375 | 4 |
pi = 3.1415
# Calculator perimeter and area
radius = float(input("Enter radius value (in centimeters): "))
area = pi * (radius **2)
perimeter = 2 * pi * radius
print("The area value is:{:.2f}".format(area))
print( "The perimeter value is:{:.2f}".format(perimeter)) | true |
1a4aa8ce1b0ea42467a39d3c2f422f2465037f9b | GiovanniSinosini/cycle_condictions | /pythagorean_theorem.py | 504 | 4.46875 | 4 |
import math
adjacent = float(input ("Enter the value of the side adjacent: "))
opposite = float(input("Enter the value of the side opposite: "))
#hypotenuse = math.sqrt((math.pow(adjacent, 2) + math.pow(opposite,2)))
#print ("Hypotenuse has a value of: ", hypotenuse)
#hypotenuse = ((adjacent ** 2) + (opposite ** ... | false |
03347d591443192c119d3fb82f4f4712279ebb62 | Parkduksung/study-python | /chapter/chapter1,2,3.py | 1,300 | 4.28125 | 4 | # chapter1,2,3,4,5 확인문제.
#--------------chapter 1-----------------
# 1-1번
print("Hello Python")
#--------------chapter 2-----------------
print("# 연습문제")
print("\\\\\\\\") # \ 4개만 나옴.
print("-" * 8) # - 8번 찍힘.
print("abcde"[1]) # b
print("abcde"[1:]) # bcde
print("abcde"[1:2]) # b
print("abcde"[:1])... | false |
b844861db93e2d99d345d5b0e83ef01a88622fb2 | mwharmon1/UnitTestStudentClass | /test/test_student.py | 1,875 | 4.28125 | 4 | """
Author: Michael Harmon
Last Date Modified: 10/28/2019
Description: These unit tests will test the Student class constructors and functionality
"""
import unittest
from class_definitions import student as s
class MyTestCase(unittest.TestCase):
def setUp(self):
self.student = s.Student('Harmon', 'Mich... | true |
93193ffd4d3a9d84cda21227724b8d7214285958 | Jovan-Popovic/django_developers_lab | /predavanje-01/oo.py | 1,059 | 4.125 | 4 | from copy import deepcopy
class Animal():
number_of_animals = 0
def __init__(self, latin_name, birth_age, weight, location):
self.latin_name = latin_name
self.birth_age = birth_age
self.weight = weight
self.__location = location
Animal.number_of_animals += 1
... | false |
010d035dd41d553525cb4580569679b03412378e | durgareddy577/python | /python_programmes/string3.py | 740 | 4.28125 | 4 | name="durga reddy";
name1="DURGA REDDY";
sentence="1abc2abc3abc4abc5";
sentence1="this is durga reddy from banglore";
print(len(name)); #to find the length of the string
print(name.upper()); #to covert lower case latter to uppercase latter
print(name1.lower()) #TO CONVERT UPPER CASE LATTER TO LOWERCASE LATTERS
p... | false |
08e693a2fbd53015bf7834908ee32ce141e8db99 | SaneStreet/challenge-100 | /challenge105/challenge105.py | 896 | 4.1875 | 4 | """
To use the python script in Command Prompt:
Write 'python your_file_name.py'
Example: 'python challenge101.py'
"""
# imports the 'month_name' functionality from the calendar module
from calendar import month_name
# function with int as parameter
def MonthName(number):
# variable holding the name of the month fr... | true |
2a53348c85e88768fd75baa03fa1b7232a4906d7 | yjthay/Leetcode | /63.py | 1,835 | 4.375 | 4 | '''
63. Unique Paths II
Medium
862
120
Favorite
Share
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram ... | true |
5bed340e0c8961445a0a0f3b577f1d386be6639d | gabrielrnascimento/calculadora | /calculadora_v1.py | 1,267 | 4.3125 | 4 | # Calculadora em Python
print("\n******************* Python Calculator *******************")
def add(x,y):
return x + y
def subtract(x,y):
return x - y
def multiply(x,y):
return x * y
def divide(x,y):
return x / y
print ('\nSelecione o número da opção desejada:')
print ('1 - Soma')
print ('2 - Subtração')
p... | false |
169c8d5734e4b1e190cc3af9e7c1c47f9e00111a | alimulyukov/Course_Work_2021 | /ConVolCylStep4.py | 1,218 | 4.1875 | 4 | import math
print("\n\tThe volume of a Cylinder is:")
print("\n\t\t\tV = \u03C0 \u00D7 radius\u00B2 \u00D7 height")
print("\n\tThis program will take as input the radius and height")
print("\tand print the volume.")
file = open("data.txt","a") #w,r,a
name = input("\n\tWhat is your name: ")
radius = 1
height = 1
w... | true |
a82fa240bd47e700230e5798dfdb882f29888208 | eldadpuzach/MyPythonProjects | /Functions/Display Calendar.py | 303 | 4.46875 | 4 | # Python program to display calendar of given month of the year
# import module
import calendar
yy = 2018
mm = 10
# To ask month and year from the user
# yy = int(input("Enter year: "))
# mm = int(input("Enter month: "))
# display the calendar
for i in range(1, 13):
print(calendar.month(yy, i)) | true |
73a3a32ed53c506ee8c65ed16230c58dc15e9848 | coretx09/pythons21 | /10.list_method.py | 2,133 | 4.71875 | 5 | """
les List sont des variables modifiables, dans laquelle on peut mettre plusieurs autres variables
et effectuer les operations suivantes:
"""
numeros = [7, 9, 3, 2, 8] # une liste
print(f"la liste: {numeros}")
print(f"{numeros[0]} le premier element de la liste") # affiche l'element se trouvant a l'index i
numer... | false |
874eb33018e94ed35c455f77dec7e86842d4351a | lilliansun/cssi_2018_intro | /python/python-testing/fizzbuzz.py | 570 | 4.34375 | 4 | """my implementation of fizzbuzz"""
def fizz_buzz(num):
"""Prints different words for certain natural numbers
This function prints out fizz when a number is divisible by 3, buzz when
divisible by 5, and fizzbuzz when divisible by both.
Args:
num: (int) The number to convert based on fizzbuzz r... | true |
582b693640f4e32601b7b1a7f34049218cbba291 | sreehari333/pdf-no-3 | /to check male or female.py | 379 | 4.40625 | 4 | gender = input("Please enter your Gender : ")
if (gender == "M" or gender == "m" or gender == "Male" or gender == "male"):
print("The gender in Male")
elif (gender == "F" or gender == "f" or gender == "FeMale" or gender == "Female" or gender == "feMale" or gender == "female"):
print("The gender is Female"... | true |
6d78a8beb5805d430f4470b07415f09a6d713753 | naresh3736-eng/python-interview-problems | /trees/binaryTree_is_fullBinaryTree.py | 2,056 | 4.1875 | 4 | class Node:
def __init__(self, key):
self.key = key
self.leftchild = None
self.rightchild = None
# using recursion
def isFullBT_recursion(root):
if root is None:
return None
if root.leftchild is None and root.rightchild is None:
return True
if root.leftchild ... | true |
62ebadffa4205282a3fb81a7ddd679bf8da0dc94 | snekhasri/spring.py | /spring.py | 832 | 4.34375 | 4 | import turtle as t
#importing the module as "t"
t.bgcolor("green")
def spiral_shape(p,c):
#creating a function with parameters "p" and "c"
if p > 0:
#if the p is less than 0,
t.forward(p)
#moving the turtle forward at p units
t.right(c)
#setting the turtle right at an angle of c
spiral_shape(p-5,c)
#callin... | true |
c5a328137b59adfa9e23b295e695a2d53026e7e6 | Naveen8282/python-code | /palyndrome.py | 230 | 4.15625 | 4 | def IsPalyndrome(input1):
txt = input1[::-1]
if txt == input1:
return "yes"
else:
return "no"
str1=str(input("enter the string: "))
print ("is the string %s Palyndrome? %s" % (str1,IsPalyndrome(str1))) | true |
5b8b60e383c8ad3b9597a0774b7c55706fcc0497 | acbahr/Python-Practice-Projects | /magic_8_ball_gui.py | 1,524 | 4.3125 | 4 | # 1. Simulate a magic 8-ball.
# 2. Allow the user to enter their question.
# 3. Display an in progress message(i.e. "thinking").
# 4. Create 20 responses, and show a random response.
# 5. Allow the user to ask another question or quit.
# Bonus:
# - Add a gui.
# - It must have box for users to enter the question.
# - It... | true |
bcedd8033fc9cbef7b282c0433f010472d32f10c | longy1/python-elib | /python_cookbook/04_Iterator_and_Generator/02_proxy_iterator.py | 611 | 4.53125 | 5 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
implement __iter__() to return iterator object
"""
# 可迭代对象只需实现__next__(), 此例借助了list的实现
class Node:
def __init__(self, value):
self._value = value
self._children = []
def add_child(self, node):
self._children.append(node)
def __repr__... | false |
37c3e583c372fc2adbec60ca23e524fa9d4de0fc | dfrog3/pythonClass | /python/week 1/three_sort_david.py | 1,772 | 4.1875 | 4 | print("Hello, I will sort three integers for you.\nPlease enter the first integer now")
firstNumber = int(input())
print("Thank you.\nPlease enter the second integer.")
secondNumber = int(input())
print("Thank you.\n please eneter the last integer.")
thirdNumber = int(input())
#fills starting variables
if firstNumber <... | true |
1e04b2e77b982dbea75275781f2ed4937dbdca86 | k-unker/codewars_katas | /where_is_my_parent.py | 1,351 | 4.21875 | 4 | #!/usr/bin/env python3
'''
Mothers arranged dance party for children in school.
On that party there are only mothers and their children.
All are having great fun on dancing floor when suddenly
all lights went out.Its dark night and no one can see
eachother.But you were flying nearby and you can see
in the dark and ... | true |
0fd5a273d72beb9bf7cbc4c663f13410a4aeb881 | prkapadnis/Python | /Programs/eighth.py | 440 | 4.21875 | 4 | """
Reverse a number
"""
number = int(input("Enter the number:"))
reverse = 0
if number < 0:
number = number * (-1)
while number != 0:
remainder = number % 10
reverse = reverse * 10 + remainder
number = number // 10
print(-reverse)
else :
while number != 0:
remainder ... | true |
b3ed3b8ea862043d0d89d77bc1fceb90325acabe | prkapadnis/Python | /Set.py | 620 | 4.1875 | 4 | myset = set()
print(type(myset))
myset = {1,2,3,4,5}
print(myset)
#built in function
myset.add(2)# This does not made any change because set don't allow the duplicate values
print(myset)
myset.remove(2)
print("After removing 2:", myset)
# print("Using pop() function: ",myset.pop())
print(myset)
second_set = {3,4,5,6... | true |
c553606397136f91a2ad94d3c48c0f5d0f999a5b | prkapadnis/Python | /OOP/Class_var.py | 1,797 | 4.25 | 4 | """
Difference between class variable and Instance variable
Instance Variable:
-The Instance variable is unique for each instance
-If we changed the class variable for specific instance then it will create a new
instance variable for that instance
Class Variable:
The class v... | true |
4c55155e0f66164f9f1512cb51c007b23234a1be | prkapadnis/Python | /Data Structure/Linked List/SinglyLinkedList.py | 2,746 | 4.15625 | 4 | class Node:
def __init__(self, data): # defination of Node
self.data = data
self.next_node = None
class LinkedList:
def __init__(self):
self.head = None
self.size = 0
def reverse(self):
privious = None
current = self.head
next = None
wh... | true |
48db87ee9b1285a6b269caba3b64b40f9ea89035 | prkapadnis/Python | /File/second.py | 896 | 4.40625 | 4 | """
write() function:
- The Write function writes the specified text into the file.
- Where the specified text is inserted is depends on the file mode and stram position.
- if 'a' is a file mode then it well be inserted at the stream position and default is
end of the file.
... | true |
7ca93f1f2fdf8f757c2206e747681e600453d93b | prkapadnis/Python | /Iterables/Iterable.py | 1,178 | 4.34375 | 4 | """
Iterable : Iterable are objects that are capable of returning their member one at a time
means in short anything we can liip over is an iterable.
Iterator : Iterable are objects which are representing the stream of data that is iterable.
iterator creates something iterat... | true |
2a06954878ad58139831283b2ec6ec0a6cb9ec74 | marciniakdaw/Python-Udemy | /BMI calculator.py | 519 | 4.25 | 4 | height = float(input("enter your height in m: "))
weight = float(input("enter your weight in kg: "))
BMI_score=round(weight/height**2)
if BMI_score<19:
print(f"Your BMI is {BMI_score}, you are underweight.")
elif BMI_score<25:
print(f"Your BMI is {BMI_score}, you have a normal weight.")
elif BMI_score<30:
print... | true |
4b3f73baf3fbd69d6bf149be403396cea9222ab5 | j-tanner/Python.Assignments | /Assignment_8.4.py | 240 | 4.1875 | 4 | filename = input("Enter file name: ")
filehandle = open(filename)
wordlist = list()
for line in filehandle:
for words in line.split():
if words not in wordlist:
wordlist.append(words)
wordlist.sort()
print(wordlist)
| true |
ab72ffcb3709b58a3f84c1d70833507f67fbd8da | courses-learning/python-crash-course | /4-1_pizzas.py | 225 | 4.3125 | 4 | # Make a list of 3x types of pizza and use a for loop to print
pizzas = ['peperoni', 'hawian', 'meat feast']
for pizza in pizzas:
print(f"I like {pizza} pizza.")
print('I like pizza takeaway nearly as much as Indian!!!')
| true |
fc2476fdf4eef757a32e62cbebc4e225b63fe132 | courses-learning/python-crash-course | /5-6_stage_of_life.py | 469 | 4.15625 | 4 | def life_stage(age):
if age < 2:
return "a baby"
elif age >= 2 and age < 4:
return "a toddler"
elif age >= 4 and age < 13:
return "a kid"
elif age >= 13 and age < 20:
return "a teenager"
elif age >= 20 and age < 65:
return "an adult"
elif age >= 65:
... | false |
9704184ee7eda4aa6fcfd13a73861f640ad65780 | HanxianshengGame/PythonPrimer | /二.bookStudy/5_1_内置类型陷阱.py | 1,054 | 4.125 | 4 | # !/usr/bin/env Python2
# -*- coding: utf-8 -*-
# @Author : 得灵
# @FILE : 5_1内置类型陷阱.py
# @Time : 2021/1/6 18:49
# @Software : PyCharm
# @Introduce: This is
# [1] 赋值创建引用,而不是复制
L = [1,2, 3]
M = ['X', L, 'Y']
print(M)
L[1] = 0
print(M)
# 若非需要共享引用,请采纳分片和 copy/ copy.deepcopy
L = [1,2, 3]... | false |
af60ab371883f6f5e0590b7039684f5c8037b4a7 | HanxianshengGame/PythonPrimer | /一.videoStudy/8_元组.py | 1,226 | 4.3125 | 4 | # !/usr/bin/env Python3
# -*- coding: utf-8 -*-
# @Author : 得灵
# @FILE : 8_元组.py
# @Time : 2020/12/12 20:46
# @Software : PyCharm
# @Introduce: This is 元组
# 元组:
# 1. 不可变的序列,在创建之后不能做任何的修改
# 2. 用()创建元组类型,数据项用逗号来分割
# 3. 可以是任何的类型
# 4. 当元组中只有一个元素时,要加上逗号,不然解释器会当作整形来处理
# 5. 同样支持切片操作
first_tuple = () # 空元组
first_t... | false |
9bfc0342386bc8efdc7be6ac1f7988ae91ee022c | sacktock/practicals | /adspractical17extra.py | 2,981 | 4.34375 | 4 | #adspractical17extra.py
#algorithms and data structures practical week 17
#matthew johnson 22 february 2013, last revised 15 february 2018
#####################################################
"""an extra question that has nothing to do with the algorithms from the
lectures, but gives some practice on thinking about ... | true |
65264cc2e04a26029120617c562595610d3062eb | 4RCAN3/PyAlgo | /pyalgo/maths/prime.py | 413 | 4.21875 | 4 | '''
module for checking whether
a given number is prime or
not
'''
def prime(n: int):
'''
Checking if the number has any
factors in the range [2, sqrt(n)]
else it is prime
'''
if (n == 2):
return True
result = True
for i in range (2, int(n ** 0.5)):
if (n % i == 0):... | true |
102598ec16c86c089841565cdb47a942b795735a | 4RCAN3/PyAlgo | /pyalgo/maths/power.py | 928 | 4.375 | 4 | '''
module for calculating
x to the power y (x ** y)
efficiently
'''
def big_power(x: int, y: int, MOD = None):
'''
For calculating powers where
x and y are large numbers
'''
result = 1
if MOD is None:
while (y > 0):
if (y & 1):
result *= x
x ... | false |
29c43a96ac935c7f9da7b2bfbc227507d74fd02c | 4RCAN3/PyAlgo | /pyalgo/graph/bfs.py | 977 | 4.21875 | 4 | '''
module for implementation
of breadth first search
'''
def bfs(graph: list, start: int):
"""
Here 'graph' represents the adjacency list
of the graph, and 'start' represents the
node from which to start
"""
visited, queue = set(), [start]
while (queue):
vertex = queue.pop(0)
... | true |
800dc205db1402fb2c155c6d4ac5af0de549988d | niranjan2822/List | /Key Lists Summations.py | 1,147 | 4.21875 | 4 | # Key Lists Summations
# Sometimes, while working with Python Dictionaries, we can have problem in which we need to perform the replace of
# key with values with sum of all keys in values
'''
Input : {‘gfg’: [4, 6, 8], ‘is’: [9, 8, 2], ‘best’: [10, 3, 2]}
output : {‘gfg’: 18, ‘is’: 19, ‘best’: 15}
'''
# Method #1 :... | true |
382a8915e11e58f68d73b4451e9efaa294ff1ffb | niranjan2822/List | /Iterating two lists at once.py | 1,777 | 4.65625 | 5 | # Iterating two lists at once
# Sometimes, while working with Python list, we can have a problem in which we have to iterate over two list elements.
# Iterating one after another is an option, but it’s more cumbersome and a one-two liner is always recommended over
# that
'''
Input 1 : [4, 5, 3, 6, 2]
Input 2 : [7, ... | true |
4ffa4b3471cedec80b47c6408b8bf1318c28dc40 | siddbose97/maze | /DFS/maze.py | 1,240 | 4.15625 | 4 | #logic inspired by Christian Hill 2017
#create a cell class to instantiate cells within the grid which will house the maze
#every cell will have walls and a coordinate pair
class cell:
# create pairs of walls
wallPairs = {"N":"S", "S":"N", "E":"W", "W":"E"}
def __init__(self, x, y):
#give a wall ... | true |
8b589bdd3f9299888080234f814c617e111817c1 | Purushotamprasai/Python | /Rehaman/001_Basic_understanding/001_basic_syntax.py | 1,023 | 4.125 | 4 | #!/usr/bin/python
# the above line is shabang line ( path of python interpreter)
#single line comment ( by using hash character '#'
'''
We can comment multiple lines at a time
by using triple quotes
'''
# the below code understand for statement concept
'''
1---> single statemnt
'''
# a line which is having si... | true |
efe69eec4380f3041992e4b82eb1252f32876859 | Purushotamprasai/Python | /Rohith_Batch/Operator/Logical Operator/001_understand.py | 908 | 4.3125 | 4 | # this file is understand for logical operators
'''
Logical AND ---> and
---------------------
Defination :
-----------
if 1st input is false case then output is 1st input value
other wise 2nd input value is the output
Logical OR---> or
---------------------
Defination :
-----------
if 1st ... | true |
ad53e27408916456b808dea9bdc0662692a5fd24 | Purushotamprasai/Python | /Z.R/files/002_write.py | 355 | 4.125 | 4 | file_obj = open("readfile.txt","w")
'''
file opened as write mode
if the file is not existed 1st create then open it"
file is existed then removes previous data
and open as fresh file
if the is open as write mode
we cant use read methodes
'''
data =input("enter some data")
file_obj.write(data)
d =... | true |
72a0cc33029ff768a219bfe8517ed7793abfe467 | Purushotamprasai/Python | /Rohith_Batch/Operator/Relational/Bitwise_Even or Odd.py | 299 | 4.34375 | 4 | '''
Program : Find the Given number is Even or Odd using bitwise operator
Programmer : Rohit
'''
def main():
a = input('Enter a value: ')
if a&1==0:
print "Number is Even"
else:
print "Number is Odd"
if (__name__=="__main__"):
main()
| true |
6644874636bb8a22a6fb4cbb5519c82567e41561 | Purushotamprasai/Python | /Tarun/003_tuple_datatype.py | 605 | 4.25 | 4 | # list data type
var_l = ( 1, 2,4.5 ,"str")
# hetro genious datatype
print var_l # we are printing list of var_1 elements
print len(var_l) # no of elements in a list
print max(var_l) # maximum list element
print min(var_l) # minimum list element
print tuple("python")#('p','y','t','h','o','n')
# tuple... | false |
e1194fa52edbd9f140b0d048833b2fd13e6517ff | Purushotamprasai/Python | /hussain_mani/python_introduction/003_Python Basic Built-in function/Built_in_function_info.py | 1,541 | 4.21875 | 4 | # python Basic Built -in Function
'''
Function :-
---------------
-----> Function is a set of instructions for doing any one task
-----> there are two types
1. User Defined Function :-
---------------------------
The programmer can define function
def ----> user defined function
2. Built-in funct... | true |
041eb90a66c152abb9e581e4b2361686ec58b5bc | Purushotamprasai/Python | /Sai_Krishna/001_Python_Basic_Syntax/001_instruction.py | 935 | 4.34375 | 4 | # this is single line comment
'''
This is
multiple line comment
'''
# what is the use of the comment
'''
As a programmer we know what we are writing the script
By using comment
we can you can give brief explanation for any statment
'''
# statement
# single statement
#------> A single line which is hav... | false |
a57998b659eb1ad0d09749a74eb54a6a7db0e58c | TomiMustapha/Shleep | /week.py | 623 | 4.15625 | 4 | ## Week class
##
## Each week is a list of fixed size 7 of positive ints
## Represents a week in which we log hours of sleep
## We can then combine weeks into a matrix to be represented graphically
import numpy as np
class Week():
def __init__(self):
self.nodes = np.array([])
def in... | true |
97487f7c395f37af614556864394127eeeb006b7 | parker57/210CT | /week4/adv2_qs.py | 1,754 | 4.25 | 4 | ## Adapt the Quick Sort algorithm to find the mth smallest element out of a list of n integers, where m is
## read from the standard input.
## For example, when m = 5, your version of Quick Sort will output the 5th smallest element out of your
## input list.
import random
def quickselect(array, m):
... | true |
521e916bcc367920ddb63aedcd90e84e38ac7f42 | Anshul-GH/jupyter-notebooks | /UdemyPythonDS/DS_BinarySearchTree/Node.py | 2,982 | 4.46875 | 4 | # Defining the class Node
class Node(object):
# Construction for class Node
def __init__(self, data):
self.data = data
# defining both the child nodes as NULL for the head node
self.leftChild = None
self.rightChild = None
# Defining the insert function.
# 'data' contai... | true |
99467384dfdee08e2f5794af6db8e964807ccc95 | JFarina5/Python | /password_tester.py | 1,107 | 4.25 | 4 | """
This program takes a given user password and adds 'points' to that password,
then calculates the total amount of 'points'. The program will take the total
amount of points and then inform the user if they have a strong password or a
weak password.
"""
import re
def password_test():
value = 0
user_pass = ... | true |
8f8505622fbd3ab77638a28c71d98133d5980fa7 | JFarina5/Python | /palindrome_tester.py | 623 | 4.4375 | 4 | """
The purpose of this program is to test a string of text
and determine if that word is a palindrome.
"""
# Palindrome method, which disregards spaces in the user's input and reverses that string
# in order to test the input to see if it is a palindrome.
def palindrome():
string = input("Please insert a palindro... | true |
18b0a035d045cfdb818ecabd0c29fad2a166fa70 | ImLeosky/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/models/square.py | 2,164 | 4.28125 | 4 | #!/usr/bin/python3
"""
the class Square that inherits from Rectangle
"""
from models.rectangle import Rectangle
class Square(Rectangle):
"""
Class Square inherits from Rectangle
"""
def __init__(self, size, x=0, y=0, id=None):
"""
Class constructor
"""
width = size
... | true |
830e2ac7c2d5a8e558877538c644ff87a2747f3b | alammahbub/py_begin_oct | /5. list.py | 1,402 | 4.53125 | 5 | # list in python start with square brackets
# list can hold any kind of data
friends = ["asib","rony","sajia"]
print(friends)
# accessing list item with there index
print(friends[2]+" has index 2")
# accessing list from back or, as negative index
print(friends[-1]+" has index -1")
# Asigning new item in list by... | true |
2a6f7cbc33008d2a22ba3974e0e90201caab553a | marko-despotovic-bgd/python | /EndavaExercises/1_3_stringoperations.py | 381 | 4.34375 | 4 | # 1. Strings and Numbers
# 1.3. Write a console program that asks for a string and outputs string length
# as well as first and last three characters.
print('Please enter some string: ')
string = (input())
print('Length: {}\nFirst 3 chars: {}\nLast 3 chars: {}'.format(len(string),
... | true |
e21afb700a8297f49dc193bd9f7d5c72b5c95c07 | 4Empyre/Bootcamp-Python | /35python_bike/bike.py | 780 | 4.21875 | 4 | class Bike(object):
def __init__ (self, price, max_speed):
self.price = price
self.max_speed = max_speed
self.miles = 0
def displayInfo(self):
print "Price:",self.price,"Max Speed:",self.max_speed,"Miles:", self.miles
def ride(self):
self.miles += 10
... | true |
c2b4a96ee434e18f2be2f2758478331919d65582 | brucekaushik/basicblog | /apps/hello-world/valid-month.py | 1,189 | 4.4375 | 4 | # -----------
# User Instructions
#
# Modify the valid_month() function to verify
# whether the data a user enters is a valid
# month. If the passed in parameter 'month'
# is not a valid month, return None.
# If 'month' is a valid month, then return
# the name of the month with the first letter
# capitalized.
#
... | true |
84b2266797647b9933d5ca848251e60e19222bcf | cameronww7/Python-Workspace | /Python-Tutorials/Python-Object-Inheritance.py | 1,303 | 4.21875 | 4 | from __future__ import print_function
import math
# Python Object Inheritance
print("Python Object Inheritance")
class Shape(object):
def __init__(self):
self.color = "Red"
self.sides = 0
def calcArea(self):
return 0
class Quadrilateral(Shape):
def __init__(self, w, l, c):
... | false |
6dad3d3891bda5551a6e6a3f03a442236cf2a9ae | cameronww7/Python-Workspace | /Python-Bootcomp-Zero_To_Hero/Sec-14-Py-Adv_Modules/113-Py-ZippingAndUnzippingFiles.py | 2,175 | 4.1875 | 4 | from __future__ import print_function
import zipfile
import shutil
import os
"""
Prompt 113-Py-ZippingAndUnzippingFiles
"""
print("113-Py-ZippingAndUnzippingFiles")
"""
Unzipping and Zipping Files
As you are probably aware, files can be compressed to a zip format.
Often people use special programs on their computer... | true |
ec0cbb2d72776eedda8618778e642c7944080959 | cameronww7/Python-Workspace | /Python-Bootcomp-Zero_To_Hero/Sec-14-Py-Adv_Modules/106-Py-Date_Time.py | 1,964 | 4.40625 | 4 | from __future__ import print_function
import datetime
"""
Prompt 106-Py-Date_Time
"""
print("106-Py-Date_Time")
"""
datetime module
Python has the datetime module to help deal with timestamps in
your code. Time values are represented with the time class.
Times have attributes for hour, minute, second, and micros... | true |
47226b0ba22174336343d4f6fe2648d053ec8612 | cameronww7/Python-Workspace | /Python-Bootcomp-Zero_To_Hero/Sec-8-Py-OOP/66-OOP-Challenge.py | 2,257 | 4.3125 | 4 |
from __future__ import print_function
import math
"""
Prompt 66-OOP-Challenge
"""
print("66-OOP-Challenge")
"""
Object Oriented Programming Challenge
For this challenge, create a bank account class that has two attributes:
owner
balance
and two methods:
deposit
withdraw
As an added requirement, withdrawals may ... | true |
6e8687c78e8198d41807ef3bd1652efcf16bffe9 | romanitalian/romanitalian.github.io | /sections/python/spiral_matrix/VH7Isb3mRqUaaHCc_spiral-matrix-in-python.py | 1,751 | 4.28125 | 4 | #!/usr/bin/env python3
# http://runnable.com/VH7Isb3mRqUaaHCc/spiral-matrix-in-python
def change_direction(dx, dy):
# not allowed!3
if abs(dx+dy) != 1:
raise ValueError
if dy == 0:
return dy, dx
if dx == 0:
return -dy, dx
def print_spiral(N=5, M=6):
if N < 0 or M < 0:
... | true |
dff98da96027c42420440cdae33e55c3dcab539b | kelvinadams/PythonTheHardWay | /ex11.py | 386 | 4.40625 | 4 | # Python the Hard Way - Exercise 11
# prompts user for their age, height, and weight
print("How old are you?", end=' ')
age = input()
print("How tall are you?", end=' ')
height = input()
print("What is your weight?", end=' ')
weight = input()
# prints out the input in a new format
print(
f"Alrighty,... | true |
3932cf29243c102f8534f103365e4b8401934a96 | arelia/django-girls-blog | /intro/python_intro_part_one.py | 550 | 4.1875 | 4 | print("Hello, Django Girls!")
myInfo = {'firstName': 'Arelia', 'lastName': 'Jones'}
print("My name is " + myInfo['firstName'] + " " + myInfo['lastName'] + ".")
a = 4
b = 6
if a == 4:
print(" is greater than ")
elif b == 2:
print(" is less than ")
else:
print("I don't know the answer")
def hi():
print('Hi ther... | false |
b7fc72d816e4fbf3dad343eb6f7f2cf47847a7e7 | SujeethJinesh/Computational-Physics-Python | /Jinesh_HW1/Prob1.py | 414 | 4.1875 | 4 | import math
def ball_drop():
height = float(input("please input the height of the tower: ")) #This is how many meters tall the tower is
gravity = 9.81 #This is the acceleration (m/s^2) due to gravity near earth's surface
time = math.sqrt((2.0*height)/gravity) #derived from h = 1/2 gt^2 to solve for time
... | true |
f6146b7e9826f07bc27579b30a5b48abbc35be7a | SujeethJinesh/Computational-Physics-Python | /Jinesh_HW1/Prob2.py | 870 | 4.21875 | 4 | import math
def travel_time():
distance_from_planet = float(input("Enter distance from planet in light years: ")) #gets user input for light year distance
speed_of_craft = float(input("please enter speed as a fraction of c: ")) #gets speed of craft in terms of c from user
stationary_observer_time_years =... | true |
a037cc7c52fa60741d40e9ac8f715b9e3bd7cc02 | carolinemascarin/LPTHW | /ex5.py | 714 | 4.21875 | 4 | #Exercise 5
myname = 'Caroline Mascarin'
myage = 27
myheight = 175
myeyes = 'Black'
myteeth = 'White'
myhair = 'Brown'
print "Lets talk about %s." % myname
print "She is %d centimeters tall" %myheight
print "She's got %s eyes and %s hair" % (myeyes, myhair)
print "if I add %d and %d I get %d" % (myage, myheight, myag... | true |
99af0848e395225fbdfa555324a93e1f03ede662 | nlscng/ubiquitous-octo-robot | /p100/problem-196/MostOftenSubtreeSumBST.py | 1,563 | 4.125 | 4 | # This problem was asked by Apple.
#
# Given the root of a binary tree, find the most frequent subtree sum. The subtree sum of a node is the sum of all values under a node, including the node itself.
#
# For example, given the following tree:
#
# 5
# / \
# 2 -5
# Return 2 as it occurs twice: once as the left leaf, ... | true |
43dc120d758dd3a1d5c60582ce1df81c0a6a8459 | nlscng/ubiquitous-octo-robot | /p100/problem-188/PythonFunctionalDebug.py | 782 | 4.15625 | 4 | # This problem was asked by Google.
#
# What will this code print out?
#
# def make_functions():
# flist = []
#
# for i in [1, 2, 3]:
# def print_i():
# print(i)
# flist.append(print_i)
#
# return flist
#
# functions = make_functions()
# for f in functions:
# f()
# How can we... | true |
62ebf7681cc0f040b0ccb64d4c2218a1d2c5c7ad | nlscng/ubiquitous-octo-robot | /p000/problem-98/WordSearchPuzzle.py | 2,521 | 4.21875 | 4 | # This problem was asked by Coursera.
#
# Given a 2D board of characters and a word, find if the word exists in the grid.
#
# The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those
# horizontally or vertically neighboring. The same letter cell may not be used more than ... | true |
70bf93d87d438fffa829d69fb3b1eb615a5322a0 | nlscng/ubiquitous-octo-robot | /p000/problem-88/DivisionWithoutOperator.py | 546 | 4.21875 | 4 | # This question was asked by ContextLogic.
#
# Implement division of two positive integers without using the division, multiplication, or modulus operators.
# Return the quotient as an integer, ignoring the remainder.
def raw_division(n: int, m: int) -> int:
if n < m:
return raw_division(m, n)
quot, ... | true |
5a75a95a3a659a9a970c94aebfc13950730718a1 | nlscng/ubiquitous-octo-robot | /p000/problem-6/XorLinkedList.py | 1,961 | 4.1875 | 4 | # An XOR linked list is a more memory efficient doubly linked list. Instead of each node holding next and prev
# fields, it holds a field named both, which is an XOR of the next node and the previous node. Implement an XOR
# linked list; it has an add(element) which adds the element to the end, and a get(index) which r... | true |
ede2ca2fec4c1156fb877811d1f5274749299ea2 | nlscng/ubiquitous-octo-robot | /p000/problem-58/SearchInRotatedSortedArray.py | 1,415 | 4.15625 | 4 | # Good morning! Here's your coding interview problem for today.
#
# This problem was asked by Amazon.
#
# An sorted array of integers was rotated an unknown number of times.
#
# Given such an array, find the index of the element in the array in faster than linear time. If the element doesn't
# exist in the array, retur... | true |
c6d5c270f8a215c1b8d8060d15e4073d6339a8bb | nlscng/ubiquitous-octo-robot | /p000/problem-68/AttackingBishop.py | 1,467 | 4.28125 | 4 | # Good morning! Here's your coding interview problem for today.
#
# This problem was asked by Google.
#
# On our special chessboard, two bishops attack each other if they share the same diagonal. This includes bishops
# that have another bishop located between them, i.e. bishops can attack through pieces.
#
# You are g... | true |
5b4735c804aafaa74f3a0461bc53fb5befbc6093 | chandrikakurla/implementing-queue-with-array-space-efficient-way-in-python- | /qu_implement queue using array.py | 2,962 | 4.1875 | 4 | #class to implement queue
class Queue:
def __init__(self,size):
self.queue=[None] *size
self.front=-1
self.rear=-1
self.size=size
#function to check empty stack
def isEmpty(self):
if self.front==-1 and self.rear==-1:
return True
else:
... | true |
041e238b857fa33960c8f51c95e21d5fd2e4cf0d | lindajaracuaro/My-Chemical-Polymorphism | /My chemical polymorphism.py | 782 | 4.28125 | 4 | # Chemical polymorphism! In this program you'll have fun using chemistry and polymorphism. Add elements and create molecules.
class Atom:
def __init__(self, label):
self.label = label
def __add__(self, other):
# Return as a chemical composition
return self.label + other.label
def __repr__(sel... | true |
6b0f193dc597b8d5f02db807376a3a7f4f39bcdd | rowens794/intro-to-cs | /ps1/ps1.py | 599 | 4.125 | 4 |
portion_down_payment = .25
r = .04
annual_salary = float(input('what is your annual salary? '))
portion_saved = float(input('what portion of your salary will you save? '))
total_cost = float(input('how much does your dream house cost? '))
current_savings = 0
months = 0
print('pre loop')
print(current_savings)
print(... | true |
f18337a4c73ad850e323599b21a91263b75ce1d9 | JKH2124/jnh-diner-project-py | /diner_project.py | 2,157 | 4.40625 | 4 | # J & K's Diner
dinnerMenu = ['STEAK', '15', 'CHICKEN', '12', 'PORK', '11', 'SALAD', '12']
sidesMenu = ['FRIES', 'RICE', 'VEGGIES', 'SOUP', '1']
dinnerSelect = input("Please select an entree: ").upper()
if dinnerSelect == dinnerMenu[0]:
print("Excellent choice! The price for that entree is {}".format(dinnerMenu[1]... | true |
9cf2dec2e90b8164e3470892b68f38fe9bef4dd7 | EliksonBT/estcmp060- | /fibonacci-spiral-fractal.py | 1,970 | 4.46875 | 4 | # Programa em python para plotar a espiral
# fractal de fibonacci
import turtle
import math
def fiboPlot(n):
a = 0
b = 1
square_a = a
square_b = b
# Setando a cor da caneta para azul
x.pencolor("blue")
# Desenhando o primeiro quadrado
x.forward(b * factor)
x.left(90)
x.forwar... | false |
e645165c06b68fadc275ab51ed701a00887f5688 | Gaurav-Pande/DataStructures | /leetcode/graphs/add_search_trie.py | 1,636 | 4.15625 | 4 | # link: https://leetcode.com/problems/add-and-search-word-data-structure-design/
class TrieNode(object):
def __init__(self):
self.children = collections.defaultdict(TrieNode)
self.is_word=False
class WordDictionary(object):
def __init__(self):
"""
Initialize your data structure... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.